package com.zjrs.zwnw.sxgl.blo.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.mohrss.leaf.core.framework.domain.blo.impl.BLOImpl;
import org.mohrss.leaf.core.framework.persistens.PageResult;
import org.mohrss.leaf.core.framework.persistens.PageUtil;
import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.util.SecurityUtils;
import com.zjrs.zwnw.sxgl.blo.SxpzxxBLO;
import com.zjrs.zwnw.sxgl.dto.*;
import com.zjrs.zwnw.sxgl.entity.*;
import com.zjrs.zwnw.sxgl.po.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SxpzxxBLOimpl extends BLOImpl implements SxpzxxBLO {
    private static final Logger LOG = LoggerFactory.getLogger(SxpzxxBLOimpl.class);
    @Resource
    SxpzxxMapper sxpzxxMapper;
    @Resource
    FwdxMapper fwdxMapper;
    @Resource
    SdszzcxxMapper sdszzcxxMapper;
    @Resource
    SxclwhMapper sxclwhMapper;
    @Resource
    SxlcxxMapper sxlcxxMapper;
    @Resource
    YwlbzcxxMapper ywlbzcxxMapper;
    @Resource
    FwrightMapper fwrightMapper;
    @Resource
    WfactiondefMapper wfactiondefMapper;
    @Resource
    Wfactiondef2taskMapper wfactiondef2taskMapper;
    @Resource
    FwrightidsxlbMapper fwrightidsxlbMapper;
    @Resource
    SxpzxxfileMapper sxpzxxfileMapper;


    @Override
    public PageResult querySxList(SxpzxxQueryDTO dto, int page, int rows) {
        QueryWrapper<SxpzxxPO> queryWrapper = new QueryWrapper<SxpzxxPO>();
        //排序：修改时间降序
        queryWrapper.orderByDesc("ts_czsj", "sxbm");
        queryWrapper.eq("yxbz", "1");

        //基本编码-实施部门名称
        if (StringUtils.isNotBlank(dto.getSsbmmc())) {
            queryWrapper.eq("ssbmmc", dto.getSsbmmc());
        }
        //实施状态（实施状态：1确认，2取消，3未确认）注：材料清单管理列表必传sszt=1
        if (StringUtils.isNotBlank(dto.getSszt())) {
            queryWrapper.eq("sszt", dto.getSszt());
        }
        Page<SxpzxxPO> page1 = new Page<>(page, rows);

        Page<SxpzxxPO> pageResult = (Page) this.sxpzxxMapper.selectPage(page1, queryWrapper);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public Map<String, String> updateSxztByIds(SxpzxxQueryDTO dto) {
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");

        StringBuilder errMsg = new StringBuilder();//失败msg
        StringBuilder succMsg = new StringBuilder();//成功msg
        int count = 0;
        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SxpzxxPO sxpzxxPO = new SxpzxxPO();
        sxpzxxPO.setTsCzsj(df.format(t));

        String ids = dto.getIds();
        String[] a = ids.split(",");
        List<String> al = Arrays.asList(a);
        QueryWrapper<SxpzxxPO> sxpzxxPOQueryWrapper = new QueryWrapper<>();
        sxpzxxPOQueryWrapper.in("rs_sx_config_lsh", al);

        return resultMap;
    }

    @Override
    public SxpzxxXsDTO getSxpzxxById(SxpzxxXsQueryDTO dto) {
        SxpzxxXsDTO sxpzxxXsDTO = this.sxpzxxMapper.getSxpzxxById(dto.getRsSxConfigLsh());
        QueryWrapper<FwdxPO> queryWrapper = new QueryWrapper<FwdxPO>();
        if (StringUtils.isNotBlank(dto.getSxbm())) {
            queryWrapper.eq("sxbm", dto.getSxbm());
        } else {
            queryWrapper.eq("rs_sx_config_lsh", dto.getRsSxConfigLsh());
        }

        return sxpzxxXsDTO;
    }

    @Override
    public PageResult getSxglclList(SxglclQueryDTO dto, int page, int rows) {
        Page<SxglclListDTO> page1 = new Page<>(page, rows);
        Page<SxglclListDTO> pageResult = null;
        if (StringUtils.isNotBlank(dto.getSxbm())) {
            pageResult = (Page) this.sxpzxxMapper.getSxglclListBySxbm(page1, dto);
        } else {
            pageResult = (Page) this.sxpzxxMapper.getSxglclListById(page1, dto);
        }

        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public PageResult getSxWglclList(SxWglclQueryDTO dto, int page, int rows) {
        Page<SdzlsxListDTO> page1 = new Page<>(page, rows);
        Page<SdzlsxListDTO> pageResult = null;
        if (StringUtils.isNotBlank(dto.getSxbm())) {
            if (StringUtils.isBlank(dto.getSsbmmc())) {
                dto.setSsbmmc(dto.getSxbm().substring(0,6));
            }
            pageResult = (Page) this.sxpzxxMapper.getSxWglclListBySxbm(page1, dto);
        } else {
            pageResult = (Page) this.sxpzxxMapper.getSxWglclListById(page1, dto);
        }

        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public Map<String, String> addSxglclByIds(SxglclAddDTO dto) {
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");
        String ids = dto.getIds();
//        String[] arr = ids.split(",");
//        List<String> idList = Arrays.asList(arr);
        //获取多选的材料类别及是否支持电子证照
        QueryWrapper<SdzlsxPO> sdzlsxPOQueryWrapper = new QueryWrapper<>();
        List<SdzlsxPO> sdzlsxPOList = sxclwhMapper.selectList(sdzlsxPOQueryWrapper);

        int glCount = 0;
        for (SdzlsxPO item :
                sdzlsxPOList) {
            //判断是否已关联
            QueryWrapper<SdszzcxxPO> glQueryWrapper = new QueryWrapper<>();
            glQueryWrapper.eq("zllbid", item.getZllbid());
            if (glCount > 0) {
                break;
            }
        }
        if (glCount > 0) {
            resultMap.put("code", "1");
            resultMap.put("msg", "存在材料已经关联。");
            return resultMap;
        }
        int count = 0;
        for (SdzlsxPO item :
                sdzlsxPOList) {
            SdszzcxxPO sdszzcxxPO = null;
            //取最大排序值
            QueryWrapper<SdszzcxxPO> sdszzcxxPOQueryWrapper = new QueryWrapper<>();
            sdszzcxxPOQueryWrapper.select("Max(orderno) orderno");

            sdszzcxxPO.setRsSxConfigLsh(dto.getRsSxConfigLsh());
            sdszzcxxPO.setZllbid(item.getZllbid());//资料类别id
            if (StringUtils.isNotBlank(dto.getSxbm())) {
                String sxbm = dto.getSxbm();
                long sxbmL = Long.parseLong(sxbm);
                sdszzcxxPO.setYwlbid(sxbmL);//事项编码
            }
            if (StringUtils.isNotBlank(item.getSfzcdzzz())) {
                sdszzcxxPO.setDzzzbz(item.getSfzcdzzz());//电子证照
            }
            sdszzcxxMapper.insert(sdszzcxxPO);
            count++;
        }
        resultMap.put("msg", "成功关联" + count + "条材料");
        return resultMap;
    }

    @Override
    public void deleteSxglclByIds(SxglclDeleteDTO dto) {
        String ids = dto.getIds();
        String[] idArr = ids.split(",");
        List<String> list = Arrays.asList(idArr);
        sdszzcxxMapper.deleteBatchIds(list);
    }

    @Override
    public void updateSxglcl(SdszzcxxDTO dto) {
        UpdateWrapper<SdszzcxxPO> updateWrapper = new UpdateWrapper<SdszzcxxPO>();
        updateWrapper.set("yjfs", dto.getYjfs()).set("fyjfs", dto.getFyjfs())
                .set("sysx", dto.getSysx());
        if (StringUtils.isNotBlank(dto.getClsm())) {
            updateWrapper.set("clsm", dto.getClsm().trim());
        } else {
            updateWrapper.set("clsm", " ");
        }
        updateWrapper.eq("sdszid", dto.getSdszid());
        sdszzcxxMapper.update(null, updateWrapper);
    }

    @Override
    public PageResult getLchjList(SxgllcQueryDTO dto, int page, int rows) {
        Page<LchjListDTO> page1 = new Page<>(page, rows);

        Page<LchjListDTO> pageResult = (Page) this.sxpzxxMapper.getLchjList(page1, dto.getSxbm());
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }

    @Override
    public void updateSxpzxxById(SxpzxxXsUpdateDTO dto) {
        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //获取用户ID
        cUser.getUserid();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SxpzxxPO sxpzxxPO = new SxpzxxPO();
        BeanUtils.copyProperties(dto, sxpzxxPO);
        sxpzxxPO.setTsCzsj(df.format(t));
        //更新服务对象
        updateFwdx(dto);

        this.sxpzxxMapper.updateById(sxpzxxPO);
    }

    @Override
    public SxglclListDTO getSxglcXx(SxglclXxQueryDTO dto) {
        SxglclListDTO sxglclListDTO = null;
        if (StringUtils.isNotBlank(dto.getSxbm())) {
            sxglclListDTO = this.sxpzxxMapper.getSxglcXxBySxbm(dto);
        } else {
            sxglclListDTO = this.sxpzxxMapper.getSxglcXxBySxId(dto);
        }
        return sxglclListDTO;
    }

    @Override
    public Map<String, String> checkNext(CheckDTO dto) {
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");
        StringBuilder errMsg = new StringBuilder();
        QueryWrapper<SxpzxxPO> queryWrapper = new QueryWrapper<>();
        if (errMsg.length() > 0) {
            //校验未通过
            resultMap.put("code", "1");
            resultMap.put("msg", errMsg.toString());
        }
        return resultMap;
    }
    //事项发布
    private void doUpdateFb(String id){
        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SxpzxxPO sxpzxxPO = new SxpzxxPO();
        sxpzxxPO.setTsCzsj(df.format(t));

        sxpzxxPO.setRsSxConfigLsh(id);
        sxpzxxPO.setFbzt("1");
        this.sxpzxxMapper.updateById(sxpzxxPO);

    }

    //更新服务对象
    public void updateFwdx(SxpzxxXsUpdateDTO dto) {
        QueryWrapper<FwdxPO> deleteWrapper = new QueryWrapper<>();
        FwdxPO fwdxPO = new FwdxPO();
        fwdxPO.setRsSxConfigLsh(dto.getRsSxConfigLsh());

        this.fwdxMapper.delete(deleteWrapper);
        fwdxPO.setFwdx("1");
        fwdxPO.setJbxxGtId(dto.getGr());
        fwdxPO.setJbxxQueryId(dto.getGr() + "_ds");
        this.fwdxMapper.insert(fwdxPO);
    }

    //发布前校验
    private void checkFb(SxpzxxPO sxpzxxPO, StringBuilder errMsg) {
        //1、校验必录字段
        QueryWrapper<FwdxPO> queryWrapper = new QueryWrapper<FwdxPO>();
        if (StringUtils.isNotBlank(sxpzxxPO.getSxbm())) {
            queryWrapper.eq("sxbm", sxpzxxPO.getSxbm());
        } else {
            queryWrapper.eq("rs_sx_config_lsh", sxpzxxPO.getRsSxConfigLsh());
        }

        if (!"6".equals(sxpzxxPO.getSlqd())) {
            //2、校验关联材料
            QueryWrapper<SdszzcxxPO> queryWrapper1 = new QueryWrapper<>();
            if (StringUtils.isNotBlank(sxpzxxPO.getSxbm())) {
                queryWrapper1.eq("ywlbid", sxpzxxPO.getSxbm());
            } else {
                queryWrapper1.eq("rs_sx_config_lsh", sxpzxxPO.getRsSxConfigLsh());
            }

            SxpzxxLcpzConfirmDTO pDto = new SxpzxxLcpzConfirmDTO();
            pDto.setRsSxConfigLsh(sxpzxxPO.getRsSxConfigLsh());
        }
    }
    @Override
    public String getMaxSxbm(String sxbm){
        return this.sxpzxxMapper.getMaxSxbm(sxbm);
    }
    @Override
    public void updateSxbmById(SxpzxxLcpzQueryDTO dto){
        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SxpzxxPO sxpzxxPO = new SxpzxxPO();
        sxpzxxPO.setProcessDefName(dto.getProcessdefname());
        this.sxpzxxMapper.updateById(sxpzxxPO);
    }
    //判断流程是否走完
    @Override
    public boolean checkProcessInstance(String id){
        int i = this.sxpzxxMapper.checkProcessInstance(id);
        if(i>0){
            return true;
        }
        return false;
    }
    //流程临时表是否存在
    @Override
    public int checkLcTemp(String id){
        return this.sxpzxxMapper.checkLcTemp(id);
    }
    //流程正式表是否存在
    @Override
    public int checkZslc(String id){
        return this.sxpzxxMapper.checkZslc(id);
    }
    @Override
    public PageResult getSxlcpzList(String id, int page, int rows){

        Page<LchjListDTO> page1 = new Page<>(page, rows);
        Page<LchjListDTO> pageResult = null;
        pageResult = (Page) this.sxpzxxMapper.getSxlcpzList(page1, id);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }


    public List<SxpzxxLchjDTO> getWfActionDefBySxid(String id){
        return this.sxpzxxMapper.getWfActionDefBySxid(id);
    }
    @Override
    public SxpzxxLcpzDTO getSxpzxxLcpzById(SxpzxxLcpzQueryDTO dto){
        return this.sxpzxxMapper.getSxpzxxLcpzById(dto.getRsSxConfigLsh());
    }
    @Override
    public void initLcTemp(SxpzxxLcpzDTO dto){
        //先清空流程临时表
        QueryWrapper<SxlchjPO> deleteWrapper = new QueryWrapper<SxlchjPO>();
        deleteWrapper.eq("process_def_name", dto.getProcessdefname());
        this.sxlcxxMapper.delete(deleteWrapper);

        SxpzxxLchjDTO hjdto = new SxpzxxLchjDTO();
        hjdto.setProcessdefid(dto.getSxbm());
        hjdto.setNextactiondefid(dto.getSxbm()+"_td");
        hjdto.setSortno("1");
        hjdto.setSfht("1");
        this.saveLchj2Temp(hjdto);

    }

    //转换流程到临时表
    @Override
    public void changeLc2Temp(SxpzxxLcpzQueryDTO dto){
        //先清空流程临时表
        QueryWrapper<SxlchjPO> deleteWrapper = new QueryWrapper<SxlchjPO>();
        deleteWrapper.eq("process_def_name", dto.getProcessdefname());
        this.sxlcxxMapper.delete(deleteWrapper);
        //查找正式流程
        List<SxpzxxLchjDTO> zslcList = this.sxpzxxMapper.getWfActionDefBySxid(dto.getRsSxConfigLsh());
    }
    //保存流程环节到临时表
    private void saveLchj2Temp(SxpzxxLchjDTO hjdto){
        SxlchjPO hjpo = new SxlchjPO();
        hjpo.setSortno(hjdto.getSortno());//排序号
        hjpo.setSfht(hjdto.getSfht());
        hjpo.setSffsdx(hjdto.getSffsdx());

        this.sxlcxxMapper.insert(hjpo);
    }
    //是否发短信
    private boolean isLcTaskSendSms(SxpzxxLchjDTO hjdto){
        if(StringUtils.isBlank(hjdto.getNextactiondefid()) || StringUtils.isBlank(hjdto.getActiondefid())){
            return false;
        }
        int isSendSms = this.sxpzxxMapper.checkHjTaskSendSms(hjdto);
        if( isSendSms > 0){
            return true;
        }
        return false;
    }
    //流程临时表是否存在科员受理环节
    @Override
    public int checkLcExistKyls(String processdefid){
        return this.sxpzxxMapper.checkLcExistKyls(processdefid);
    }

    //获取环节信息根据流程ID
    @Override
    public SxpzxxLchjDTO getLchjxxByLcid(String processdefid){
        return this.sxpzxxMapper.getLchjxxByLcid(processdefid);
    }

    //新增科员受理环节
    @Override
    public void addHjKysl(String processdefid){

        SxpzxxLchjDTO hjdto = this.getLchjxxByLcid(processdefid);

        //新增科员受理环节
        hjdto.setActiondefid(processdefid+"_kysl");
        hjdto.setActiondefname("科员受理");
        hjdto.setSortno("2");
        this.saveLchj2Temp(hjdto);
        //窗口收件环节的下一环节改为科员受理
        UpdateWrapper<SxlchjPO> updateWrapper = new UpdateWrapper<SxlchjPO>();
        updateWrapper.eq("ACTION_DEF_ID", processdefid+"_cksl")
                .eq("sfht","0");
        this.sxlcxxMapper.update(null, updateWrapper);
        //增加科员受理回退到窗口
        hjdto.setNextactiondefid(processdefid+"_cksl");
        hjdto.setSfht("1");
        this.saveLchj2Temp(hjdto);

    }

    //保存环节
    @Override
    public Map<String, String> saveHj(SxpzxxLcpzSaveHjDTO dto){
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");

        SxpzxxLchjDTO hjdto = new SxpzxxLchjDTO();
        hjdto.setActiondefname(dto.getActiondefname());
        hjdto.setSortno(dto.getSortno());

        if(this.sxpzxxMapper.checkSortno(hjdto) > 0){
            resultMap.put("code", "1");
            resultMap.put("msg", "环节序号已存在");
            return resultMap;
        }

        this.saveLchj2Temp(hjdto);

        return resultMap;

    }

    //删除环节
    @Override
    public void delHj(SxpzxxLcpzDelHjDTO dto){

        //删除的是科员受理环节，重新初始化流程
        if(dto.getActiondefid().indexOf("_kysl") != -1){
            //删除不是退单、办结、窗口受理的环节
            QueryWrapper<SxlchjPO> deleteWrapper = new QueryWrapper<SxlchjPO>();
            deleteWrapper.eq("PROCESS_DEF_ID",dto.getProcessdefid())
                    .notIn("ACTION_DEF_ID",dto.getProcessdefid()+"_cksl");
            this.sxlcxxMapper.delete(deleteWrapper);
            //更新窗口受理的下一环节为办结
            UpdateWrapper<SxlchjPO> updateWrapper = new UpdateWrapper<SxlchjPO>();
            updateWrapper.eq("PROCESS_DEF_ID",dto.getProcessdefid())
                    .eq("SFHT","0");
            this.sxlcxxMapper.update(null, updateWrapper);
            return;
        }
        //删除回退给自己的环节
        QueryWrapper<SxlchjPO> deleteWrapper = new QueryWrapper<SxlchjPO>();
        deleteWrapper.eq("NEXT_ACTION_DEF_ID", dto.getActiondefid())
                .eq("SFHT","1");
        this.sxlcxxMapper.delete(deleteWrapper);

       this.delHjOnly(dto);

    }
    //只处理删除环节，删当前环节，调整下一环节为当前环节的环节
    private void delHjOnly(SxpzxxLcpzDelHjDTO dto){
        //环节ID的记录物理删除
        QueryWrapper<SxlchjPO> deleteWrapper = new QueryWrapper<SxlchjPO>();
        deleteWrapper.eq("ACTION_DEF_ID", dto.getActiondefid())
                .eq("PROCESS_DEF_ID",dto.getProcessdefid());
        this.sxlcxxMapper.delete(deleteWrapper);

        //下一环节ID的记录，修改下一环节为空，非回退环节
        UpdateWrapper<SxlchjPO> updateWrapper = new UpdateWrapper<SxlchjPO>();
        updateWrapper.eq("NEXT_ACTION_DEF_ID", dto.getActiondefid())
                .eq("SFHT","0");
        this.sxlcxxMapper.update(null, updateWrapper);
        //删除多余的环节（非回退环节），多个相同环节，其中有下一环节为空的
        List<SxpzxxLchjDTO> hjlist = this.sxpzxxMapper.getBlankHjMoreThanOne(dto.getProcessdefid());
        if(hjlist != null && hjlist.size() != 0){
            for(int i =0;i<hjlist.size();i++){
                SxpzxxLchjDTO hjdto = hjlist.get(i);
                QueryWrapper<SxlchjPO> delWrapper = new QueryWrapper<SxlchjPO>();
                delWrapper.eq("ACTION_DEF_ID", hjdto.getActiondefid())
                        .isNull("NEXT_ACTION_DEF_ID");
                this.sxlcxxMapper.delete(delWrapper);
            }

        }

        //删除多余的环节（回退环节），删除下一环节为空的
        QueryWrapper<SxlchjPO> delWrapper2 = new QueryWrapper<SxlchjPO>();
        delWrapper2.eq("PROCESS_DEF_ID",dto.getProcessdefid())
                .isNull("NEXT_ACTION_DEF_ID");
        this.sxlcxxMapper.delete(delWrapper2);

    }
    //环节设置列表
    @Override
    public List<SxpzxxLcpzSetListDTO> getLcpzSetList(SxpzxxLcpzSetDTO dto){

        String nowhj = dto.getActiondefid();//当前环节

        List<SxpzxxLcpzSetListDTO> lcList = this.sxpzxxMapper.getLcpzSetList(dto.getProcessdefid());

        return lcList;

    }

    //保存环节设置列表
    @Override
    public Map<String, String> saveSetHj(SxpzxxLcpzSetListSaveDTO dto){
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");

        String processdefid=dto.getProcessdefid();//流程ID
        String actiondefid = dto.getActiondefid();//当前环节ID
        String sortno=  dto.getSortno();//排序号

        SxpzxxLchjDTO hjdto = new SxpzxxLchjDTO();
        hjdto.setSortno(sortno);

        List<SxpzxxLcpzSetListDTO> setListDTOList=dto.getData();

        if(setListDTOList != null && setListDTOList.size() != 0){
            //删除当前环节
            SxpzxxLcpzDelHjDTO delHjDTO=new SxpzxxLcpzDelHjDTO();
            delHjDTO.setActiondefid(actiondefid);
            delHjDTO.setProcessdefid(processdefid);
            this.delHjOnly(delHjDTO);

            //新增一个空的当前环节
            this.saveLchj2Temp(hjdto);

        }

        return resultMap;

    }
    //确认流程
    @Override
    public Map<String, String> confirmLcpz(SxpzxxLcpzConfirmDTO dto){
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");
        StringBuilder errMsg = new StringBuilder();
        //流程配置信息是否存在
        int countLctemp = this.sxpzxxMapper.checkLcTemp(dto.getRsSxConfigLsh());
        int countLc = this.sxpzxxMapper.checkZslc(dto.getRsSxConfigLsh());
        if(countLctemp == 0 && countLc == 0){
            errMsg.append("流程环节未配置，请先配置。");
            return resultMap;
        }

        //是否存在相同排序号的环节

        Integer count = this.sxpzxxMapper.checkSortnoMoreThanOne(dto.getRsSxConfigLsh());
        if(count != null){
            errMsg.append("存在重复环节序号。");
        }

        //非回退环节，下一环节的排序号大于当前环节的

        //回退环节，下一环节排序号小于当前环节的

        //所有非回退环节都有下一环节，除了办结、退单
        List<SxpzxxLchjDTO> hjdtoList = this.sxpzxxMapper.checkAllHjHaveNext(dto.getRsSxConfigLsh());
        if(hjdtoList != null && hjdtoList.size() != 0){
            String checkMsg = "";
            for(int i =0;i<hjdtoList.size();i++){
                SxpzxxLchjDTO hjdto=hjdtoList.get(i);
                checkMsg+=hjdto.getActiondefname()+",";
            }
        }
        if(errMsg.length() >0){
            resultMap.put("code", "1");
            resultMap.put("msg", errMsg.toString());
        }

        return resultMap;
    }

    //确认流程,转换流程到正式表
    private Map<String, String> confirmLcpzAndConvert(SxpzxxLcpzConfirmDTO dto){

        //-----------------------------确认流程--------------------------
        Map<String, String> resultMap = this.confirmLcpz(dto);
        if("1".equals(resultMap.get("code"))){
            return resultMap;
        }

        //-----------------------------流程是否有改动，是时判断是否有正在办理的业务-------------

        boolean isChange = false;
        if(this.checkProcessInstance(dto.getRsSxConfigLsh())){//存在未结束的业务
            List<String> zshjList = this.sxpzxxMapper.getWfactiondefHj(dto.getRsSxConfigLsh());
            List<String> temphjList = this.sxpzxxMapper.getWfactiondeftermHj(dto.getRsSxConfigLsh());
            if(zshjList != null && zshjList.size() != 0 && temphjList != null && temphjList.size() != 0){
                    if(zshjList.size() != temphjList.size()){//环节个数不一样
                        isChange = true;
                    }
            }
        }

        if(isChange){
            resultMap.put("code", "1");
            resultMap.put("msg", "该事项还有业务正在办理中，请先办结后再发布！");
            return resultMap;
        }

        LOG.info("------------流程确认结束，开始转换流程到正式表-------------");
        //------------------------------转换流程到正式表-----------------------------
        int countLctemp = this.sxpzxxMapper.checkLcTemp(dto.getRsSxConfigLsh());
        if(countLctemp == 0){//临时流程不存在，无须转换
            return resultMap;
        }
        SxpzxxLcpzDTO lcpzdto = this.sxpzxxMapper.getSxpzxxLcpzById(dto.getRsSxConfigLsh());
        String sxlb = lcpzdto.getSxlb();//事项类别
        //查子系统代码，权限ID
        String lb=sxlb;
        if(!sxlb.contains("440800")){
            lb=sxlb.substring(0,6)+"00";
        }
        LOG.info("子系统代码,类别"+lb);
        QueryWrapper<FwrightidsxlbPO> qWrapper = new QueryWrapper<FwrightidsxlbPO>();
        qWrapper.eq("SXLB",lb);
        FwrightidsxlbPO fwrightidsxlbPO = this.fwrightidsxlbMapper.selectOne(qWrapper);
        if(fwrightidsxlbPO == null){
            resultMap.put("msg", "子系统代码，权限ID配置信息不存在");
            return resultMap;
        }
        final String rightid = fwrightidsxlbPO.getRightid();//权限ID前两位
        final String rightname=fwrightidsxlbPO.getMc();//权限名称
        final String subsystype = fwrightidsxlbPO.getSubsystype();//子系统代码
        String shiJiCkRightid = "";//市级事项的窗口受理环节权限放在80开头，区县的与其他环节放一起

        boolean isShiJi = false;
        String sxmc = lcpzdto.getSxmc();//事项名称
        String sxbm = lcpzdto.getSxbm();//事项编码
        LOG.info("事项名称："+sxmc+",事项编码："+sxbm);

        boolean tempHaveKysl = false;//流程临时表是否存在科员受理环节
        int countHaveKysl = this.sxpzxxMapper.isWfactiondeftempHaveKysl(dto.getRsSxConfigLsh());
        if(countHaveKysl > 0){
            tempHaveKysl = true;
        }

        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String nowTime = df.format(t);

        //-------------------------初始化流程注册表------------------
        YwlbzcxxPO ywlbzcxxPO = new YwlbzcxxPO();
        QueryWrapper<YwlbzcxxPO> deleteWrapper = new QueryWrapper<YwlbzcxxPO>();
        deleteWrapper.eq("YWLBID", lcpzdto.getSxbm());
        this.ywlbzcxxMapper.delete(deleteWrapper);
        this.ywlbzcxxMapper.insert(ywlbzcxxPO);

        //-------------------------初始化流程表、流程事件表---------------------
        List<SxpzxxLchjDTO> wfactiondeftempList =  this.sxpzxxMapper.getWfactiondeftempList(dto.getRsSxConfigLsh());
        if(wfactiondeftempList != null && wfactiondeftempList.size() != 0){
            String processdefid = wfactiondeftempList.get(0).getProcessdefid();//流程ID
            String processdefname = wfactiondeftempList.get(0).getProcessdefname();//流程名称

            boolean existZslc = false;//正式流程权限是否存在
            int zsnum = this.sxpzxxMapper.checkZslcHaveKysl(processdefid+"_kysl");
            if(zsnum > 0){
                existZslc = true;
            }
            //根据流程ID，清空流程表
            QueryWrapper<WfactiondefPO> wfactiondefPOQueryWrapper = new QueryWrapper<WfactiondefPO>();
            wfactiondefPOQueryWrapper.eq("PROCESS_DEF_ID", processdefid);
            this.wfactiondefMapper.delete(wfactiondefPOQueryWrapper);
            //根据流程ID，清空流程事件表
            QueryWrapper<Wfactiondef2taskPO> dWrapper = new QueryWrapper<Wfactiondef2taskPO>();
            dWrapper.eq("PROCESS_DEF_ID", processdefid);
            this.wfactiondef2taskMapper.delete(dWrapper);

            //-----------处理权限表---------
            LOG.info("处理权限表");
            //确认二级菜单ID
            String sxRightid = "";



            //处理流程表办结、退单环节
            WfactiondefPO wfactiondefPO = new WfactiondefPO();
            wfactiondefPO.setSubsystype(subsystype);
            this.wfactiondefMapper.insert(wfactiondefPO);
            wfactiondefPO.setActionDefName("退单");
            wfactiondefPO.setSortno("90");
            this.wfactiondefMapper.insert(wfactiondefPO);

            //当前用户为管理员时，把流程的分配权限授权给当前用户
            //从上下文中获取当前登陆用户
            CurrentUser cUser = SecurityUtils.getCurrentUser();
            //获取用户ID
            String userid = cUser.getUserid();
            LOG.info("处理分配权限");

            String operid = this.sxpzxxMapper.getAdminOperid(userid);
            if(!StringUtils.isBlank(operid)){//非超级管理员的管理员
                //清除fw_operator2right，processdefid
                LOG.info("清除fw_operator2right,开始");
                LOG.info("清除fw_operator2right,operid="+operid);
                LOG.info("清除fw_operator2right,processdefid="+processdefid);
                HashMap<String,String> pMap = new HashMap<String,String>();
                pMap.put("operid",operid);
                pMap.put("processdefid",processdefid);
                this.sxpzxxMapper.delFwoperator2right(pMap);
                LOG.info("清除fw_operator2right,结束");
                //增加分配权限
                LOG.info("增加分配权限,开始");
                List<FwrightPO> fwrightPOList = this.sxpzxxMapper.getRightsByProcessdefid(processdefid);
                if(fwrightPOList != null && fwrightPOList.size() != 0){

                    Fwoperator2rightPO fwoperator2rightPO = new Fwoperator2rightPO();
                    fwoperator2rightPO.setOperid(operid);
                }
                LOG.info("增加分配权限,结束");


            }
        }




        return resultMap;
    }
    //环节名称动态字典
    public List<HjmcDictDTO> getHjmcDict(){
        List<HjmcDictDTO> hjmcist = sxpzxxMapper.getHjmcDict();
        return hjmcist;
    }
    //获取流程图信息
    @Override
    public Map<String, List> getLcpzLct(SxpzxxLcpzGetLctDTO dto){
        Map<String, List> resultMap = new HashMap<String, List>();

        List<SxpzxxLcpzLctListDTO> nodesList = this.sxpzxxMapper.getLctNodes(dto.getProcessdefid());
        List<SxpzxxLcpzLctListDTO> edgesList = this.sxpzxxMapper.getLctEdges(dto.getProcessdefid());

        if(nodesList != null && nodesList.size() != 0){
            resultMap.put("nodes",nodesList);
        }
        if(edgesList != null && edgesList.size() != 0){
            resultMap.put("edges",edgesList);
        }

        return resultMap;

    }
    //取事项配置流水号根据流程ID
    public String getRssxconfigIdByProcessdefid(String processdefid){
        return this.sxpzxxMapper.getRssxconfigIdByProcessdefid(processdefid);
    }

    //获取事项配置附件list
    public PageResult getSxpzxxFjybList(SxpzxxFjybQueryDTO dto, int page, int rows){
        Page<SxpzxxFjybListDTO> page1 = new Page<>(page, rows);
        Page<SxpzxxFjybListDTO> pageResult = null;
        pageResult = (Page) this.sxpzxxMapper.getSxpzxxFjybList(page1, dto);
        PageResult result = PageUtil.PageResult(pageResult);
        return result;
    }
    //保存事项配置附件样表
    @Override
    public Map<String, String> saveFjyb(SxpzxxFjybSaveDTO dto){
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("code", "0");
        resultMap.put("msg", "操作成功");

        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //获取用户ID
        cUser.getUserid();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SxpzxxfilePO po = new SxpzxxfilePO();
        BeanUtils.copyProperties(dto, po);
        po.setBae006(cUser.getRegioncode());

        this.sxpzxxfileMapper.insert(po);

        return resultMap;

    }
    @Override
    public void delFjybByIds(SxpzxxFjybDelDTO dto) {
        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //获取用户ID
        cUser.getUserid();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SxpzxxfilePO po = new SxpzxxfilePO();
        po.setBae004(cUser.getUserid());
        po.setBae005(df.format(t));

        String ids = dto.getIds();

    }
    //批量修改领导信息
    public void saveBatchLdxx(SxpzxxBatchUpdateLdxxDTO dto){
        //从上下文中获取当前登陆用户
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        //获取用户ID
        cUser.getUserid();
        //操作时间
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SxpzxxPO po = new SxpzxxPO();
        po.setTsCzsj(df.format(t));
        if(StringUtils.isNotBlank(dto.getKz())){
            po.setKz(dto.getKz());
        }
        if(StringUtils.isNotBlank(dto.getFgld())){
            po.setFgld(dto.getFgld());
        }

        String ids = dto.getIds();
        String[] idArr = ids.split(",");
        List<String> list = Arrays.asList(idArr);

        for(String id : list){
            po.setRsSxConfigLsh(id);
            sxpzxxMapper.updateById(po);
        }
    }
}
