/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.sing.active.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.utils.BeanPropertyUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.gateway.active_gateway.constant.ActiveProductConstant;
import org.springblade.gateway.active_gateway.util.ActiveProductUtil;
import org.springblade.sing.active.entity.ActiveProductRecord;
import org.springblade.sing.active.service.IActiveProductRecordService;
import org.springblade.sing.active.vo.ActiveProductRecordVO;
import org.springblade.sing.active.wrapper.ActiveProductRecordWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 活动作品 控制器
 *
 * @author BladeX
 * @since 2021-11-10
 */
@RestController
@AllArgsConstructor
@RequestMapping("sing_active/activeproductrecord")
@Api(value = "活动作品", tags = "活动作品接口")
public class ActiveProductRecordController extends BladeController {

	private final IActiveProductRecordService activeProductRecordService;

	private final BladeRedis bladeRedis;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入activeProductRecord")
	public R<ActiveProductRecordVO> detail(ActiveProductRecord activeProductRecord) {

		ActiveProductRecord detail = activeProductRecordService.getOne(Condition.getQueryWrapper(activeProductRecord));

		if (detail != null){
			//获取排名
			String key = ActiveProductConstant.PRODUCT_SORT_CACHE_KEY.concat(":").concat(detail.getActiveId().toString());
			Long revrank = bladeRedis.zRevrank(key, detail.getId());

			ActiveProductRecordVO activeProductRecordVO = ActiveProductRecordWrapper.build().entityVO(detail);
			if (revrank != null){
				activeProductRecordVO.setRank(revrank + 1);
			}
			return R.data(activeProductRecordVO);
		}
			return R.data(null);
	}

	/**
	 * 分页 活动作品搜索
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入activeProductRecord")
	public R<IPage<ActiveProductRecordVO>> list(ActiveProductRecord activeProductRecord, Query query) {
		IPage<ActiveProductRecord> pages = activeProductRecordService.page(Condition.getPage(query), Condition.getQueryWrapper(activeProductRecord).lambda().orderByDesc(ActiveProductRecord::getHeatValue));
		return R.data(ActiveProductRecordWrapper.build(bladeRedis).pageVO(pages));
	}

	@GetMapping("/getMyTotalHeat")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "获取我获取的总热力值", notes = "传入activeProductRecord")
	public R getMyTotalHeat(ActiveProductRecord activeProductRecord, Query query) {
		QueryWrapper<ActiveProductRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("IFNULL(sum(heat_value),0) as totalHeat").lambda()
			.eq(ActiveProductRecord::getPhone, activeProductRecord.getPhone());
		Map<String, Object> map = activeProductRecordService.getMap(queryWrapper);
		BigDecimal totalHeat = (BigDecimal) map.get("totalHeat");
		return R.data(Optional.ofNullable(totalHeat).orElse(BigDecimal.ZERO));
	}

	/**
	 * 自定义分页 活动作品
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入activeProductRecord")
	public R<IPage<ActiveProductRecordVO>> page(ActiveProductRecordVO activeProductRecord, Query query) {
		IPage<ActiveProductRecordVO> pages = activeProductRecordService.selectActiveProductRecordPage(Condition.getPage(query), activeProductRecord);
		return R.data(pages);
	}

	/**
	 * 新增 活动作品
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入activeProductRecord")
	public R save(@Valid @RequestBody ActiveProductRecord activeProductRecord) {
		return R.status(activeProductRecordService.save(activeProductRecord));
	}

	/**
	 * 修改 活动作品
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入activeProductRecord")
	public R update(@Valid @RequestBody ActiveProductRecord activeProductRecord) {
		return R.status(activeProductRecordService.updateById(activeProductRecord));
	}

	/**
	 * 新增或修改 活动作品
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Transactional(rollbackFor = Exception.class)
	@ApiOperation(value = "新增或修改", notes = "传入activeProductRecord")
	public R submit(@Valid @RequestBody ActiveProductRecord activeProductRecord) {
		if(ObjectUtils.isEmpty(activeProductRecord.getProductNo())){
			//查询最大值
			Map<String, Object> map = activeProductRecordService.getMap(Wrappers.<ActiveProductRecord>query().select(new StringBuilder("IFNULL(max(")
					.append(BeanPropertyUtil.getFieldNameToUnder(ActiveProductRecord::getProductNo)).append("),0) as NO").toString())
				.eq(BeanPropertyUtil.getFieldNameToUnder(ActiveProductRecord::getActiveId), activeProductRecord.getActiveId()));
			activeProductRecord.setProductNo(Long.valueOf(MapUtil.getInt(map, "NO")+1));
		}
		return R.status(activeProductRecordService.saveOrUpdate(activeProductRecord) && ActiveProductUtil.addProductRank(activeProductRecord));
	}

	/**
	 * 删除 活动作品
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> longs = Func.toLongList(ids);
		List<ActiveProductRecord> activeProductRecords = activeProductRecordService.listByIds(longs);
		for (ActiveProductRecord activeProductRecord : activeProductRecords) {
			ActiveProductUtil.delProductRank(activeProductRecord);
		}
		return R.status(activeProductRecordService.deleteLogic(longs));
	}


}
