package com.tofly.gpsboot.service.audit.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tofly.api.UserTaskClient;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.*;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.service.audit.IAuditPlanDisuseServer;
import com.tofly.gpsboot.service.mq.IAuditMessageService;
import com.tofly.gpsboot.service.paln.CheckhistoryService;
import com.tofly.gpsboot.service.paln.task.PlanInspectUserService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.paln.task.PlancancleService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.message.Usertask;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.plan.PlanInspectUser;
import com.tofly.pojo.plan.Plancancle;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Zev
 */
@Service("AUDIT_TYPE_PLAN_DISUSE")
public class AuditPlanDisuseServerImpl implements IAuditPlanDisuseServer {

    @Autowired
    private PlanService planService;

    @Autowired
    private PlancancleService plancancleService;

    @Autowired
    private CheckhistoryService checkhistoryService;

    @Autowired
    private IAuditMessageService iAuditMessageService;

    @Autowired
    private UserTaskClient userTaskClient;
    @Autowired
    private PlanInspectUserService planInspectUserService;


    @Override
    public void audit(ReportAuditDto dto) throws BusinessException {
        Long id = dto.getId();

        Plancancle info = plancancleService.getById(id);
        Plan plan = planService.getById(info.getPlanId());
        if (AuditSateEnum.AUDIT_YES.getCode().equals(info.getAuditResult())) {
            throw new BusinessException(Constant.AUDIT_NOT_UNCOMMITTED_CODE, Constant.AUDIT_NOT_UNCOMMITTED);
        }
        String auditNotes = dto.getAuditNotes();
        Long auditId = dto.getAuditId();
        String auditResult = dto.getAuditResult();
        Date date = DateTimeUtil.convertLDTToDate(LocalDateTime.now());
        // 修改对象审核状态 审核时间
        info.setAuditTime(date);
        info.setAuditUser(auditId);
        info.setAuditResult(auditResult);
        info.setAuditNotes(auditNotes);

        // 当前计划派发人才能作废审核(计划创建人)
        Long userId = SecurityUtils.getUserId();
        if(!userId.equals(plan.getCreateUser())){
            throw new BusinessException(Constant.TASK_PLAN_NOT_DISTRIBUTE_DISUSE_CODE, Constant.TASK_PLAN_NOT_DISTRIBUTE_DISUSE);
        }

        // 同意 当前任务状态修改为计划已作废
        if(AuditSateEnum.AUDIT_YES.getCode().equals(auditResult)){
            plan.setPlanState(PlanStateEnum.PLAN_STATE_PLAN_DISUSE.getCode());
            planService.updateById(plan);
            // 获取当前计划下关联处理人
            Set<Long> userList = planInspectUserService.list(new QueryWrapper<PlanInspectUser>().lambda().eq(PlanInspectUser::getPlanId, plan.getId())).stream().map(PlanInspectUser::getUserId).collect(Collectors.toSet());
            // 待办事项处理
            userList.forEach(user->{
                Usertask usertask = new Usertask();
                usertask.setTableName(MessageTopicEnum.TASK_PLAN_SEND.getTableName());
                usertask.setHandleUser(user);
                usertask.setTableId(info.getId());
                List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
                if(null != result && result.size()>0){
                    result.forEach(task->{
                        task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                        task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                        userTaskClient.updateById(task);
                    });

                }
            });
        }else {
            // 审核不通过,上报状态再设置为 待上报
            info.setIsSubmit(ReportSateEnum.REPORT_UNCOMMITTED.getCode());
            // 任务状态还原成 已开始未执行
            plan.setPlanState(PlanStateEnum.PLAN_STATE_EXECUTION_NOT_STARTED.getCode());
        }

        plancancleService.updateById(info);
        // 存入当前计划审批历史信息
        checkhistoryService.recordHis(AuditTypeEnum.AUDIT_TYPE_PLAN_DISUSE.getCode(), id, auditResult, auditNotes, auditId, date);


        // 发送mq消息(月计划审核成功/失败)给上报对象到消息提示列表
        // 通知审核对象mq消息
        iAuditMessageService.auditTypePlanDisuse(JSON.toJSONString(dto));
        // 待办事项处理状态置为完成
        // 待办事项处理
        Usertask usertask = new Usertask();
        usertask.setTableName(MessageTopicEnum.REPORT_PLAN_DISUSE.getTableName());
        usertask.setTableId(id);
        List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
        if(null != result && result.size()>0){
            Usertask task = result.get(0);
            task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
            task.setHandleUser(SecurityUtils.getUserId());
            task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
            userTaskClient.updateById(task);
        }
    }
}
