package com.willalp.flow.service.impl;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.willalp.common.core.domain.entity.SysUser;
import com.willalp.common.core.domain.model.LoginUser;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.SecurityUtils;
import com.willalp.common.utils.StringUtils;
import com.willalp.erms.domain.HsGoodsStorage;
import com.willalp.erms.service.IHsGoodsStorageService;
import com.willalp.files.service.IHsOrgPersonnelFilesService;
import com.willalp.flow.domain.*;
import com.willalp.flow.domain.enums.FlowEnum;
import com.willalp.flow.domain.json.Operators;
import com.willalp.flow.domain.req.FlowReq;
import com.willalp.flow.mapper.*;
import com.willalp.flow.service.*;
import com.willalp.msg.domain.HsAppUserMsg;
import com.willalp.msg.service.IHsAppUserMsgService;
import com.willalp.system.domain.HsPostConfig;
import com.willalp.system.domain.vo.PostTreeVo;
import com.willalp.system.service.IHsPostConfigService;
import com.willalp.system.service.ISysConfigService;
import com.willalp.wx.domain.WxMsgTemplateApproval;
import com.willalp.wx.enums.WxTemplateKeyEnum;
import com.willalp.wx.service.WxMsgService;
import com.willalp.wx.utils.WxUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class HsFlowEngineServiceImpl implements HsFlowEngineService {

    @Resource
    private HsFlowBaseMapper hsFlowBaseMapper;

    @Resource
    private IHsFlowBaseService flowBaseService;

    @Resource
    private IHsFlowCcService flowCcService;

    @Resource
    private HsFlowExamplesMapper hsFlowExamplesMapper;

    @Resource
    private HsFlowModelMapper hsFlowModelMapper;

    @Resource
    private IHsFlowRunningRecordService flowRunningRecordService;

    @Resource
    private HsFlowTaskMapper hsFlowTaskMapper;

    @Resource
    private HsFlowCcMapper hsFlowCcMapper;

    @Resource
    private HsFlowConditionModelMapper flowConditionModelMapper;

    @Resource
    private IHsFlowConditionModelService conditionModelService;

    @Resource
    private IBizLeaveImgService leaveImgService;

    @Resource
    private IHsGoodsStorageService goodsStorageService;

    @Resource
    private IHsOrgPersonnelFilesService opfService;

    @Resource
    private WxMsgService wxMsgService;

    @Resource
    private WxUtils wxUtils;

    @Resource
    private IHsAppUserMsgService userMsgService;

    @Resource
    private IHsFlowTaskService taskService;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private IHsPostConfigService postConfigService;


    @Override
    public Map<String, Object> submitTask(HsFlowTask task, Map<String, Object> params) {
        String examplesId = task.getExamplesId();
        if (StringUtils.isBlank(examplesId)) {
            throw new BaseException("EXAMPLES_ID - IS_NULL");
        }
        HsFlowExamples hsFlowExamples = hsFlowExamplesMapper.selectById(examplesId);
        if (null == hsFlowExamples) {
            throw new BaseException("流程实例为定义或找不到");
        }
        HsFlowBase hsFlowBase = hsFlowBaseMapper.firstFlowBase(examplesId);
        if (null == hsFlowBase) {
            throw new BaseException("请创建实例");
        }
        task.setBaseGroupId(hsFlowBase.getGroupId());
        //判断是否存在上级节点 不存在则为父级组件 然后跳过
        if (StringUtils.isBlank(hsFlowBase.getUpStepId())) {
            if (StringUtils.isNotBlank(hsFlowBase.getDownStepId())) {
                hsFlowBase = hsFlowBaseMapper.selectById(hsFlowBase.getDownStepId());
            } else {
                throw new BaseException("流程配置错误");
            }
        }
        //判断提交时流程条件，更新至对应组件
        hsFlowBase = getFlowBaseByTermResult(task.getId(), hsFlowBase, params);
        if (StringUtils.isBlank(hsFlowBase.getDownStepId())) {
            task.setIsCandidate(ONE);
        } else {
            HsFlowBase base = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(task.getBaseGroupId(), hsFlowBase.getDownStepId());
            if (base != null && !base.getModelType().equals(APPROVAL) && StringUtils.isBlank(base.getDownStepId())) {
                task.setIsCandidate(ONE);
            }
        }
        task.setInitiator(SecurityUtils.getUsername());
        task.setBaseId(hsFlowBase.getId());
        task.setBaseName(hsFlowBase.getFlowModuleName());
        task.setTaskName(hsFlowExamples.getExamplesName());
        task.setCreateTime(new Date());
        //获取候选人
        if (ObjectUtils.isNotNull(params)) {
            String userName = (String) params.get("candidate");
            if (StringUtils.isNotBlank(userName)) {
                task.setOperator(userName);
            }
        }
        try {
            hsFlowTaskMapper.insert(task);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("提交失败");
        }
        //启动超时删除线程
        taskService.removeWaitTimeOutTask(task);
        Map<String, Object> map = new HashMap<>(4);
        map.put("taskId", task.getId());
        map.put("tree", getApprovalTreePost(task.getBaseGroupId(), task.getBaseId()));
        return map;
    }

    @Override
    public int submitCandidate(String taskId, String candidate, String applyUserName) {
        HsFlowTask hsFlowTask = hsFlowTaskMapper.selectById(taskId);
        if (hsFlowTask == null) {
            throw new BaseException("超时未提交任务已过期");
        }
        String content = null;
        try {
            //生成审批结果消息列表
            String examplesId = hsFlowTask.getExamplesId();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            HsFlowExamples example = hsFlowExamplesMapper.selectById(examplesId);
            Map<String, Object> formData = hsFlowTaskMapper
                    .selectBusinessCase(example.getBusinessTableName(), hsFlowTask.getBusinessId());
            if (examplesId.equals(sysConfigService.selectConfigByKey(HsFlowEngineService.BIZ_LEAVE_FLOW_KEY))) {
                String leaveStartTime = DateUtils.dateTime(sdf.parse(formData.get("leave_start_time").toString()));
                String leaveEndTime = DateUtils.dateTime(sdf.parse(formData.get("leave_end_time").toString()));
                content = "<p>标题：" + formData.get(TITLE) + P_LABEL_TAIL +
                        "<p>申请人：" + formData.get(APPLY_USER_NAME) + P_LABEL_TAIL +
                        "<p>开始时间：" + leaveStartTime + P_LABEL_TAIL +
                        "<p>结束时间：" + leaveEndTime + P_LABEL_TAIL;
            } else if (examplesId.equals(sysConfigService.selectConfigByKey(HsFlowEngineService.RESERVE_FLOW_KEY))) {
                HsGoodsStorage goodsStorage = goodsStorageService.getById(formData.get("good_id") + "");
                if (goodsStorage != null) {
                    content = "<p>标题：" + formData.get(TITLE) + P_LABEL_TAIL +
                            "<p>申请人：" + formData.get(APPLY_USER_NAME) + P_LABEL_TAIL +
                            "<p>物资名称：" + goodsStorage.getName() + P_LABEL_TAIL +
                            "<p>申请数量：" + formData.get("amount") + goodsStorage.getUnit() + P_LABEL_TAIL;
                }
            } else {
                content = "<p>标题：" + formData.get(TITLE) + P_LABEL_TAIL +
                        "<p>申请人：" + formData.get(APPLY_USER_NAME) + P_LABEL_TAIL;
            }
            //异步生成审批消息列表
            userMsgService.saveApprovalMsgAndPush(ONE,
                    String.valueOf(formData.get(TITLE)), content, taskId,
                    candidate, applyUserName, new Date());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(candidate)) {
            hsFlowTask.setOperator(candidate);
            if (0 < hsFlowTaskMapper.updateById(hsFlowTask)) {
                return 1;
            }
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int nextStep(FlowReq flow) {
        if (StringUtils.isBlank(flow.getTaskId())) {
            throw new BaseException("FLOW_TASK_ID - IS_NULL");
        }
        if (StringUtils.isBlank(flow.getResult())) {
            throw new BaseException("FLOW_RESULT - IS_NULL");
        }
        //获取任务实例并验证
        HsFlowTask hsFlowTask = hsFlowTaskMapper.selectById(flow.getTaskId());
        if (null == hsFlowTask) {
            throw new BaseException("没有找到任务实例");
        }
        if (!SecurityUtils.getUsername().equals(hsFlowTask.getOperator())) {
            throw new BaseException("无操作权限");
        }
        if (ONE.equals(hsFlowTask.getIsEnd())) {
            throw new BaseException("任务已结束");
        }
        if (StringUtils.isBlank(flow.getBaseId())) {
            throw new BaseException("FLOW_BASE_ID - IS_NULL");
        }
        if (StringUtils.isBlank(hsFlowTask.getBaseGroupId())) {
            throw new BaseException("FLOW_BASE_GROUP_ID - IS_NULL");
        }
        //获取当前基础组件并验证
        HsFlowBase flowBase = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(hsFlowTask.getBaseGroupId(), flow.getBaseId());
        //判断是否存在上级节点 不存在则为父级组件 然后跳过
        if (StringUtils.isBlank(flowBase.getUpStepId())) {
            if (StringUtils.isNotBlank(flowBase.getDownStepId())) {
                flowBase = hsFlowBaseMapper.selectById(flowBase.getDownStepId());
            } else {
                throw new BaseException("流程配置错误");
            }
        }
        String stepId = null;
        //获取是否 是同意结果
        boolean resultTrue = FlowEnum.RESULT_TRUE.getValue().equals(flow.getResult());
        boolean resultCaseOf = FlowEnum.RESULT_CASE_OF.getValue().equals(flow.getResult());
        Map<String, Object> formData = flow.getFormData();
        //申请人[userCode]
        String applyUserId = String.valueOf(formData.get("apply_user_id"));
        //操作人信息
        SysUser operator;
        String username = null;
        String nickName = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (null != loginUser && null != loginUser.getUser()) {
            username = loginUser.getUser().getUserName();
            nickName = loginUser.getUser().getNickName();
        }
        List<HsFlowRunningRecord> list = new ArrayList<>();
        //生成审批记录
        HsFlowRunningRecord frr = new HsFlowRunningRecord();
        frr.setBaseId(flow.getBaseId());
        frr.setTaskId(flow.getTaskId());
        frr.setCreateTime(new Date());
        //当前流程名 + 操作人
        String frrComment = hsFlowTask.getBaseName() + "：" + nickName;
        frr.setOperator(username);
        frr.setYesOrNo(flow.getResult());
        list.add(frr);
        if (resultCaseOf) {
            //转交
            hsFlowTask.setOperator(flow.getNextApproval());
            frr.setComment("转交至 " + flow.getNextUserName());
            frr.setOperator(SecurityUtils.getUsername());
            frr.setYesOrNo(flow.getResult());
        } else {
            if (resultTrue) {
                //同意
                frr.setComment(frrComment + (StringUtils.equals(CONSENT, flow.getComment()) ? " - " + CONSENT : " - " + CONSENT + "：" + flow.getComment()));
                flowBase = baseRun(flowBase, hsFlowTask, formData);
            } else {
                //拒绝
                frr.setComment(frrComment + (StringUtils.equals(REJECT, flow.getComment()) ? " - " + REJECT : " - " + REJECT + "：" + flow.getComment()));
                stepId = flow.getRejectBaseId();
                flowBase = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(hsFlowTask.getBaseGroupId(), stepId);
            }
        }
        //任务结束
        if (flowBase == null && !resultCaseOf) {
            hsFlowTask.setBaseId(null);
            hsFlowTask.setOperator(hsFlowTask.getOperator());
            hsFlowTask.setIsEnd(ONE);
            hsFlowTask.setRemark(TASK_END_CN_TEXT);
            HsFlowRunningRecord frrEnd = new HsFlowRunningRecord();
            frrEnd.setComment(TASK_AUTO_END_CN_TEXT);
            frrEnd.setOperator(SecurityUtils.getUsername());
            frrEnd.setTaskId(flow.getTaskId());
            frrEnd.setCreateTime(new Date(System.currentTimeMillis() + 1000));
            list.add(frrEnd);
            //生成审批结果消息列表
            HsAppUserMsg appUserMsg = new HsAppUserMsg();
            appUserMsg.setMsgContent("您的 [" + formData.get(TITLE) + "] 申请" + (resultTrue ? APPROVED : DENIED));
            appUserMsg.setMsgTitle("审批结果");
            appUserMsg.setMsgIsRead(ZERO);
            appUserMsg.setUserCode(applyUserId);
            appUserMsg.setMsgType(FOUR);
            appUserMsg.setIsPush(ZERO);
            appUserMsg.setRemark(hsFlowTask.getId());
            appUserMsg.setCreateTime(new Date());
            userMsgService.save(appUserMsg);
            //推送微信审批结果通知
            wxMsgService.sendResultMsg(String.valueOf(formData.get(TITLE)), resultTrue ? APPROVED : DENIED, applyUserId);
        } else {
            //任务继续
            hsFlowTask.setMsgIsRead(ZERO);
            hsFlowTask.setOperator(flow.getNextApproval());
            hsFlowTask.setBaseName(flowBase.getFlowModuleName());
            hsFlowTask.setBaseId(flowBase.getId());
            if (StringUtils.isNotBlank(flowBase.getDownStepId())) {
                HsFlowBase nextFlowBase = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(hsFlowTask.getBaseGroupId(), flowBase.getDownStepId());
                if (nextFlowBase != null && nextFlowBase.getModelType().equals(APPROVAL)) {
                    hsFlowTask.setIsCandidate(ZERO);
                } else {
                    hsFlowTask.setIsCandidate(ONE);
                }
            } else {
                hsFlowTask.setIsCandidate(ONE);
            }
            //生成审批结果消息列表
            HsAppUserMsg appUserMsg = new HsAppUserMsg();
            String content = null;
            String examplesId = hsFlowTask.getExamplesId();
            if (examplesId.equals(sysConfigService.selectConfigByKey(HsFlowEngineService.BIZ_LEAVE_FLOW_KEY))) {
                content = "<p>标题：" + formData.get(TITLE) + P_LABEL_TAIL +
                        "<p>申请人：" + formData.get(APPLY_USER_NAME) + P_LABEL_TAIL +
                        "<p>开始时间：" + formData.get("leave_start_time").toString() + P_LABEL_TAIL +
                        "<p>结束时间：" + formData.get("leave_end_time").toString() + P_LABEL_TAIL;
            } else if (examplesId.equals(sysConfigService.selectConfigByKey(HsFlowEngineService.RESERVE_FLOW_KEY))) {
                HsGoodsStorage goodsStorage = goodsStorageService.getById(formData.get("good_id") + "");
                if (goodsStorage != null) {
                    content = "<p>标题：" + formData.get(TITLE) + P_LABEL_TAIL +
                            "<p>申请人：" + formData.get(APPLY_USER_NAME) + P_LABEL_TAIL +
                            "<p>物资名称：" + goodsStorage.getName() + P_LABEL_TAIL +
                            "<p>申请数量：" + formData.get("amount") + goodsStorage.getUnit() + P_LABEL_TAIL;
                }
            } else {
                content = "<p>标题：" + formData.get(TITLE) + P_LABEL_TAIL +
                        "<p>申请人：" + formData.get(APPLY_USER_NAME) + P_LABEL_TAIL;

            }
            appUserMsg.setMsgContent(content);
            appUserMsg.setMsgTitle(String.valueOf(formData.get(TITLE)));
            appUserMsg.setMsgIsRead(ZERO);
            appUserMsg.setUserCode(hsFlowTask.getOperator());
            appUserMsg.setMsgType(ONE);
            appUserMsg.setIsPush(ZERO);
            appUserMsg.setRemark(hsFlowTask.getId());
            appUserMsg.setCreateTime(new Date());
            userMsgService.save(appUserMsg);
            //推送微信待审批通知
            WxMsgTemplateApproval wxMsgTemplateApproval = new WxMsgTemplateApproval();
            wxMsgTemplateApproval.setThing5(wxUtils.getFormat(String.valueOf(formData.get(TITLE))));
            wxMsgTemplateApproval.setThing11(wxUtils.getFormat(String.valueOf(formData.get(APPLY_USER_NAME))));
            wxMsgTemplateApproval.setTime12(wxUtils.getFormat(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date())));
            wxMsgService.sendQRCodeMsg(hsFlowTask.getOperator(), wxMsgTemplateApproval, WxTemplateKeyEnum.APPROVAL_WAIT, true);
        }
        hsFlowTaskMapper.updateById(hsFlowTask);
        flowRunningRecordService.saveBatch(list);
        return 1;
    }

    @Override
    public HsFlowBase baseRun(HsFlowBase base, HsFlowTask task, Map<String, Object> formData) {
        switch (base.getModelType()) {
            case APPROVAL:
                //直接获取下一级节点
                base = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(task.getBaseGroupId(), base.getDownStepId());
                //如果下一个不是审批组件则再进行一步，如抄送，延时处理，触发器等
                if (base != null && !APPROVAL.equals(base.getModelType())) {
                    return baseRun(base, task, formData);
                } else {
                    return base;
                }
            case DELAY:
                //延时处理节点
                break;
            case TRIGGER:
                //触发器节点
                break;
            case CONCURRENT:
                //并行节点
                break;
            case CONDITIONS:
                //设置条件组ID，并与父级ID组合为复合主键确认唯一性（逻辑唯一）
                return getFlowBaseByTermResult(task.getId(), base, formData);
            case CONDITION:
                //解析单个条件中的详细数据
                break;
            case CC:
                //抄送节点
                HsFlowCc cc = new HsFlowCc();
                cc.setId(IdWorker.getIdStr());
                cc.setExamplesId(task.getExamplesId());
                cc.setFormData(JSON.toJSONString(formData));
                cc.setTaskId(task.getId());
                cc.setTitle(task.getTaskName());
                cc.setCreateTime(new Date());
                cc.setUpdateTime(new Date());
                cc.setRemark("0");
                Operators operators = JSON.parseObject(base.getOperator(), Operators.class);
                List<Operators.OperatorDto> assignedUser = operators.getAssignedUser();
                List<String> sbUid = new ArrayList<>();
                StringBuilder sbUname = new StringBuilder();
                if (0 != assignedUser.size()) {
                    for (int i = 0; i < assignedUser.size(); i++) {
                        if (i != (assignedUser.size() - 1)) {
                            sbUid.add(assignedUser.get(i).getId() + ",");
                            sbUname.append(assignedUser.get(i).getName()).append(",");
                        } else {
                            sbUid.add(assignedUser.get(i).getId());
                            sbUname.append(assignedUser.get(i).getName());
                        }
                    }
                }
                List<PostTreeVo> postTreeVos = new ArrayList<>();
                for (String id : sbUid) {
                    HsPostConfig postConfig = postConfigService.getBaseMapper().selectOne(new QueryWrapper<HsPostConfig>()
                            .eq("id", id));
                    cc.setUsers(postConfig.getPostUserG());
                    postTreeVos.addAll(postConfigService.setUsers(postConfig));
                }
                HsFlowRunningRecord frrCc = new HsFlowRunningRecord();
                frrCc.setBaseId(base.getId());
                frrCc.setTaskId(task.getId());
                frrCc.setCreateTime(new Date());
                frrCc.setComment("已抄送至：" + sbUname);
                frrCc.setOperator(SecurityUtils.getUsername());
                frrCc.setYesOrNo(FlowEnum.CC.getValue());
                //先持久化抄送数据
                flowCcService.save(cc);
                flowRunningRecordService.save(frrCc);
                List<HsAppUserMsg> msgs = new ArrayList<>();
                //再发送推送和生成审批结果消息列表
                if (0 != postTreeVos.size()) {
                    for (PostTreeVo postTreeVo : postTreeVos) {
                        //再发送推送和生成审批结果消息列表
                        HsAppUserMsg appUserMsg = new HsAppUserMsg();
                        appUserMsg.setMsgContent(formData.get(APPLY_USER_NAME) + "的 [" + formData.get(TITLE) + "]");
                        appUserMsg.setMsgTitle(CC_TITLE);
                        appUserMsg.setMsgIsRead(ZERO);
                        appUserMsg.setUserCode(postTreeVo.getValue());
                        appUserMsg.setMsgType(SEVEN);
                        appUserMsg.setIsPush(ZERO);
                        appUserMsg.setRemark(cc.getId());
                        appUserMsg.setCreateTime(new Date());
                        msgs.add(appUserMsg);
                        if (StringUtils.isBlank(base.getDownStepId())) {
                            wxMsgService.sendResultMsg(CC_TITLE + " - " + formData.get(TITLE), APPROVED, postTreeVo.getValue());
                        } else {
                            base = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(task.getBaseGroupId(), base.getDownStepId());
                            wxMsgService.sendResultMsg(CC_TITLE + " - " + formData.get(TITLE), UNDERWAY, postTreeVo.getValue());
                        }
                    }
                    userMsgService.saveBatch(msgs);
                }
                if (StringUtils.isNotBlank(base.getDownStepId())) {
                    return flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(task.getBaseGroupId(), base.getDownStepId());
                } else {
                    return null;
                }
            case ROOT:
            default:
                break;
        }
        throw new BaseException("流程配置出错");
    }


    /**
     * 通过条件组件判断结果获取流程组件
     *
     * @param hsFlowBase
     * @param params
     * @return
     */
    private HsFlowBase getFlowBaseByTermResult(String taskId, HsFlowBase hsFlowBase, Map<String, Object> params) {
        //判断当前组件有无条件组件
        if (StringUtils.isNotBlank(hsFlowBase.getTermModuleId()) &&
                null != params) {
            //遍历绑定的条件组件 查找下一步 （待添加条件级别优化）
            List<HsFlowConditionModel> hsFlowConditionModels = flowConditionModelMapper.queryConditionGroup(
                    hsFlowBase.getUpStepId(), hsFlowBase.getTermModuleId());
            for (HsFlowConditionModel item : hsFlowConditionModels) {
                String paramName = item.getParamName();
                String[] s = paramName.split("_");
                StringBuilder appendStr = new StringBuilder();
                if (0 != s.length) {
                    appendStr.append(s[0]);
                    for (int i = 1; i < s.length; i++) {
                        appendStr.append(s[i].substring(0, 1).toUpperCase()).append(s[i].substring(1));
                    }
                    paramName = appendStr.toString();
                }
                if (null != params.get(paramName)) {
                    if (conditionModelService.executeConditionJudgment(item, params.get(paramName))) {
                        //对应条件组件
                        HsFlowBase termModule = hsFlowBaseMapper.selectOne(
                                new QueryWrapper<HsFlowBase>().eq("term_module_id", item.getId()));
                        if (null == termModule) {
                            throw new BaseException("流程条件配置出错");
                        }
                        //通过条件组件获取审批组件
                        if (StringUtils.isBlank(termModule.getDownStepId())) {
                            throw new BaseException("流程条件配置出错，没有后续审批人");
                        }
                        HsFlowBase taskCurrentBase = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(termModule.getGroupId()
                                , termModule.getDownStepId());
                        if (null == taskCurrentBase) {
                            throw new BaseException("流程条件配置出错");
                        }
                        return taskCurrentBase;
                    }
                }
            }
            hsFlowTaskMapper.deleteById(taskId);
            flowRunningRecordService.remove(new QueryWrapper<HsFlowRunningRecord>()
                    .eq("task_id", taskId));
            throw new BaseException("流程条件未满足，流程关闭，请重新发起");
        } else {
            return hsFlowBase;
        }
    }

    @Override
    public List<HsFlowTask> getToDoByTaskId(String taskId) {
        if (StringUtils.isBlank(taskId)) {
            return null;
        }
        List<HsFlowTask> hsFlowTasks = hsFlowTaskMapper.selectList(new QueryWrapper<HsFlowTask>()
                .eq("id", taskId));
        return getHsFlowTasks(hsFlowTasks);
    }

    @Override
    public List<HsFlowTask> getTaskIdByCcId(String ccId) {
        if (StringUtils.isBlank(ccId)) {
            return null;
        }
        HsFlowCc hsFlowCc = hsFlowCcMapper.selectById(ccId);
        List<HsFlowTask> hsFlowTasks = hsFlowTaskMapper.selectList(new QueryWrapper<HsFlowTask>()
                .eq("id", hsFlowCc.getTaskId()));
        return getHsFlowTasks(hsFlowTasks);
    }


    @Override
    public List<HsFlowTask> getToDo(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return null;
        }
        List<HsFlowTask> hsFlowTasks = hsFlowTaskMapper.selectAllByOperator(userCode);
        return getHsFlowTasks(hsFlowTasks);
    }

    @Override
    public List<HsFlowTask> getInitiator(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return null;
        }
        List<HsFlowTask> hsFlowTasks = hsFlowTaskMapper.selectAllByInitiator(userCode);
        return getHsFlowTasks(hsFlowTasks);
    }

    @Override
    public List<HsFlowTask> getDone(String userCode) {
        if (StringUtils.isBlank(userCode)) {
            return null;
        }
        List<HsFlowTask> hsFlowTasks = hsFlowTaskMapper.getDone(userCode);
        return getHsFlowTasks(hsFlowTasks);
    }

    private List<HsFlowTask> getHsFlowTasks(List<HsFlowTask> hsFlowTasks) {
        if (0 != hsFlowTasks.size()) {
            List<HsFlowExamples> hsFlowExamples = hsFlowExamplesMapper.selectHsFlowExamplesList(null);
            hsFlowTasks.forEach(item -> {
                String businessId = item.getBusinessId();
                if (0 != hsFlowExamples.size()) {
                    hsFlowExamples.forEach(example -> {
                        if (StringUtils.isNotBlank(businessId)) {
                            //查询业务数据
                            Map<String, Object> stringObjectMap = hsFlowTaskMapper
                                    .selectBusinessCase(example.getBusinessTableName(), businessId);
                            if (ObjectUtils.isNotNull(stringObjectMap)) {
                                if ("biz_leave".equals(example.getBusinessTableName())) {
                                    //请假流程添加图片
                                    List<Map<String, Object>> leaveImgs = leaveImgService.getBaseMapper().selectMaps(new QueryWrapper<BizLeaveImg>().eq("biz_leave_id", businessId));
                                    stringObjectMap.put("imgUrls", leaveImgs);
                                }
                                if ("hs_goods_storage_record".equals(example.getBusinessTableName())) {
                                    //物资流程物资数据
                                    Map<String, Object> goods = goodsStorageService.flowGetGoodsById(String.valueOf(stringObjectMap.get("goods_id")));
                                    stringObjectMap.put("goodsData", goods);
                                }
                                if ("personnel_hire_approval".equals(example.getBusinessTableName())) {
                                    //人员数据
                                    Map<String, Object> personnel = opfService.flowGetFilesById(String.valueOf(stringObjectMap.get("personnel_id")));
                                    stringObjectMap.put("personnelData", personnel);
                                }
                                //统一时间类型字段处理
                                Set<String> strings = stringObjectMap.keySet();
                                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
                                strings.forEach(str -> {
                                    if (StringUtils.isNotBlank(str) && str.contains("time") || str.contains("date")) {
                                        if (stringObjectMap.get(str) instanceof LocalDateTime) {
                                            stringObjectMap.put(str, formatter.format((LocalDateTime) stringObjectMap.get(str)));
                                        }
                                    }
                                });
                                item.setFormData(new JSONObject(stringObjectMap));
                            }
                        }
                    });
                }
            });
        }
        return hsFlowTasks;
    }

    @Override
    public List<HsFlowRunningRecord> currentTaskRecords(String taskId) {
        if (StringUtils.isNotBlank(taskId)) {
            HsFlowRunningRecord hsFlowRunningRecord = new HsFlowRunningRecord();
            hsFlowRunningRecord.setTaskId(taskId);
            return flowRunningRecordService.selectHsFlowRunningRecordList(hsFlowRunningRecord);
        }
        return null;
    }

    @Override
    public List<HsFlowRunningRecord> rejectTaskRecords(String taskId) {
        if (StringUtils.isNotBlank(taskId)) {
            HsFlowTask task = taskService.getById(taskId);
            if (task == null) {
                throw new BaseException("task not found");
            }
            List<HsFlowRunningRecord> flowRunningRecords = new ArrayList<>();
            HsFlowRunningRecord hsFlowRunningRecord = new HsFlowRunningRecord();
            hsFlowRunningRecord.setTaskId(taskId);
            hsFlowRunningRecord.setComment("发起人");
            hsFlowRunningRecord.setYesOrNo("LAUNCH");
            flowRunningRecords.add(hsFlowRunningRecord);
            List<HsFlowRunningRecord> records = flowRunningRecordService.getBaseMapper().selectList(new QueryWrapper<HsFlowRunningRecord>()
                    .eq("task_id", taskId).last("AND yes_or_no = 'RESULT_TRUE' GROUP BY base_id"));

            for (HsFlowRunningRecord record : records) {
                if (StringUtils.isNotBlank(record.getBaseId()) &&
                        StringUtils.equals(record.getBaseId(), task.getBaseId())) {
                    break;
                }
                String comment = record.getComment();
                record.setComment(comment.substring(0, comment.indexOf("-")));
                flowRunningRecords.add(record);
            }
            return flowRunningRecords;
        }
        return new ArrayList<>();
    }

    @Override
    public int revoke(String taskId) {
        if (StringUtils.isNotBlank(taskId)) {
            long selectCount = flowRunningRecordService.getBaseMapper().selectCount(new QueryWrapper<HsFlowRunningRecord>()
                    .eq("task_id", taskId));
            if (selectCount > 0) {
                throw new BaseException("已有审批结果无法撤销");
            }
            return hsFlowTaskMapper.deleteById(taskId);
        }
        return 0;
    }

    @Override
    public int removeBusinessForm(String examplesId, String businessId) {
        if (!(StringUtils.isNotBlank(examplesId) && StringUtils.isNotBlank(businessId))) {
            throw new BaseException("关键参数为空无法删除业务表单");
        }
        HsFlowExamples hsFlowExamples = hsFlowExamplesMapper.selectById(examplesId);
        if (null == hsFlowExamples) {
            throw new BaseException("FLOW_EXAMPLES_NUll");
        }
        String businessTableName = hsFlowExamples.getBusinessTableName();
        if (StringUtils.isNotBlank(businessTableName)) {
            return hsFlowExamplesMapper.removeBusinessForm(businessTableName, businessId);
        }
        return 0;
    }

    @Override
    public List<PostTreeVo> getApprovalTreePost(String groupId, String baseId) {
        HsFlowBase flowTaskCurrentBase = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(groupId, baseId);
        if (null == flowTaskCurrentBase) {
            return null;
        }
        //如果是抄送组件
        if (CC.equals(flowTaskCurrentBase.getModelType())) {
            String downStepId = flowTaskCurrentBase.getDownStepId();
            if (StringUtils.isNotBlank(downStepId)) {
                flowTaskCurrentBase = flowBaseService.getFlowTaskBaseByGroupIdAndBaseId(groupId, downStepId);
            } else {
                return null;
            }
        }
        Operators operators = JSON.parseObject(flowTaskCurrentBase.getOperator(), Operators.class);
        List<Operators.OperatorDto> assignedUser = operators.getAssignedUser();
        List<PostTreeVo> list = new ArrayList<>();
        PostTreeVo postTreeVo = new PostTreeVo();
        postTreeVo.setText(flowTaskCurrentBase.getFlowModuleName());
        postTreeVo.setValue(flowTaskCurrentBase.getId());
        if (0 != assignedUser.size()) {
            List<HsPostConfig> postConfigs = postConfigService.getBaseMapper().selectList(new QueryWrapper<HsPostConfig>()
                    .eq("id", assignedUser.get(0).getId()));
            postTreeVo.setChildren(postConfigService.getTreePost(postConfigs).get(0).getChildren());
        }
        list.add(postTreeVo);
        return list;
    }

    @Override
    public List<PostTreeVo> getNextApprovalTreePost(String groupId, String baseId) {
        HsFlowBase nextFlowTaskBase = flowBaseService.getNextFlowTaskBase(groupId, baseId);
        if (null == nextFlowTaskBase) {
            return null;
        }
        return getApprovalTreePost(groupId, nextFlowTaskBase.getId());
    }

    public static void main(String[] args) {
        int[][] array = {
                {1, 2, 3, 1, 2, 3},
                {4, 5, 6, 1, 2, 3},
                {7, 8, 9, 1, 2, 3},
                {7, 8, 9, 1, 2, 3},
                {7, 8, 9, 1, 2, 3},
                {7, 8, 9, 1, 2, 3}
        };
        int column = 0;
        int sum = 0;
        //高
        int height = array.length;
        //宽
        int width = array[0].length;
        if (width != height) {
            return;
        }
        int sumItem = width * height;
        if (sumItem % 2 == 0) {
            //偶数
            for (int i = 0; i < array.length; i++) {
                sum += array[i][column];
                column++;
            }
            column = width - 1;
            for (int i = array.length - 1; i >= 0; i--) {
                sum += array[i][column];
                column--;
            }
            System.out.println("SUM - " + sum);
        } else {
            //奇数
        }
    }
}

