package com.sckw.mine.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sckw.core.model.constant.Global;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.web.response.HttpResult;
import com.sckw.mine.common.OrderServerCommon;
import com.sckw.mine.entity.KwBusinessActionTrack;
import com.sckw.mine.entity.KwBusinessMineOrder;
import com.sckw.mine.entity.KwBusinessWorkFlowNode;
import com.sckw.mine.entity.req.ReviewOrderParam;
import com.sckw.mine.entity.req.TaskCardPageListParam;
import com.sckw.mine.entity.res.TaskCardPageListRes;
import com.sckw.mine.enums.MineStatusEnum;
import com.sckw.mine.mapper.KwBusinessActionTrackMapper;
import com.sckw.mine.mapper.MineMapper;
import com.sckw.mine.mapper.MineOrderMapper;
import com.sckw.mine.mapper.WorkFlowNodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @desc:
 * @author: Lt
 * @date: 2024-05-29
 */
@Service
public class TaskCardService {

    @Autowired
    KwBusinessActionTrackMapper kwBusinessActionTrackMapper;

    @Autowired
    MineMapper mineMapper;

    @Autowired
    MineOrderMapper mineOrderMapper;

    @Autowired
    OrderServerCommon orderServerCommon;

    @Autowired
    WorkFlowNodeMapper workFlowNodeMapper;


    /**
    * @Description: 任务卡片分页列表
    * @Author: Lt
    * @Date: 2024/5/29 15:38
    */
    public HttpResult taskCardPageList(TaskCardPageListParam param)
    {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<TaskCardPageListRes> businessTruckPageListRes = kwBusinessActionTrackMapper.taskCardPageList(param);
        //businessTruckPageListRes.forEach(e -> {
        //    e.setStatusStr(MineStatusEnum.getNameByCode(e.getStatus()));
        //});
        return HttpResult.ok(new PageRes<>(new PageInfo<>(businessTruckPageListRes)));
    }

