/*
 *    Copyright (c) 2018-2025, hnqz 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 pig4cloud.com 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: hnqz
 */
package com.qunzhixinxi.hnqz.admin.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackage;
import com.qunzhixinxi.hnqz.admin.entity.WmScorePackageStatus;
import com.qunzhixinxi.hnqz.admin.entity.WmTask;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageApiInput;
import com.qunzhixinxi.hnqz.admin.entity.input.WmScorePackageApiOutput;
import com.qunzhixinxi.hnqz.admin.enums.ScorePackageStatusEnum;
import com.qunzhixinxi.hnqz.admin.mapper.WmScorePackageMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmScorePackageStatusMapper;
import com.qunzhixinxi.hnqz.admin.mapper.WmTaskMapper;
import com.qunzhixinxi.hnqz.admin.service.WmScorePackageStatusService;
import com.qunzhixinxi.hnqz.common.core.util.R;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 积分包状态
 *
 * @author pigx code generator
 * @date 2020-07-17 23:32:01
 */
@Service
@AllArgsConstructor
public class WmScorePackageStatusServiceImpl extends ServiceImpl<WmScorePackageStatusMapper, WmScorePackageStatus> implements WmScorePackageStatusService {

	private final WmScorePackageStatusMapper wmScorePackageStatusMapper;
	private final WmScorePackageMapper wmScorePackageMapper;
	private final WmTaskMapper wmTaskMapper;

