package com.yeejoin.precontrol.common.action;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.component.rule.MethodParam;
import com.yeejoin.amos.component.rule.RuleActionBean;
import com.yeejoin.amos.component.rule.RuleMethod;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.SingBadManagementDto;
import com.yeejoin.precontrol.common.entity.Retribution;
import com.yeejoin.precontrol.common.entity.Reward;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.enums.RetributionEum;
import com.yeejoin.precontrol.common.enums.RewardEum;
import com.yeejoin.precontrol.common.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service(value = "TaskAction")
@RuleActionBean(beanLabel = "任务")
public class TaskAction {

    @Autowired
    private IRewardService rewardService;

    @Autowired
    private IRetributionService retributionService;

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IBadManagementPersonService badManagementPersonService;
    
	@Autowired
	IStatisticsService statisticsService;


    @RuleMethod(methodLabel = "处理奖惩", project = "施工安全预控")
    @Transactional
    public void handleBad(@MethodParam(paramLabel = "违章dto") SingBadManagementDto dto) {
        log.error("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        System.out.println("========================" + JSONObject.toJSONString(dto));
        Date nowDate = new Date();
        if (dto != null && dto.getId() != null) {
            Task task = taskService.getById(dto.getId());
            if (task != null) {
                // ========================奖励========================
                Reward list = (Reward) rewardService.getOne(new LambdaQueryWrapper<Reward>()
                        .eq(Reward::getTaskId, task.getId()));
                // 防止重复添加数据
                if (null == list) {
                    // 奖励
                    Reward reward = new Reward();
                    reward.setPersonId(task.getCreatePersonId());
                    reward.setTaskId(dto.getId());
                    reward.setMoney(dto.getRewardMoney());
                    reward.setStatus(RewardEum.NOT_REDEEMED.getValue());
                    reward.setCreateDate(nowDate);
                    // 判断是否已经该任务是否已处理
                    if (rewardService.getOne(new LambdaQueryWrapper<Reward>().eq(Reward::getPersonId, task.getCreatePersonId()).eq(Reward::getTaskId, task.getId())) == null) {
                        rewardService.save(reward);
                    }
                }
                // ========================惩罚========================
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("task_id", dto.getId());
                //List<BadManagementPerson> listIds = (List<BadManagementPerson>) badManagementPersonService.listByMap(map);
                List<Long> listIds = dto.getBadManagementId();
                log.error("========================" + JSONObject.toJSONString(listIds));
                if (listIds != null && listIds.size() > 0) {
                    List<Retribution> listRe = new ArrayList<Retribution>();
                    for (Long personId : listIds) {
                        Retribution retribution = new Retribution();
                        retribution.setCompanyId(dto.getCompanyId());
                        retribution.setPersonId(personId);
                        retribution.setTaskId(dto.getId());
                        retribution.setMoney(dto.getPunishMoney());
                        retribution.setStatus(RetributionEum.UNPAID_FINE.getValue());
                        retribution.setCreateDate(nowDate);
                        // 判断是否已经该任务是否已处理
                        Retribution retribution1 = retributionService.getOne(new LambdaQueryWrapper<Retribution>().eq(Retribution::getPersonId, task.getCreatePersonId()).eq(Retribution::getTaskId, task.getId()));
                        if ( retribution1 == null) {
                        	log.error("========================" + JSONObject.toJSONString(retribution1));
                        	listRe.add(retribution);
                        }
                    }
//                    // 过滤重复数据
//                    List<Retribution> listDb = (List<Retribution>) retributionService.list(new LambdaQueryWrapper<Retribution>()
//                            .eq(Retribution::getTaskId, task.getId()));
//                    if (null != listDb && listDb.size() > 0) {
//                        personIds = processRereibution(listDb, personIds,task.getId());
//                    }
                    // 惩罚
//                    personIds.forEach(personId -> {
//
//                    });
                    retributionService.saveBatch(listRe);
                }
        		//更新推送
        		String orgCode=   task.getOrgCode();
        		statisticsService.initWs(orgCode, Constant.WS_VIOLATIONRANK);
        		statisticsService.initWs(orgCode, Constant.WS_FBSVIOLATIONRANK);
        		statisticsService.initWs(orgCode, Constant.WS_DAYVIOLATION);
        		statisticsService.initWs(orgCode, Constant.WS_REDORGREENCODE);
            }
        } else {
            log.info("处理奖惩 dto is null");
        }
    }

    // 处理重复数据
    public static List<Long> processRereibution(List<Retribution> listDb, List<Long> personIds, Long taskId) {
        List<Long> retPersonIds = new ArrayList<>();
        for (Long personId : personIds) {
            if(duplication(listDb,personId, taskId)){
                retPersonIds.add(personId);
            }
        }
        return retPersonIds;
    }

    // 去重
    public static boolean duplication(List<Retribution> retributionList, Long personId, Long taskId) {
        for (Retribution retribution : retributionList) {
            if(personId.equals(retribution.getPersonId()) && taskId.equals(retribution.getTaskId())){
                // 有重复数据
                return false;
            }
        }
        // 没有重复数
        return true;
    }

}
