package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.FlowStatusEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.WorkOrderEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.HygfWorkOrderStationAuditingDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.WorkflowResultDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.HygfRectificationOrder;
import com.yeejoin.amos.boot.module.hygf.api.entity.HygfWorkOrderStationAuditing;
import com.yeejoin.amos.boot.module.hygf.api.entity.RectificationOrderAuditing;
import com.yeejoin.amos.boot.module.hygf.api.entity.WorkOrderPowerStation;
import com.yeejoin.amos.boot.module.hygf.api.mapper.RectificationOrderAuditingMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IRectificationOrderAuditingService;
import com.yeejoin.amos.boot.module.hygf.api.dto.RectificationOrderAuditingDto;
import com.yeejoin.amos.feign.workflow.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;

/**
 * 施工完工审核表服务实现类
 *
 * @author system_generator
 * @date 2024-08-13
 */
@Service
public class RectificationOrderAuditingServiceImpl extends BaseService<RectificationOrderAuditingDto, RectificationOrderAuditing, RectificationOrderAuditingMapper> implements IRectificationOrderAuditingService {
    @Autowired
    HygfRectificationOrderServiceImpl rectificationOrderService;

    @Autowired
    private WorkFlowService workFlowService;
    @Autowired

    private static final String PROCESSKEY = "RectificationAudit";