	@Override
	public R getPage(Page page, WmScorePackageStatus wmScorePackageStatus) {
		IPage<WmScorePackageStatus> pages=wmScorePackageStatusMapper.getPage(page, wmScorePackageStatus);
		return R.ok(pages);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R approvalStatus(WmScorePackageStatus wmScorePackageStatus) {
		WmScorePackageStatus packageStatus1=this.getById(wmScorePackageStatus.getId());
		wmScorePackageStatus.setPackageId(packageStatus1.getPackageId());
		//审批
		WmScorePackage wmScorePackage=wmScorePackageMapper.selectById(wmScorePackageStatus.getPackageId());
		if(wmScorePackage.getPackageType1().equals("1")){//定额
			//定额包一人一包，所以score=userscore
			wmScorePackageStatus.setUserScore(String.valueOf(wmScorePackage.getScore()));
			wmScorePackageStatus.setTaskNum(0);
		}else {
			wmScorePackageStatus.setTaskNum(wmScorePackage.getTaskNum());
			wmScorePackageStatus.setUserScore(String.valueOf(wmScorePackage.getUserScore()));
		}

		wmScorePackageStatus.setUpdateTime(LocalDateTime.now());
		wmScorePackageStatus.setUserId(null);
		this.updateById(wmScorePackageStatus);

		if("2".equals(wmScorePackageStatus.getStatus())) {//同意
			wmScorePackage.setScorePackageStatus("3");//进行中
			//判断该积分包是否审核满员，如果是，其他接单对象自动改为审核不通过
			WmScorePackageStatus wmScorePackageStatus1=new WmScorePackageStatus();
			wmScorePackageStatus1.setPackageId(wmScorePackageStatus.getPackageId());
			wmScorePackageStatus1.setStatus("2");//审核通过
			wmScorePackageStatus1.setDelFlag("0");
			wmScorePackageStatus1.setEnableFlag("0");
			List<WmScorePackageStatus> sList=this.list(Wrappers.query(wmScorePackageStatus1));
			Integer usernum=wmScorePackage.getUserNum()==null?1:wmScorePackage.getUserNum();
			if(sList.size()>=usernum){//接单审核通过人数等于积分包需求人数
				LambdaUpdateWrapper<WmScorePackageStatus> updateWrapper=new LambdaUpdateWrapper();
				updateWrapper.set(WmScorePackageStatus::getStatus,"3");//审核不通过
				updateWrapper.set(WmScorePackageStatus::getTaskAddFlag,"0");//不允许新增任务
				updateWrapper.eq(WmScorePackageStatus::getPackageId,wmScorePackageStatus.getPackageId());
				updateWrapper.eq(WmScorePackageStatus::getStatus,"1");
				updateWrapper.eq(WmScorePackageStatus::getDelFlag,"0");
				updateWrapper.eq(WmScorePackageStatus::getEnableFlag,"0");
				this.update(updateWrapper);
				//wmScorePackage.setPackageStatus("2");
				wmScorePackage.setUpdateTime(LocalDateTime.now());
				wmScorePackage.setReceiveDate(LocalDateTime.now());
				wmScorePackage.setIsReceive("1");//不允许接单
				wmScorePackageMapper.updateById(wmScorePackage);
			}

		}else {//不同意
			wmScorePackageStatus.setTaskAddFlag("0");//不可以新增任务
			wmScorePackageStatus.setUserId(null);
			this.updateById(wmScorePackageStatus);
		}

		WmScorePackageStatus query = new WmScorePackageStatus();
		query.setPackageId(wmScorePackageStatus.getPackageId());
		query.setStatus("2");
		query.setDelFlag("0");
		query.setEnableFlag("0");
		int total = this.count(Wrappers.query(query));
		if(total>=1){//有人接单成功
			wmScorePackage.setScorePackageStatus("3");//进行中
			if(total>=wmScorePackage.getUserNum()){//人数已满
				wmScorePackage.setIsReceive("1");//不允许接单
			}
		}else {//没有人接单成功
			WmScorePackageStatus query1 = new WmScorePackageStatus();
			query1.setPackageId(wmScorePackageStatus.getPackageId());
			query1.setStatus("1");
			int total1 = this.count(Wrappers.query(query1));
			if(total1==0){
				wmScorePackage.setScorePackageStatus("1");//已分派待申领
			}else {
				wmScorePackage.setScorePackageStatus("2");//已申领待审批
			}

		}

		wmScorePackageMapper.updateById(wmScorePackage);

		//拒绝没有操作
		return  R.ok();
	}

	/**
	 * 终止接单
	 * @param wmScorePackageStatus
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateZZ(WmScorePackageStatus wmScorePackageStatus) {
		String enableType=wmScorePackageStatus.getEnableType();
		wmScorePackageStatus=this.getById(wmScorePackageStatus.getId());
		wmScorePackageStatus.setEnableType(enableType);
		WmScorePackage wmScorePackage1=wmScorePackageMapper.selectById(wmScorePackageStatus.getPackageId());
		Integer res=0;
		wmScorePackageStatus.setTaskAddFlag("0");//不允许新增任务
		if("1".equals(enableType)){//全部收回
			wmScorePackage1.setIsReceive("0");//允许接单
			//先终止任务，再收回任务积分
			wmScorePackageStatus.setEnableFlag("1");//已终止

			LambdaUpdateWrapper<WmTask> updateWrapper=new LambdaUpdateWrapper();
			updateWrapper.set(WmTask::getEnableFlag,"1");
			updateWrapper.eq(WmTask::getScorePackageId,wmScorePackageStatus.getPackageId());
			updateWrapper.eq(WmTask::getTaskUserId,wmScorePackageStatus.getUserId());
			wmTaskMapper.update(new WmTask(),updateWrapper);
			//WmScorePackage wmScorePackage1=wmScorePackageMapper.selectById(wmScorePackageStatus.getPackageId());
		}else if("2".equals(enableType)){//部分收回
			//部分收回，只收回没有做的任务，做完的任务，可以审核，审核不通过，可以继续做任务
			//计算该用户任务的总积分，如果总积分，小于积分包的个人积分值，那么积分包的总积分值减去少的一部分
			WmTask wmTask=new WmTask();
			wmTask.setEnableFlag("0");
			wmTask.setScorePackageId(wmScorePackageStatus.getPackageId());
			wmTask.setTaskUserId(wmScorePackageStatus.getUserId());
			wmTask.setTaskStatus("1,2,3");
			List<WmTask> taskList=wmTaskMapper.selectByTask(wmTask);
			if(taskList==null||taskList.size()==0){
				if(wmScorePackage1.getPackageType1().equals("1")){//定额
					//这个用户还没有做任务时，积分值设为0
					wmScorePackageStatus.setUserScore("0");
					wmScorePackage1.setScore(wmScorePackage1.getScore()-Integer.valueOf(wmScorePackageStatus.getUserScore()));
				}else {//2，3 定量
					//定量收回任务个数
					wmScorePackageStatus.setTaskNum(0);
				}

			}else {
				if(wmScorePackage1.getPackageType1().equals("1")){//定额
					Integer sum = taskList.stream().mapToInt(WmTask::getScore).sum();
					res = Integer.valueOf(wmScorePackageStatus.getUserScore()) - sum;
					if (res > 0) {//个人积分包值大于任务积分值
						wmScorePackageStatus.setUserScore(sum + "");
					}
				}else {//2，3 定量
					//定量收回任务个数
					wmScorePackageStatus.setTaskNum(taskList.size());
				}

			}
		}

		//更新结单数据
		this.updateById(wmScorePackageStatus);
		//更新积分包的积分总值
		if(res>0){
			if(wmScorePackage1.getPackageType1().equals("1")){//定额
				wmScorePackage1.setScore(wmScorePackage1.getScore()-res);
				if(!StringUtil.isEmpty(wmScorePackage1.getRelationScoreId())){
					WmScorePackage wmScorePackage2=wmScorePackageMapper.selectById(wmScorePackage1.getRelationScoreId());
					wmScorePackage2.setKfpjf(wmScorePackage2.getKfpjf()+res);
					wmScorePackageMapper.updateById(wmScorePackage2);
				}
			}

		}
		wmScorePackageMapper.updateById(wmScorePackage1);
		this.updateScorePackageStatus(wmScorePackageStatus.getPackageId());

		return R.ok();
	}


	/**
	 * 公共方法--判断积分包状态scorePackageStatus
	 * @param ScorePackageId
	 */
	@Override
	@Transactional
	public  void updateScorePackageStatus(String ScorePackageId){
		WmScorePackage wmScorePackage=wmScorePackageMapper.selectById(ScorePackageId);
		WmTask wmTask1=new WmTask();
		wmTask1.setDelFlag("0");
		wmTask1.setEnableFlag("0");
		wmTask1.setRealFlag("0");
		wmTask1.setScorePackageId(ScorePackageId);
		wmTask1.setTaskStatus("2");//未审核
		wmTask1.setScorePackageId(ScorePackageId);
		List<Map<String,String>> resMap=wmTaskMapper.PackageIsFinishByTask(wmTask1);
		if(null==resMap){
			//没有接单成功的人，判断是否有接单未审核的数据
			LambdaQueryWrapper<WmScorePackageStatus> queryWrapper=new LambdaQueryWrapper<>();
			queryWrapper.eq(WmScorePackageStatus::getPackageId,ScorePackageId);
			queryWrapper.eq(WmScorePackageStatus::getStatus,"1");
			List<WmScorePackageStatus> statusList=this.list(queryWrapper);
			if(null==statusList||statusList.size()==0){
				wmScorePackage.setScorePackageStatus("1");//已分派待申领
			}else {
				wmScorePackage.setScorePackageStatus("2");//已申领待审批
			}

		}else if(resMap.size()>=wmScorePackage.getUserNum()){//接单成功人满了
			boolean result=true;
			for (Map<String,String> map: resMap) {
				if(!StringUtil.isEmpty(map.get("isFinish"))){
					Integer res=Integer.valueOf(map.get("isFinish"));
					if(res>0){
						result=false;
						//return R.ok();
					}
				}else {
					result=false;
					//return R.ok();
				}

			}

			if(result){
				//更新所有的任务
				LambdaUpdateWrapper<WmTask> updateWrapper=new LambdaUpdateWrapper<>();
				updateWrapper.eq(WmTask::getScorePackageId,ScorePackageId);
				updateWrapper.eq(WmTask::getRealFlag,"9");
				updateWrapper.set(WmTask::getRealFlag,"1");
				wmTaskMapper.update(new WmTask(),updateWrapper);
				LambdaUpdateWrapper<WmTask> updateWrapper1=new LambdaUpdateWrapper<>();
				updateWrapper1.eq(WmTask::getScorePackageId,ScorePackageId);
				updateWrapper1.eq(WmTask::getTaskStatus,"2");
				updateWrapper1.set(WmTask::getTaskStatus,"4");
				wmTaskMapper.update(new WmTask(),updateWrapper1);

				wmScorePackage.setPackageFinishStatus("1");//已完成
				// 有关联积分包，则设置为‘已完成待审批’；没有关联积分包，则直接设置为‘已完成待结算’
				if (StringUtils.isNotBlank(wmScorePackage.getRelationScoreId())) {
					wmScorePackage.setScorePackageStatus(ScorePackageStatusEnum.TO_BE_APPROVAL.val()); // 已完成待审批
				} else {
					wmScorePackage.setScorePackageStatus(ScorePackageStatusEnum.TO_BE_SETTLED.val()); // 已完成待结算
				}
				wmScorePackage.setTaskAddFlag("0");//已完成不可以做任务
				wmScorePackage.setPackageFinishTime(LocalDateTime.now());

			}
		}else {
			//接单人没有满，但是有人接单，状态是进行中
			wmScorePackage.setScorePackageStatus("3");//进行中

		}
		wmScorePackageMapper.updateById(wmScorePackage);
	}

	@Override
	public List<WmScorePackageStatus> getByPackageId(WmScorePackageStatus wmScorePackageStatus) {
		return wmScorePackageStatusMapper.getByPackageId( wmScorePackageStatus);
	}

	@Override
	public boolean delStatusByPackageId(String packageId) {

		return this.update(Wrappers.<WmScorePackageStatus>lambdaUpdate()
				.eq(WmScorePackageStatus::getPackageId,packageId)
				.set(WmScorePackageStatus::getDelFlag,"1"));
	}

	@Override
	public IPage<WmScorePackageApiOutput> getReceivedPackageList(Page page, WmScorePackageApiInput input) {
		return wmScorePackageStatusMapper.getReceivedPackageList(page,input);
	}

	/**
	 * 更新积分包状态
	 * @param wmTask
	 * @param wmScorePackage
	 * @param scorePackageStatus
	 */
	@Override
	public void updatePackageAndStatus(WmTask wmTask, WmScorePackage wmScorePackage, WmScorePackageStatus scorePackageStatus) {
		WmTask taskQuery = new WmTask();
		taskQuery.setScorePackageId(wmTask.getScorePackageId());
		QueryWrapper<WmTask> taskQueryWrapper = Wrappers.query(taskQuery);
		/**
		 * 查询出 审核通过和审核中的任务
		 */
		taskQueryWrapper.lambda()
				.ne(WmTask::getTaskStatus, "4")
				.eq(WmTask::getRealFlag, "0");
//				.ne(WmTask::getRealFlag, "1");
		List<WmTask> wmTaskList = wmTaskMapper.selectList(taskQueryWrapper);
		/**
		 * 判断定量还是定额 1- 定额   2-定量
		 */
		if ("1".equals(wmScorePackage.getPackageType1())) {

			int totalCount = 0;
			for (WmTask wmtask : wmTaskList) {
				totalCount += wmtask.getScore();
			}

			if (totalCount >= wmScorePackage.getScore()) {
				wmScorePackage.setTaskAddFlag("0");
				scorePackageStatus.setTaskAddFlag("0");
			}else {
				wmScorePackage.setTaskAddFlag("1");
				scorePackageStatus.setTaskAddFlag("1");
			}
			wmScorePackageStatusMapper.updateById(scorePackageStatus);
		} else {
			List<WmTask> userTaskList = wmTaskList.stream().filter(item ->
					item.getTaskUserId().equals(wmTask.getTaskUserId())).collect(Collectors.toList());

			if (userTaskList.size() >= scorePackageStatus.getTaskNum()) {
				scorePackageStatus.setTaskAddFlag("0");
			}else {
				scorePackageStatus.setTaskAddFlag("1");

			}
			wmScorePackageStatusMapper.updateById(scorePackageStatus);

			/**
			 * 改变大包状态
			 */
			WmScorePackageStatus queryAll = new WmScorePackageStatus();
			queryAll.setPackageId(wmScorePackage.getId());
			queryAll.setStatus("2");
			queryAll.setTaskAddFlag("0");
			List<WmScorePackageStatus> statusAll = wmScorePackageStatusMapper.selectList(Wrappers.query(queryAll));
			if(new BigDecimal(wmScorePackage.getUserNum())
					.compareTo(new BigDecimal(statusAll.size())) <= 0){
				wmScorePackage.setTaskAddFlag("0");
			}else {
				wmScorePackage.setTaskAddFlag("1");
			}

//			if (wmTaskList.size() >= wmScorePackage.getTaskNum()) {
//				wmScorePackage.setTaskAddFlag("0");
//			}else {
//				wmScorePackage.setTaskAddFlag("1");
//			}

		}

		wmScorePackageMapper.updateById(wmScorePackage);
	}


	@Override
	public IPage<WmScorePackageStatus> getWmScorePackageStatusPage(Page page, WmScorePackageStatus wmScorePackageStatus) {
		return wmScorePackageStatusMapper.getWmScorePackageStatusPage(page,wmScorePackageStatus);
	}

	/**
	 * 获取当前部门已接单人的列表
	 *
	 * @param deptId 部门id
	 * @param packageType1 积分包任务类型1
	 * @param packageType2 积分包任务类型2
	 * @return
	 */
	@Override
	public List<Map<String, String>> getDeptReceiveUserList(String deptId, String packageType1, String packageType2) {
		return wmScorePackageStatusMapper.getDeptReceiveUserList(deptId, packageType1, packageType2);
	}
}
