/*
 *      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.modules.guosen.production.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.guosen.activity.entity.Activity;
import org.springblade.modules.guosen.activity.service.IActivityService;
import org.springblade.modules.guosen.loginUser.entity.LoginUser;
import org.springblade.modules.guosen.loginUser.service.ILoginUserService;
import org.springblade.modules.guosen.production.entity.Production;
import org.springblade.modules.guosen.production.service.IProductionService;
import org.springblade.modules.guosen.production.vo.ProductionVO;
import org.springblade.modules.guosen.production.wrapper.ProductionWrapper;
import org.springblade.modules.guosen.rank.service.RankService;
import org.springblade.modules.guosen.userActivityStatistical.entity.UserActivityStatistical;
import org.springblade.modules.guosen.userActivityStatistical.service.IUserActivityStatisticalService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-06-16
 */
@RestController
@AllArgsConstructor
@RequestMapping("cyzh-production/production")
@Api(value = "报名", tags = "接口")
public class ProductionController extends BladeController {

	private final IProductionService productionService;

	@Resource
	private IActivityService activityService;
	@Resource
	private RankService rankService;
	@Resource
	private IUserActivityStatisticalService userActivityStatisticalService;
	@Resource
	private ILoginUserService loginUserService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入production")
	public R<ProductionVO> detail(Production production) {
		Production detail = productionService.getOne(Condition.getQueryWrapper(production));
		return R.data(ProductionWrapper.build(rankService).entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入production")
	public R<IPage<ProductionVO>> list(Production production, Query query) {
		IPage<Production> pages = productionService.page(Condition.getPage(query), Condition.getQueryWrapper(production).lambda().orderByDesc(Production::getHotValue));
		return R.data(ProductionWrapper.build(rankService).pageVO(pages));
	}


	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入production")
	public R<IPage<ProductionVO>> page(ProductionVO production, Query query) {
		IPage<ProductionVO> pages = productionService.selectProductionPage(Condition.getPage(query), production);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入production")
	public R save(@Valid @RequestBody Production production) {
		return R.status(productionService.save(production));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入production")
	public R update(@Valid @RequestBody Production production) {
		Long productionId = production.getId();
		Long userId = production.getUserId();
		Production serviceById = productionService.getById(productionId);

		//修改作品热力值
		if (serviceById != null && serviceById.getHotValue() != null && production.getHotValue().compareTo(serviceById.getHotValue()) != 0) {
			//增加的热力值
			BigDecimal subtract = production.getHotValue().subtract(serviceById.getHotValue());
			//获取活动id
			Long activityId = production.getActivityId();
			rankService.zSetRemove(activityId.toString(),productionId.toString(),1);
			rankService.addScore(activityId.toString(),productionId.toString(), Convert.toDouble(production.getHotValue()),1);
			rankService.addScore(activityId.toString(),userId.toString(), Convert.toDouble(subtract),0);
			//修改活动统计的数据
			UserActivityStatistical serviceOne = userActivityStatisticalService.getOne(Condition.getQueryWrapper(new UserActivityStatistical())
				.lambda().eq(UserActivityStatistical::getActivityId, activityId)
				.eq(UserActivityStatistical::getUserId, userId));
			serviceOne.setTotalHotValue(serviceOne.getTotalHotValue().add(subtract));
			userActivityStatisticalService.updateById(serviceOne);
			//修改个人总热力
			LoginUser loginUser = loginUserService.getById(userId);
			loginUser.setTotalHot(loginUser.getTotalHot().add(subtract));
			loginUserService.updateById(loginUser);
		}
		return R.status(productionService.updateById(production));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入production")
	public R submit(@Valid @RequestBody Production production) {
		return R.status(productionService.saveOrUpdate(production));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		return R.status(productionService.delete(idList));
	}

	/**
	 * 获取作品详情
	 */
	@GetMapping("/getProductDetail")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "获取作品详情", notes = "传入作品id,和查询者的userId")
	public R<ProductionVO> getProductDetail(Long id, Long userId) {
		ProductionVO productionVO = productionService.getProductDetail(id,userId);
		return R.data(productionVO);
	}

	/**
	 * 浏览作品
	 */
	@GetMapping("/visit")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "浏览作品", notes = "传入作品id")
	public R visit(Long id) {
		Production production = productionService.getById(id);
		Activity activity = activityService.getById(production.getActivityId());
		Integer visitBase = activity.getVisitBase();
		visitBase = visitBase == null ? 0 : visitBase;
		Integer visitTotal = production.getVisitTotal();
		Integer num= visitTotal == null || visitTotal==0? (visitBase+1) : (visitTotal + 1);
		production.setVisitTotal(num);
		return R.status(productionService.updateById(production));
	}

	/**
	 * 参赛
	 */
	@PostMapping("/create")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "参赛", notes = "传入production")
	public R create(@Valid @RequestBody Production production) {
		return productionService.create(production);
	}

	/**
	 * 排行榜
	 */
	@GetMapping("/rank")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "排行榜", notes = "传入activityId,榜单类型type")
	public R rank(Long activityId, String type) {
		Assert.notNull(activityId, "请输入活动id");
		//将该活动所有作品按热度倒序
		List<Production> productionList = productionService.list(Condition.getQueryWrapper(new Production()).lambda()
			.eq(Production::getActivityId, activityId)
			.orderByDesc(Production::getHotValue));
		if (StrUtil.isBlank(type)) {
			//查询总榜
			return R.data(productionList);
		}
		//根据分类排行
		List<Production> list = productionList.stream().filter(item -> type.equals(item.getPersonType())).collect(Collectors.toList());
		return R.data(list);
	}

}
