package com.sckw.mine.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.utils.TenantUtil;
import com.sckw.core.web.response.HttpResult;
import com.sckw.mine.common.OrderServerCommon;
import com.sckw.mine.entity.KwBusinessWorkFlow;
import com.sckw.mine.entity.KwBusinessWorkFlowNode;
import com.sckw.mine.entity.dto.WorkFlowNodeDTO;
import com.sckw.mine.entity.req.WorkFlowInsertParam;
import com.sckw.mine.entity.req.WorkFlowPageListParam;
import com.sckw.mine.entity.req.WorkFlowUpdateParam;
import com.sckw.mine.entity.res.WorkFlowPageListRes;
import com.sckw.mine.enums.WorkFlowTypeEnum;
import com.sckw.mine.mapper.WorkFlowMapper;
import com.sckw.mine.mapper.WorkFlowNodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @desc:
 * @author: Lt
 * @date: 2024-05-31
 */
@Service
public class WorkFlowService {

    @Autowired
    private WorkFlowMapper workFlowMapper;

    @Autowired
    private WorkFlowNodeMapper workFlowNodeMapper;

    @Autowired
    private OrderServerCommon orderServerCommon;

    /**
    * @Description: 流程新增
    * @Author: Lt
    * @Date: 2024/5/31 14:48
    */
    public HttpResult insert(WorkFlowInsertParam param)
    {
        LambdaQueryWrapper<KwBusinessWorkFlow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(KwBusinessWorkFlow::getWorkName, param.getWorkName())
                .eq(KwBusinessWorkFlow::getDelFlag, Global.NUMERICAL_ZERO);
        KwBusinessWorkFlow workFlowExists = workFlowMapper.selectOne(wrapper);
        if(ObjectUtils.isNotNull(workFlowExists)) {
            return HttpResult.error("流程已存在,请重新输入");
        }
        if (param.getWorkFlowNode().isEmpty()) {
            return HttpResult.error("流程节点不能为空");
        }


        KwBusinessWorkFlow kwBusinessWorkFlow = BeanUtil.copyProperties(param, KwBusinessWorkFlow.class);

        String workCode = orderServerCommon.generatorNum("WK", 13);
        Long workFlowId = new IdWorker(1L).nextId();

        String tenantId = TenantUtil.getTenant();
        kwBusinessWorkFlow.setId(workFlowId);
        kwBusinessWorkFlow.setTenantId(tenantId);
        kwBusinessWorkFlow.setNodeCount(param.getWorkFlowNode().size());  //节点数量
        kwBusinessWorkFlow.setWorkCode(workCode);
        workFlowMapper.insert(kwBusinessWorkFlow);
        //流程节点新增
        insertWorkFlowNode(String.valueOf(workFlowId), param.getWorkFlowNode());
        return HttpResult.ok("添加成功");
    }

    /**
    * @Description: 流程编辑
    * @Author: Lt
    * @Date: 2024/5/31 16:39
    */
    public HttpResult update(WorkFlowUpdateParam param)
    {


        LambdaQueryWrapper<KwBusinessWorkFlow> wrapperWorkFlowExists = new LambdaQueryWrapper<>();
        wrapperWorkFlowExists.eq(KwBusinessWorkFlow::getId, param.getId()).eq(KwBusinessWorkFlow::getDelFlag, Global.NUMERICAL_ZERO);
        KwBusinessWorkFlow workFlowExists = workFlowMapper.selectOne(wrapperWorkFlowExists);
        if (ObjectUtils.isNull(workFlowExists)){
            return HttpResult.error("流程不存在,请检查");
        }
        LambdaQueryWrapper<KwBusinessWorkFlow> wrapper = new LambdaQueryWrapper<>();
        wrapper.ne(KwBusinessWorkFlow::getId, param.getId());
        wrapper.eq(KwBusinessWorkFlow::getDelFlag, Global.NUMERICAL_ZERO);
        wrapper.eq(KwBusinessWorkFlow::getWorkName, param.getWorkName());
        KwBusinessWorkFlow workNameExists = workFlowMapper.selectOne(wrapper);
        if (ObjectUtils.isNotNull(workNameExists)) {
            return HttpResult.error("当前流程名称已存在,请重新输入");
        }

        KwBusinessWorkFlow kwBusinessWorkFlow = BeanUtil.copyProperties(param, KwBusinessWorkFlow.class);
        int i = workFlowMapper.updateById(kwBusinessWorkFlow);
        if (i > 0) {
            //先删除所有节点
            LambdaUpdateWrapper<KwBusinessWorkFlowNode> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(KwBusinessWorkFlowNode::getFlowId, param.getId())
                    .eq(KwBusinessWorkFlowNode::getDelFlag, Global.NUMERICAL_ZERO)
                    .set(KwBusinessWorkFlowNode::getDelFlag, Global.NUMERICAL_ONE);
            workFlowNodeMapper.update(null, updateWrapper);

            //流程节点新增
            insertWorkFlowNode(param.getId(), param.getWorkFlowNode());

        }
        return HttpResult.ok("编辑成功");

    }

