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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tofly.api.UserTaskClient;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.*;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.service.audit.IAuditEmergencyDisServer;
import com.tofly.gpsboot.service.audit.IAuditPlanMtServer;
import com.tofly.gpsboot.service.comm.IAuditService;
import com.tofly.gpsboot.service.emergency.EmergencyDisService;
import com.tofly.gpsboot.service.emergency.EmergencyService;
import com.tofly.gpsboot.service.mq.IAuditMessageService;
import com.tofly.gpsboot.service.paln.CheckhistoryService;
import com.tofly.gpsboot.service.paln.PlanMtService;
import com.tofly.gpsboot.service.paln.PlanchildtypeService;
import com.tofly.gpsboot.service.paln.PlantypeService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.paln.task.PlanchildService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.comm.Audit;
import com.tofly.pojo.emergency.Emergency;
import com.tofly.pojo.emergency.EmergencyDis;
import com.tofly.pojo.message.Usertask;
import com.tofly.pojo.plan.*;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * @author Zev
 */
@Service("AUDIT_TYPE_EMERGENCY_DIS")
public class AuditEmergencyDisServerImpl implements IAuditEmergencyDisServer {
    @Autowired
    private EmergencyService emergencyService;
    @Autowired
    private EmergencyDisService emergencyDisService;
    @Autowired
    private CheckhistoryService checkhistoryService;

    @Autowired
    private IAuditMessageService iAuditMessageService;
    @Autowired
    private UserTaskClient userTaskClient;

    @Autowired
    private IAuditService auditService;



    @Override
    public void audit(ReportAuditDto dto) throws BusinessException {
        Long id = dto.getId();
        Long auditId = dto.getAuditId();
        String auditResult = dto.getAuditResult();
        String auditNotes = dto.getAuditNotes();
        List<EmergencyDis> emergencyDisList = dto.getEmergencyDisList();
        // 判断传值问题
        if (null == id || null == auditId || StringUtils.isEmpty(auditResult) || emergencyDisList.isEmpty()) {
            throw new BusinessException(Constant.DATA_VALIDATION_CODE, Constant.DATA_VALIDATION + " 审核计划id= " + id + ",审核人= " + auditId + ",审核状态= " + auditResult + ",应急处理记录列表" + emergencyDisList.toString());
        }
        List<Audit> auditList = auditService.list(new QueryWrapper<Audit>().lambda()
                .ge(Audit::getAuditType, AuditTypeEnum.AUDIT_TYPE_EMERGENCY_DIS.getCode())
                .ge(Audit::getAuditUser, auditId)
                .ge(Audit::getAuditPlanId, id)
                .ge(Audit::getAuditState, AuditSateEnum.AUDIT_UNCOMMITTED.getCode()));
        // 判断当前是否有审核信息
        if (null != auditList && auditList.size() > 0) {
            Date date = new Date();
            Emergency emergency = emergencyService.getById(id);
            Audit audit = auditList.get(0);
            audit.setAuditTime(date);
            audit.setAuditUser(auditId);
            audit.setAuditState(auditResult);
            audit.setAuditNote(auditNotes);

            if (AuditSateEnum.AUDIT_YES.getCode().equals(auditResult)) {
                // 计划状态设置为 4 已完成
                // 完成当前计划id下所有代办信息
                emergency.setState("4");
                Usertask usertask = new Usertask();
                usertask.setTableName(MessageTopicEnum.TASK_EMERGENCY_DIS.getTableName());
                usertask.setTableId(id);
                List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
                if (null != result && result.size() > 0) {
                    result.forEach(info -> {
                        info.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                        info.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                        userTaskClient.updateById(info);
                    });
                }
            } else {
                // 计划状态设置为 2 已派工
                emergency.setState("2");

                // 将维护计划 设置为历史
                emergencyDisList.forEach(i -> {
                    i.setIsHis("1");
                });

                // 审核人待办事项处理
                Usertask usertask = new Usertask();
               // usertask.setTableName(MessageTopicEnum.REPORT_EMERGENCY_DIS.getTableName());

                usertask.setTableName(MessageTopicEnum.REPORT_EMERGENCY.getTableName());
                usertask.setHandleUser(auditId);
                usertask.setTableId(id);
                List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
                if (null != result && result.size() > 0) {
                    result.forEach(task->{
                        task.setHandleTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
                        task.setHandleUser(auditId);
                        task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                        userTaskClient.updateById(task);
                    });
                }
            }
            // 更新审核信息
            auditService.updateById(audit);
            // 批量修改应急处理记录审核信息
            emergencyDisService.updateBatchById(emergencyDisList);

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

            // 修改应急事件主信息
            emergencyService.updateById(emergency);

            // 通知审核对象mq消息 给上报对象到消息提示列表
            iAuditMessageService.auditEmergencyDis(dto, emergencyDisList.stream().map(EmergencyDis::getDisUserId).collect(Collectors.toSet()));
        } else {
            throw new BusinessException(Constant.AUDIT_SEL_NULL_CODE, Constant.AUDIT_SEL_NULL);
        }
    }


}
