package org.jeecg.modules.flowpath.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.flowpath.convert.FlowPathConvert;
import org.jeecg.modules.flowpath.dto.ItdmCreateRunFlowPath;
import org.jeecg.modules.flowpath.entity.ItdmFlowPath;
import org.jeecg.modules.flowpath.entity.ItdmFlowPathStep;
import org.jeecg.modules.flowpath.entity.ItdmRunFlowPath;
import org.jeecg.modules.flowpath.entity.ItdmRunFlowPathStep;
import org.jeecg.modules.flowpath.mapper.*;
import org.jeecg.modules.flowpath.service.IItdmFlowPathStepService;
import org.jeecg.modules.flowpath.service.IItdmRunFlowPathService;
import org.jeecg.modules.itdmFirstPage.entity.ItdmTask;
import org.jeecg.modules.itdmFirstPage.service.IItdmTaskService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.weituo.service.IItdmWeituoInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 运行流程表
 * @Author: jeecg-boot
 * @Date:   2023-07-20
 * @Version: V1.0
 */
@Service
public class ItdmRunFlowPathServiceImpl extends ServiceImpl<ItdmRunFlowPathMapper, ItdmRunFlowPath> implements IItdmRunFlowPathService {
    @Autowired
    @SuppressWarnings("all")
    private ItdmFlowPathMapper itdmFlowPathMapper;

    @Autowired
    @SuppressWarnings("all")
    private ItdmFlowPathStepMapper itdmFlowPathStepMapper;


    @Autowired
    @SuppressWarnings("all")
    private ItdmRunFlowPathMapper itdmRunFlowPathMapper;

    @Autowired
    @SuppressWarnings("all")
    private ItdmRunFlowPathStepMapper itdmRunFlowPathStepMapper;

    @Autowired
    private ItdmFZRunFlowPathLogService logService;

    @Autowired
    @SuppressWarnings("all")
    private IItdmTaskService taskService;
    @Autowired
    @SuppressWarnings("all")
    private ISysRoleService roleService;
    @Autowired
    @SuppressWarnings("all")
    private ISysUserService userService;
    @Autowired
    @SuppressWarnings("all")
    private IItdmWeituoInfoService weituoInfoService;
    @Autowired
    @SuppressWarnings("all")
    private IItdmFlowPathStepService flowPathStepService;


    /**
     * 新增运行流程
     */
    @Override
    @Transactional
    public void createRunFlowPath(ItdmCreateRunFlowPath itdmCreateRunFlowPath) {
        //流程（目前只有唯一一条）
        ItdmFlowPath itdmFlowPath = itdmFlowPathMapper.selectById(itdmCreateRunFlowPath.getFlowPathId());

        if (itdmFlowPath == null || !Objects.equals(itdmFlowPath.getStatus(), "0")) {
            throw new JeecgBootException("流程不存在/流程禁用, 发起失败");
        }

        boolean b = itdmRunFlowPathMapper.exists(Wrappers.lambdaQuery(ItdmRunFlowPath.class).eq(ItdmRunFlowPath::getWeituoNo, itdmCreateRunFlowPath.getWeituoNo()));

        if (b) {
            throw new JeecgBootException("该委托编号已经有流程了");
        }

        //查对应所有流程步骤，按sort正序
        List<ItdmFlowPathStep> list = itdmFlowPathStepMapper.selectList(Wrappers.lambdaQuery(ItdmFlowPathStep.class)
                .eq(ItdmFlowPathStep::getFlowPathId, itdmCreateRunFlowPath.getFlowPathId()).orderByAsc(ItdmFlowPathStep::getSort));

        //当前登录用户
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //新增一条当前运行流程
        ItdmRunFlowPath itdmRunFlowPath = new ItdmRunFlowPath();
        itdmRunFlowPath.setFlowPathId(itdmCreateRunFlowPath.getFlowPathId());
        itdmRunFlowPath.setWeituoNo(itdmCreateRunFlowPath.getWeituoNo());
        itdmRunFlowPath.setName(itdmFlowPath.getName());
        itdmRunFlowPath.setFaqiUser(user.getUsername());
        itdmRunFlowPath.setDqSetp(list.get(0).getId());
//        itdmRunFlowPath.setDqSetpUserIds(list.get(0).getUserIds());
        //当前运行流程的用户改为选择的人
        itdmRunFlowPath.setDqSetpUserIds(itdmCreateRunFlowPath.getUserName());
        itdmRunFlowPath.setDqSetpRoleId(list.get(0).getRoleId());
        itdmRunFlowPath.setStatus("0");//当前运行流程状态0开始2结束
        itdmRunFlowPathMapper.insert(itdmRunFlowPath);

        //新增运行流程后，新增一条我的审批
        ItdmTask itdmTask = new ItdmTask();
        if(list.get(0).getRoleId()!=null  && !"".equals(list.get(0).getRoleId())){
            String role = roleService.getById(list.get(0).getRoleId()).getRoleName();
            itdmTask.setTaskRole(role);//待办角色
        }
        if(list.get(0).getUserIds()!=null && !"".equals(list.get(0).getUserIds())){
//            String userName = userService.getUserByName(list.get(0).getUserIds().split(",")[0]).getRealname();
            //改为选择的人
            String userName = userService.getUserByName(itdmCreateRunFlowPath.getUserName()).getRealname();
            itdmTask.setTaskUser(userName);//待办人员
        }
        Map<String, Object> weituoMap = new HashMap<>();
        weituoMap.put("weituo_no",itdmCreateRunFlowPath.getWeituoNo());
        String weituoId = weituoInfoService.listByMap(weituoMap).get(0).getId();
        itdmTask.setWeituoId(weituoId);//委托id
        String taskContent = flowPathStepService.getById(list.get(0).getId()).getName();//步骤名称
        itdmTask.setTaskContent(taskContent);//当前步骤名
        itdmTask.setTaskStatus(0);//待办
        taskService.insertTaskAfterJudge(itdmTask);

        //新增运行流程步骤
        for (int i = 0; i < list.size(); i++) {
            ItdmFlowPathStep itdmFlowPathStep = list.get(i);
            //第一步的所属用户改为新增时选择的人
            if(itdmFlowPathStep.getSort().equals("1")) itdmFlowPathStep.setUserIds(itdmCreateRunFlowPath.getUserName());
            // todo
            ItdmRunFlowPathStep itdmRunFlowPathStep = FlowPathConvert.INSTANCE.to(itdmFlowPathStep, null,itdmRunFlowPath.getId());
            itdmRunFlowPathStepMapper.insert(itdmRunFlowPathStep);
        }


    }
}