    /**
     * 分页查询
     */
    public Page<RectificationOrderAuditingDto> queryForRectificationOrderAuditingPage(Page<RectificationOrderAuditingDto> page) {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<RectificationOrderAuditingDto> queryForRectificationOrderAuditingList() {
        return this.queryForList("", false);
    }


    public void addRectification(HygfRectificationOrder hygfRectificationOrder) {
        //添加整改单
        hygfRectificationOrder.setRectificationStatus(hygfRectificationOrder.getAddorSubmit().equals("1") ?
                WorkOrderEnum.待提交.getCode() : WorkOrderEnum.待整改.getCode());
        rectificationOrderService.saveOrUpdate(hygfRectificationOrder);


        if (hygfRectificationOrder.getAddorSubmit().equals("0")) {
            //开启工作流 并执行一步
            ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
            List<ActWorkflowStartDTO> params = new ArrayList<>();
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey(PROCESSKEY);
            dto.setBusinessKey(String.valueOf(new Date().getTime()));
            dto.setCompleteFirstTask(true);
            HashMap<String, Object> map = new HashMap<>();
            map.put("approvalStatus", "0");
            dto.setVariables(map);
            params.add(dto);
            actWorkflowBatchDTO.setProcess(params);
            List<ProcessTaskDTO> processTaskDTOS = workFlowService.startBatch(actWorkflowBatchDTO);
            List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(processTaskDTOS);

            WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
            RectificationOrderAuditingDto rectificationOrderAuditingDto = new RectificationOrderAuditingDto();
            BeanUtils.copyProperties(workflowResultDto, rectificationOrderAuditingDto);
            rectificationOrderAuditingDto.setRectificationOrder(hygfRectificationOrder.getSequenceNbr());
            rectificationOrderAuditingDto.setPromoter(RequestContext.getExeUserId());
            this.createWithModel(rectificationOrderAuditingDto);
            //发起待办
//            commonService.buildTaskModel(commonService.buildTaskModelDto(rectificationOrderAuditingDto, workflowResultDto, BusinessTypeEnum.HYGF_ZGDSHLC));

        }
    }


    //	工作流执行一步
    public void wofkflowExcute(String instanceId, String approvalStatus, String comment) {
        LambdaQueryWrapper<RectificationOrderAuditing> query = new LambdaQueryWrapper<>();
        query.eq(RectificationOrderAuditing::getInstanceId, instanceId);
        query.orderByDesc(BaseEntity::getRecDate);
        query.last("limit 1");
        RectificationOrderAuditing rectificationOrderAuditing = this.getBaseMapper().selectOne(query);

        //组装信息
        TaskResultDTO task = new TaskResultDTO();

        task.setTaskId(rectificationOrderAuditing.getNextTaskId());
        HashMap<String, Object> map = new HashMap<>();
        RectificationOrderAuditingDto rectificationOrderAuditingDto = new RectificationOrderAuditingDto();
        task.setResultCode("approvalStatus");
        map.put("approvalStatus", approvalStatus);
        task.setComment(comment == null ? "" : comment);
        task.setVariable(map);
        //执行流程
        ProcessTaskDTO processTaskDTO = workFlowService.complete(rectificationOrderAuditing.getNextTaskId(), task);
        List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO));
        WorkflowResultDto workflowResultDto = workflowResultDtos.get(0);
        BeanUtils.copyProperties(workflowResultDto, rectificationOrderAuditingDto);
        rectificationOrderAuditingDto.setRectificationOrder(rectificationOrderAuditing.getRectificationOrder());
        rectificationOrderAuditingDto.setPromoter(rectificationOrderAuditing.getPromoter());
        if (null == rectificationOrderAuditingDto.getInstanceId()) {
            rectificationOrderAuditingDto.setInstanceId(rectificationOrderAuditing.getInstanceId());
        }
        this.createWithModel(rectificationOrderAuditingDto);
        //更新待办
//        workflowResultDto.setInstanceId(rectificationOrderAuditing.getInstanceId());
//        commonService.updateTaskModelAndAddTask(rectificationOrderAuditing,workflowResultDto,BusinessTypeEnum.HYGF_ZGDSHLC);
    }


    public void nextTaskExcute(HygfRectificationOrder hygfRectificationOrder) {
        //添加整改单信息
        rectificationOrderService.saveOrUpdate(hygfRectificationOrder);
        LambdaQueryWrapper<RectificationOrderAuditing> query = new LambdaQueryWrapper<>();
        query.eq(RectificationOrderAuditing::getRectificationOrder, hygfRectificationOrder.getSequenceNbr());
        query.orderByDesc(BaseEntity::getRecDate);
        query.last("limit 1");
        RectificationOrderAuditing rectificationOrderAuditing = this.getBaseMapper().selectOne(query);

        if (hygfRectificationOrder.getAddorSubmit().equals("0")) {
            this.wofkflowExcute(rectificationOrderAuditing.getInstanceId(), "0", "填写整改单");
        }
    }

    public void nextTaskAduit(HygfRectificationOrder hygfRectificationOrder) {
        //添加整改单信息 若审核结果为不通过时候 添加历史审核意见 直接组装好格式 时间+审核意见
        String auditResult = hygfRectificationOrder.getAuditResult();
        if (hygfRectificationOrder.getAuditResult().equals("不通过")) {
            if (StringUtils.isEmpty(hygfRectificationOrder.getAuditIdea())){
                throw new  BadRequest("审核不通过时审核意见不可为空");
            }
            hygfRectificationOrder.setAuditIdea(null);
            hygfRectificationOrder.setAuditResult(null);
        }
        rectificationOrderService.saveOrUpdate(hygfRectificationOrder);
        LambdaQueryWrapper<RectificationOrderAuditing> query = new LambdaQueryWrapper<>();
        query.eq(RectificationOrderAuditing::getRectificationOrder, hygfRectificationOrder.getSequenceNbr());
        query.orderByDesc(BaseEntity::getRecDate);
        query.last("limit 1");
        RectificationOrderAuditing rectificationOrderAuditing = this.getBaseMapper().selectOne(query);
        this.wofkflowExcute(rectificationOrderAuditing.getInstanceId(), auditResult.equals("通过") ? "0" : "1", "审核整改单");
    }

    public void rollback(Long sequenceNbr) {
        LambdaQueryWrapper<RectificationOrderAuditing> query = new LambdaQueryWrapper<>();
        query.eq(RectificationOrderAuditing::getRectificationOrder, sequenceNbr);
        query.orderByDesc(BaseEntity::getRecDate);
        query.last("limit 1");
        RectificationOrderAuditing rectificationOrderAuditing = this.getBaseMapper().selectOne(query);
        if (null != rectificationOrderAuditing ){
            workFlowService.stopProcess(rectificationOrderAuditing.getInstanceId());
            this.getBaseMapper().deleteByInstanceId(rectificationOrderAuditing.getInstanceId());
        }

        LambdaUpdateWrapper<HygfRectificationOrder> up = new LambdaUpdateWrapper<>();
        up.set(HygfRectificationOrder::getRectificationStatus,WorkOrderEnum.已作废.getCode());
        up.eq(BaseEntity::getSequenceNbr,sequenceNbr);
        rectificationOrderService.getBaseMapper().update(null,up);
    }
}