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


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.service.paln.task.PlanInspectUserService;
import com.tofly.gpsboot.service.paln.task.PlanchildService;
import com.tofly.pojo.plan.PlanInspectUser;
import com.tofly.pojo.plan.Planchild;
import com.tofly.pojo.plan.dto.ReportAuditDto;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.service.audit.IAuditHiddenTroubleEliminationServer;
import com.tofly.gpsboot.service.mq.IAuditMessageService;

import com.tofly.gpsboot.service.paln.CheckhistoryService;
import com.tofly.gpsboot.service.paln.task.PlanService;
import com.tofly.gpsboot.service.trouble.ToubleclearService;
import com.tofly.gpsboot.service.trouble.ToubleplanService;
import com.tofly.gpsboot.service.trouble.TroubleService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.message.Usertask;
import com.tofly.pojo.plan.Plan;
import com.tofly.pojo.trouble.Toubleclear;
import com.tofly.pojo.trouble.Toubleplan;
import com.tofly.pojo.trouble.Trouble;

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_HIDDEN_TROUBLE_ELIMINATION")
public class AuditHiddenTroubleEliminationServiceImpl implements IAuditHiddenTroubleEliminationServer {

    @Autowired
    private ToubleclearService toubleclearService;

    @Autowired
    private TroubleService troubleService;

    @Autowired
    private CheckhistoryService checkhistoryService;

    @Autowired
    private IAuditMessageService iAuditMessageService;

    @Autowired
    private UserTaskClient userTaskClient;
    @Autowired
    private PlanService planService;

    @Autowired
    private ToubleplanService toubleplanService;
    @Autowired
    private PlanchildService planchildService;

    @Autowired
    private PlanInspectUserService planInspectUserService;

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

        Toubleclear toubleclear = toubleclearService.getById(id);
        Long toubleId = toubleclear.getToubleId();
        Trouble info = troubleService.getById(toubleId);
        // 当前隐患消除记录审核状态排除已审核通过数据
        if (AuditSateEnum.AUDIT_YES.getCode().equals(toubleclear.getAuditResult())) {
            throw new BusinessException(Constant.AUDIT_NOT_UNCOMMITTED_CODE, Constant.AUDIT_NOT_UNCOMMITTED);
        }
        String auditResult = dto.getAuditResult();
        Date date = DateTimeUtil.convertLDTToDate(LocalDateTime.now());
        String auditNotes = dto.getAuditNotes();
        Long auditId = info.getAuditUser();
        // 审核时间
        toubleclear.setAuditTime(date);
        // 审核人(同派工人)
        toubleclear.setAuditUser(auditId);
        // 审核状态
        toubleclear.setAuditResult(auditResult);
        // 审核意见
        toubleclear.setAuditNotes(auditNotes);

        if(AuditSateEnum.AUDIT_YES.getCode().equals(auditResult)){
            // 隐患主计划状态变为
            info.setState(TroubleSateEnum.TROUBLE_SATE_YES_ELIMINATE.getCode());

            // 对应的巡检计划状态全部变成4 计划完成
            Set<Long> toublePlanIdList = toubleplanService.list(new QueryWrapper<Toubleplan>().lambda().eq(Toubleplan::getTroubleId, toubleId)).stream().map(Toubleplan::getPlanId).collect(Collectors.toSet());
            List<Plan> list = planService.list(new QueryWrapper<Plan>().lambda().in(Plan::getId, toublePlanIdList));
            list.forEach(i->i.setPlanState(PlanStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode()));
            // 巡检子计划状态更改
            planchildService.update(new UpdateWrapper<Planchild>().lambda().in(Planchild::getPlanId,toublePlanIdList).set(Planchild::getPlanState,IsPlanChildStateEnum.PLAN_STATE_PLAN_COMPLETE.getCode()));
            planService.updateBatchById(list);
            // 完成处理当前隐患待办计划任务信息
            toubleclearService.clearTroubleUserTaskPlan(toubleId);

        }else {
            // 审核不通过,上报状态再设置为 待上报
            info.setIsSubmit(ReportSateEnum.REPORT_UNCOMMITTED.getCode());
            // 隐患主计划状态变为
            info.setState(TroubleSateEnum.TROUBLE_SATE_PATROL.getCode());
        }
        troubleService.updateById(info);
        toubleclearService.updateById(toubleclear);
        // 存入当前计划审批历史信息
        checkhistoryService.recordHis(AuditTypeEnum.AUDIT_TYPE_HIDDEN_TROUBLE_ELIMINATION.getCode(), id, auditResult, auditNotes, auditId, date);


        // 发送mq消息(计划审核成功/失败)给上报对象到消息提示列表
        // 通知审核对象mq消息
        iAuditMessageService.auditTypeHiddenTroubleElimination(JSON.toJSONString(info));
        // 待办事项处理
        Usertask usertask = new Usertask();
        usertask.setTableName(MessageTopicEnum.REPORT_HIDDEN_TROUBLE_ELIMINATION.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);
            });

        }
    }
}