    /**
    * @Description: 流程节点新增
    * @Author: Lt
    * @Date: 2024/5/31 16:56
    */
    private void insertWorkFlowNode(String flowId,List<WorkFlowNodeDTO> param)
    {
        for (int f = 0; f < param.size(); f++) {
            KwBusinessWorkFlowNode workFlowNode = new KwBusinessWorkFlowNode();
            workFlowNode.setId(new IdWorker(1L).nextId());
            workFlowNode.setFlowId(flowId);
            workFlowNode.setNodeId(param.get(f).getNodeId());
            workFlowNode.setNodeName(param.get(f).getNodeName());
            workFlowNode.setSort(f + 1);
            workFlowNodeMapper.insert(workFlowNode);
        }
    }

    /**
    * @Description: 流程节点分页列表
    * @Author: Lt
    * @Date: 2024/5/31 16:56
    */
    public HttpResult pageList(WorkFlowPageListParam param)
    {
        String tenantId = TenantUtil.getTenant();
        PageHelper.startPage(param.getPage(), param.getPageSize());
        param.setTenantId(tenantId);

        List<WorkFlowPageListRes> workPageListRes = workFlowMapper.pageList(param);
        workPageListRes.forEach(e -> {
            if (ObjectUtils.isNotNull(e.getStatus())) {
                e.setStatusStr(e.getStatus() == 1 ? "启用" : "禁用");
                e.setWorkTypeStr(WorkFlowTypeEnum.getNameByCode(e.getWorkType()));
            }
        });

        return HttpResult.ok(new PageRes<>(new PageInfo<>(workPageListRes)));
    }

    /**
    * @Description: 流程节点详情
    * @Author: Lt
    * @Date: 2024/5/31 17:11
    */
    public HttpResult detail(String id)
    {
        WorkFlowPageListParam param = new WorkFlowPageListParam();
        param.setId(id);
        List<WorkFlowPageListRes> workPageListRes = workFlowMapper.pageList(param);
        if (!workPageListRes.isEmpty()){

            WorkFlowPageListRes returnData = workPageListRes.get(0);
            returnData.setStatusStr(returnData.getStatus() == 1 ? "启用" : "禁用");
            returnData.setWorkTypeStr(WorkFlowTypeEnum.getNameByCode(returnData.getWorkType()));
            return HttpResult.ok(returnData);
        }
        return HttpResult.ok(null);
    }

    /**
     * @Description: 状态操作(停用 启用)   1=启用   2=禁用
     * @Author: Lt
     * @Date: 2024/5/31 11:34
     */
    public HttpResult statusAction(String id, Integer status)
    {
        if (StringUtils.isBlank(id)) {
            throw new RuntimeException("id必填");
        }
        if(status==null) {
            throw new RuntimeException("状态必填");
        }
        KwBusinessWorkFlow kwBusinessNode = workFlowMapper.selectById(id);
        if (ObjectUtils.isNull(kwBusinessNode)) {
            throw new RuntimeException("当前数据不存在,请检查");
        }

        int i = workFlowMapper.statusAction(id, status);
        if (i>0) {
            return HttpResult.ok("操作成功");
        }
        return HttpResult.error("操作失败");
    }

    public HttpResult workFlowDelete(String id) {

        KwBusinessWorkFlow kwBusinessWorkFlow = workFlowMapper.selectById(id);
        if (kwBusinessWorkFlow.getStatus().equals(1)){
            return HttpResult.error("当前流程使用中,无法删除");
        }

        LambdaUpdateWrapper<KwBusinessWorkFlow> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(KwBusinessWorkFlow::getDelFlag, Global.NUMERICAL_ONE)
                .eq(KwBusinessWorkFlow::getId, id);
        int update = workFlowMapper.update(null, updateWrapper);
        if(update > 0) {
            LambdaUpdateWrapper<KwBusinessWorkFlowNode> objectLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            objectLambdaUpdateWrapper.eq(KwBusinessWorkFlowNode::getFlowId, id)
                            .set(KwBusinessWorkFlowNode::getDelFlag, Global.NUMERICAL_ONE);
            workFlowNodeMapper.update(null, objectLambdaUpdateWrapper);
        }
        return HttpResult.ok("删除成功");
    }


}
