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

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.IAuditRepairYearPlanServer;
import com.tofly.gpsboot.service.comm.IAuditService;
import com.tofly.gpsboot.service.maintain.RepairplanyearService;
import com.tofly.gpsboot.service.mq.IAuditMessageService;
import com.tofly.gpsboot.service.mq.IReportMessageService;
import com.tofly.gpsboot.service.paln.CheckhistoryService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.comm.Audit;
import com.tofly.pojo.maintain.Repairplanyear;
import com.tofly.pojo.message.Usertask;
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.stream.Collectors;

/**
 * 抢维修年计划审核
 *
 * @author Zev
 */
@Service("AUDIT_TYPE_REPAIR_YEAR_PLAN")
public class AuditRepairYearPlanServerImpl implements IAuditRepairYearPlanServer {


    @Autowired
    private CheckhistoryService checkhistoryService;

    @Autowired
    private IAuditMessageService iAuditMessageService;

    @Autowired
    private RepairplanyearService repairplanyearService;

    @Autowired
    private IReportMessageService iReportMessageService;

    @Autowired
    private IAuditService iAuditService;

    @Autowired
    private UserTaskClient userTaskClient;

    @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<Audit> list = iAuditService.list(new QueryWrapper<Audit>().lambda().eq(Audit::getAuditType, AuditTypeEnum.AUDIT_TYPE_REPAIR_YEAR_PLAN.getCode()).eq(Audit::getAuditPlanId, id));
        if (null != list && list.size() > 0) {
            // 判断当前审核人是否拥有审核当前对象的权力
            // 不支持对应的同一个负责人审批多次
            List<Audit> auditList = list.stream().filter(i -> auditId.equals(i.getAuditUser()) && AuditSateEnum.AUDIT_UNCOMMITTED.getCode().equals(i.getAuditState())).collect(Collectors.toList());
            if (auditList.size() > 0) {
                Audit audit = auditList.get(0);
                String auditState = audit.getAuditState();
                // 判断当前审核对象状态是否为待审批
                if (AuditSateEnum.AUDIT_UNCOMMITTED.getCode().equals(auditState)) {
                    Repairplanyear info = repairplanyearService.getById(id);
                    Date date = DateTimeUtil.convertLDTToDate(LocalDateTime.now());
                    // 修改审核对象 审核时间/审核说明/审核状态
                    audit.setAuditTime(date);
                    audit.setAuditNote(auditNotes);
                    audit.setAuditState(auditResult);

                    // 当前审批是否为通过
                    if (AuditSateEnum.AUDIT_YES.getCode().equals(auditResult)) {
                        // 审批链判断是否需要进行下一级审批
                        Audit nextAudit = iAuditService.getNextAudit(list, audit.getAuditLevel());
                        if (null != nextAudit) {
                            // 修改当前对象的审核状态为待审核
                            nextAudit.setAuditState(AuditSateEnum.AUDIT_UNCOMMITTED.getCode());
                            // 发送消息通知该审批人
                            ReportAuditDto auditDto = new ReportAuditDto();
                            auditDto.setId(id);
                            iReportMessageService.reportRepairYearPlan(auditDto, nextAudit.getAuditUser());
                            iAuditService.updateById(nextAudit);
                        } else {
                            // 修改年计划状态 通过
                            info.setPlanState(auditResult);
                        }
                    } else {
                        // 修改年计划状态 不通过
                        info.setPlanState(auditResult);
                        // 修改上报状态 未提交
                        info.setIssubmit(IsSubmitEnum.IS_SUBMIT_NO.getCode());
                    }
                    // 更新当前审批对象
                    iAuditService.updateById(audit);
                    // 存入当前计划审批历史信息
                    checkhistoryService.recordHis(AuditTypeEnum.AUDIT_TYPE_REPAIR_YEAR_PLAN.getCode(), id, auditResult, auditNotes, auditId, date);
                    // 更新抢维修年计划信息状态
                    repairplanyearService.updateById(info);
                    // 通知上报对象mq消息
                    iAuditMessageService.auditTypeRepairYearPlan(dto, info.getSubmitUser());
                    // 待办事项处理状态置为完成
                    // 待办事项处理
                    Usertask usertask = new Usertask();
                    usertask.setTableName(MessageTopicEnum.REPORT_REPAIR_YEAR_PLAN.getTableName());
                    usertask.setHandleUser(SecurityUtils.getUserId());
                    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(SecurityUtils.getUserId());
                            task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                            userTaskClient.updateById(task);
                        });

                    }
                } else {
                    throw new BusinessException(Constant.PLAN_DISPATCHING_AUDIT_NOT_DISPOSE_ERROR_CODE, Constant.PLAN_DISPATCHING_AUDIT_NOT_DISPOSE_ERROR);
                }

            } else {
                throw new BusinessException(Constant.PLAN_DISPATCHING_AUDIT_ERROR_CODE, Constant.PLAN_DISPATCHING_AUDIT_ERROR);
            }
        } else {
            throw new BusinessException(Constant.PLAN_DISPATCHING_AUDIT_ERROR_CODE, Constant.PLAN_DISPATCHING_AUDIT_ERROR);
        }
    }
}