    /**
    * @Description: 任务卡片操作
    * @Author: Lt
    * @Date: 2024/5/29 15:44
    */
    public HttpResult reviewOrder(ReviewOrderParam reviewOrderParam)
    {
        KwBusinessActionTrack kwBusinessActionTrack = kwBusinessActionTrackMapper.selectById(reviewOrderParam.getId());
        if (ObjectUtils.isNull(kwBusinessActionTrack))
        {
            return HttpResult.error("当前任务不存在");
        }
        //根据订单号查找订单
        Long orderId = kwBusinessActionTrack.getMineOrderId();
        KwBusinessMineOrder kwBusinessMineOrder = mineOrderMapper.selectById(orderId);
        if (ObjectUtils.isNull(kwBusinessMineOrder))
        {
            return HttpResult.error("未找到当前订单");
        }
        //已找到当前订单
        //找到订单所属流程id
        String flowId = kwBusinessMineOrder.getWorkFlow();
        //找到当前流程下所有节点
        List<KwBusinessWorkFlowNode> list = workFlowNodeMapper.selectList(new QueryWrapper<KwBusinessWorkFlowNode>()
                .eq("flow_id", flowId).eq("del_flag", Global.NUMERICAL_ZERO)
        );

        List<KwBusinessActionTrack> kwBusinessActionTracks = kwBusinessActionTrackMapper.selectList(new QueryWrapper<KwBusinessActionTrack>()
                .eq("mine_order_id", orderId)
                .eq("del_flag", Global.NUMERICAL_ZERO)
        );

        String orderStatus = null;
        //审核通过
        if (reviewOrderParam.getYesOrNo() == 1) {
            String nextNodeId = null;
            String nextNodeName = null;
            //找到它的下一个任务是什么
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getNodeId().equals(kwBusinessActionTrack.getStatus())) {
                    nextNodeId = list.get(i + 1).getNodeId();
                    nextNodeName = list.get(i + 1).getNodeName();
                }
            }
            //防止多次审核
            if (!ObjectUtils.isEmpty(nextNodeId)) {

                for (KwBusinessActionTrack businessActionTrack : kwBusinessActionTracks) {
                    if (Objects.equals(businessActionTrack.getStatus(), nextNodeId)
                            || Objects.equals(businessActionTrack.getStatus(), MineStatusEnum.FIFTEEN.getCode())
                            || Objects.equals(businessActionTrack.getStatus(), MineStatusEnum.TWENTY.getCode())
                    ) {
                        return HttpResult.error("当前任务已被审核过,请勿重复审核");
                    }
                }
            }
            //执行下一个流程
            orderServerCommon.saveActionTrack(orderId, nextNodeId, nextNodeName, nextNodeName);
            orderStatus = nextNodeId;
        }else{
            //未通过,驳回状态
            for (KwBusinessActionTrack businessActionTrack : kwBusinessActionTracks) {
                if ("15".equals(businessActionTrack.getStatus())) {
                    return HttpResult.error("当前任务已被驳回,请勿重复操作");
                }
            }
            String nameByCode = MineStatusEnum.getNameByCode(MineStatusEnum.FIFTEEN.getCode());
            orderServerCommon.saveActionTrack(orderId, String.valueOf(MineStatusEnum.FIFTEEN.getCode()), nameByCode, nameByCode);
            orderStatus = String.valueOf(MineStatusEnum.FIFTEEN.getCode());
        }
        //修改订单状态
        LambdaUpdateWrapper<KwBusinessMineOrder> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        objectLambdaUpdateWrapper.set(KwBusinessMineOrder::getStatus, orderStatus).eq(KwBusinessMineOrder::getId, orderId);
        mineOrderMapper.update(null, objectLambdaUpdateWrapper);

        String msg = reviewOrderParam.getYesOrNo() == 1 ? "审核" : "驳回";

        return HttpResult.ok(msg+ "成功");
    }

    /**
    * @Description: 执行项目下一步
    * @Author: Lt
    * @Date: 2024/6/6 9:16
    */
    public HttpResult carryTrack(ReviewOrderParam reviewOrderParam)
    {
        KwBusinessActionTrack kwBusinessActionTrack = kwBusinessActionTrackMapper.selectById(reviewOrderParam.getId());
        if (ObjectUtils.isNull(kwBusinessActionTrack))
        {
            return HttpResult.error("当前任务不存在");
        }
        //根据订单号查找订单
        Long orderId = kwBusinessActionTrack.getMineOrderId();
        KwBusinessMineOrder kwBusinessMineOrder = mineOrderMapper.selectById(orderId);
        if (ObjectUtils.isNull(kwBusinessMineOrder))
        {
            return HttpResult.error("未找到当前订单");
        }
        //已找到当前订单
        //找到订单所属流程id
        String flowId = kwBusinessMineOrder.getWorkFlow();
        String status = kwBusinessMineOrder.getStatus();
        //找到当前流程下所有节点
        List<KwBusinessWorkFlowNode> list = workFlowNodeMapper.selectList(new QueryWrapper<KwBusinessWorkFlowNode>()
                .eq("flow_id", flowId).eq("del_flag", Global.NUMERICAL_ZERO)
        );
        String nextStatusId = null;
        String nextNodeName = null;
        for (KwBusinessWorkFlowNode kwBusinessWorkFlowNode : list) {
            if (Integer.valueOf(kwBusinessWorkFlowNode.getNodeId()) > Integer.valueOf(status)) {
                nextStatusId = kwBusinessWorkFlowNode.getNodeId().toString();
                nextNodeName = kwBusinessWorkFlowNode.getNodeName();
            }
        }
        if (ObjectUtils.isNull(nextStatusId)) {
            return HttpResult.error("当前任务已完成,无法继续执行");
        }

        List<KwBusinessActionTrack> kwBusinessActionTracks = kwBusinessActionTrackMapper.selectList(new QueryWrapper<KwBusinessActionTrack>()
                .eq("mine_order_id", orderId)
                .eq("del_flag", Global.NUMERICAL_ZERO)
        );
        for (KwBusinessActionTrack businessActionTrack : kwBusinessActionTracks) {
            if (businessActionTrack.getStatus().equals(nextStatusId)) {
                return HttpResult.error("当前任务已被执行,请勿重复操作");
            }
        }

        //执行任务
        orderServerCommon.saveActionTrack(orderId, nextStatusId, nextNodeName, nextNodeName);

        //修改订单状态
        LambdaUpdateWrapper<KwBusinessMineOrder> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        objectLambdaUpdateWrapper.set(KwBusinessMineOrder::getStatus, nextStatusId).eq(KwBusinessMineOrder::getId, orderId);
        mineOrderMapper.update(null, objectLambdaUpdateWrapper);

        return HttpResult.ok("操作成功");





    }


}
