package com.engine.htxc.contract.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.engine.common.util.ServiceUtil;
import com.engine.core.impl.Service;
import com.engine.htxc.common.R;
import com.engine.htxc.commonutil.db.DbTools;
import com.engine.htxc.commonutil.base.BaseUtil;
import com.engine.htxc.commonutil.db.EntityCrudUtil;
import com.engine.htxc.commonutil.fileutil.FileUtil;
import com.engine.htxc.commonutil.log.CustomizeLog;
import com.engine.htxc.contract.cmd.WorkflowNextJudgeCmd;
import com.engine.htxc.contract.dao.CghtDao;
import com.engine.htxc.contract.dao.ContractDao;
import com.engine.htxc.contract.dao.ContractModeDao;
import com.engine.htxc.contract.dto.*;
import com.engine.htxc.contract.entity.*;
import com.engine.htxc.contract.number.entity.Uf_ContractNoAggr;
import com.engine.htxc.contract.service.ContractService;
import static com.engine.htxc.workflow.create.business.contract.init.ContractSignType.Archived;

import com.engine.htxc.contract.util.ContractUtil;
import com.engine.htxc.eseal.service.EsealService;
import com.engine.htxc.eseal.service.impl.EsealServiceImpl;
import com.engine.htxc.workflow.create.autotrigger.contract.service.impl.AutoApprovalServiceImpl;
import com.engine.htxc.workflow.create.autotrigger.contract.vo.AutoApproval;
import com.engine.integration.util.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSetTrans;
import weaver.docs.docs.DocIdUpdate;
import weaver.docs.docs.DocImageManager;
import weaver.docs.docs.ImageFileIdUpdate;
import weaver.docs.docs.VersionIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.DBTools;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import weaver.interfaces.htsc.comInfo.PropBean;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author K1810015
 * @version 1.0.0
 * @ClassName ContractServiceImpl.java
 * @createTime 2022年07月01日 09:59:00
 */
public class ContractServiceImpl extends Service implements ContractService {

    private static final Logger logger= LoggerFactory.getLogger(ContractServiceImpl.class);

    public static final int DEFAULT_DOCLANGURAGE = 7;
    /**
     * 主目录默认值
     */
    public static final int DEFAULT_MAINCATEGORY = -1;
    /**
     * 子目录默认值
     */
    public static final int DEFAULT_SUBCATEGORY = -1;
    /**
     * 落款日期是否特殊要求默认值
     */
    public static final String LKRQSFYTSYQ_DEFAULT = "0";
    /**
     * 非压缩文件
     */
    public static final String IS_NOT_ZIP = "0";
    public static final int SFXJWFK_NO = 1;
    public static final String SFWDSF_DEFAULT = "0";
    public static final String BHSJE_DEFAULT = "0.00";

    private final DbTools dbtools=new DbTools();
    private PropBean pb=new PropBean();

    private EsealService esealService=ServiceUtil.getService(EsealServiceImpl.class);

    @Override
    public JSONArray getfileinfo(User user, Map<String, Object> map) {
        String contractmode= Util.null2String(map.get("contractmode"));
        if(StringUtils.isBlank(contractmode)){
            return null;
        }
        String sql="select wj as docid,mbmc as filename from uf_wdzx where mbbh in (?)";
        List<Map<String,Object>> retlist= DBTools.getsqltolist(sql,contractmode);
        if(retlist==null || retlist.size()<=0){
            return null;
        }
        JSONArray jsonArray= new FileUtil().getfilelinfo(user,retlist);
        return jsonArray;
    }

    @Override
    public JSONArray getdocimagefileinfo(User user, Map<String, Object> map) {
        JSONArray jsonarray=new JSONArray();
        String docids= Util.null2String(map.get("docids"));
        if(StringUtils.isBlank(docids)){
            return jsonarray;
        }
        jsonarray= new FileUtil().getdocimagefileinfo(user, Arrays.stream(docids.split(",")).collect(Collectors.toList()));
        return jsonarray;
    }


    @Override
    public boolean updateStatus(User user, Map<String, Object> map) {

        String formid = Util.null2String(map.get("formid"));
        String id = Util.null2String(map.get("id"));
        if (StringUtils.isBlank(id) || StringUtils.isBlank(formid)) {
            return false;
        }
        Map<String, String> setmap = new HashMap<>(1);
        setmap.put("yyjgdzt", Util.null2String(Archived.getValue()));
        String tablename = dbtools.getFormmodeidToTable(formid);
        if (StringUtils.isBlank(tablename)) {
            return false;
        }
        Map<String, String> wheremap = new HashMap<>(1);
        wheremap.put("id", id);
        return dbtools.updateSql(tablename, setmap, wheremap);
    }

    @Override
    public boolean updateContractenType(User user, Map<String, Object> map) {
        String gdlx = Util.null2String(map.get("gdlx"));
        String gdbz = Util.null2String(map.get("gdbz"));
        String formid = Util.null2String(map.get("formid"));
        String id = Util.null2String(map.get("id"));
        if (StringUtils.isBlank(id) || StringUtils.isBlank(formid) || StringUtils.isBlank(gdlx)) {
            return false;
        }
        Map<String, String> setmap = new HashMap<>(1);
        setmap.put("gdlx", gdlx);
        if (!StringUtils.isBlank(gdbz)) {
            setmap.put("gdbz", gdbz);
        }
        String tablename = dbtools.getFormmodeidToTable(formid);
        if (StringUtils.isBlank(tablename)) {
            return false;
        }
        Map<String, String> wheremap = new HashMap<>(1);
        wheremap.put("id", id);
        return dbtools.updateSql(tablename, setmap, wheremap);
    }

    @Override
    public String linkMode(User user, Map<String, Object> map) {
        String requestid=Util.null2String(map.get("requestid"));
        if(StringUtils.isBlank(requestid)){
            return JSON.toJSONString(R.error("参数有误"));
        }
        List<Map<String,Object>> detail=dbtools.getRequestidToMapList(requestid,null,4);
        if(detail==null && detail.size()<=0){
            return JSON.toJSONString(R.error("数据有误"));
        }
        Map<String,String> setmap=new HashMap<>(2);
        setmap.put("htsplcrequestid",requestid);
        setmap.put("zt","2");
        detail.forEach((item)->{
            Map<String,Object> detailmap=(HashMap<String,Object>)item;
            String htbh=Util.null2String(detailmap.get("htbh"));
            String htbb=Util.null2String(detailmap.get("htbb"));
            String htlx=Util.null2String(detailmap.get("htlx"));
            if(!StringUtils.isBlank(htbb) && !StringUtils.isBlank(htbh) && !StringUtils.isBlank(htlx)){
                  //做删除操作
                ContractModeDao contractModeDao=new ContractModeDao(htlx,htbh,htbb);
                if(!StringUtils.isBlank(contractModeDao.modeid)){
                    contractModeDao.updateMode(setmap);
                }
            }
        });

         return JSON.toJSONString(R.ok("已关联!"));
    }

    @Override
    public String unLinkMode(User user, Map<String, Object> map) {
        String requestid=Util.null2String(map.get("requestid"));
        if(StringUtils.isBlank(requestid)){
            return JSON.toJSONString(R.error("参数有误"));
        }
        List<Map<String,Object>> detail=dbtools.getRequestidToMapList(requestid,null,4);
        if(detail==null && detail.size()<=0){
            return JSON.toJSONString(R.error("数据有误"));
        }
        Map<String,String> setmap=new HashMap<>(2);
        setmap.put("htsplcrequestid","");
        setmap.put("zt","0");
        detail.forEach((item)->{
            Map<String,Object> detailmap=(HashMap<String,Object>)item;
            String htbh=Util.null2String(detailmap.get("htbh"));
            String htbb=Util.null2String(detailmap.get("htbb"));
            String htlx=Util.null2String(detailmap.get("htlx"));
            if(!StringUtils.isBlank(htbb) && !StringUtils.isBlank(htbh) && !StringUtils.isBlank(htlx)){
                //做删除操作
                ContractModeDao contractModeDao=new ContractModeDao(htlx,htbh,htbb);
                if(contractModeDao!=null){
                    contractModeDao.updateMode(setmap);
                }
            }
        });

        return JSON.toJSONString(R.ok("已删除!"));
    }



    @Override
    public String workflowNextJudge(User user, Map<String, Object> map) {
      String requestid=Util.null2String(map.get("requestid"));
      if(StringUtils.isBlank(requestid)){
         return JSON.toJSONString(R.error("参数有误"));
      }
        CustomizeLog.printLog("参看参数："+requestid+"userid："+user.toString());
        Map<String,Object> retmap=  new WorkflowNextJudgeCmd(map,user).execute(null);
      if(retmap==null || retmap.isEmpty()){
          return(JSON.toJSONString(R.error("参数有误"))) ;
      }
       if((boolean)retmap.get("flag")==true){
          return JSON.toJSONString( R.ok("true"));
       }
       return JSON.toJSONString(R.error(Util.null2String(retmap.get("msg"))));

    }

    @Override
    public String guidePages(User user, Map<String, Object> map) {
        String htbhs=Util.null2String(map.get("htbhs"));
        Map<String,Object> res=new HashMap<>(2);
        if(StringUtils.isBlank(htbhs)){
            return JSON.toJSONString(R.error("参数有误"));
        }
        String condition = Arrays.stream(htbhs.split(",")).distinct().map((item)->"\'"+item+"\'").collect(Collectors.joining(","));
        String validSql = " select wm_concat_old(distinct htlx) htlx  from uf_contractlist where htbh in ("+condition+")  ";
        String htlx= dbtools.getsqlonevalue(validSql,null);
        if(StringUtils.isBlank(htlx)){
            return JSON.toJSONString(R.error("查询结果集有误"));
        }
        Integer count=htlx.split(",").length;
        res.put("htlx",htlx);
        res.put("count",count);
        if(count!=1) {
            return JSON.toJSONString( R.ok(res));
        }
        //查询合同所有附件
        List<String> fjlist=new ArrayList<>();
        // by wf 添加印章字段、常用印章字段
        List<String> ztlist=new ArrayList<>();
        List<String> yzlist=new ArrayList<>();
        List<String> cyyzlist=new ArrayList<>();
        String configSql = " select a.jmbd maintable,b.jmbd dttable,fjzd from uf_htspckhtqcpzb a, uf_htspckhtqcpzb_dt1 b " +
                    " where a.id=b.mainid and htfl='"+htlx+"'";
        List configlist=dbtools.getSqlToList(configSql,null);
        if(configlist==null &&configlist.size()<=0){
            //查询结果
            return JSON.toJSONString(R.error("配置文件有误"));
        }
        configlist.forEach((item)->{
            Map<String,Object> configmap=(HashMap<String,Object>)item;
            String maintable = Util.null2String(configmap.get("maintable"));
            String dttable = Util.null2String(configmap.get("dttable"));
            String fjzd = Util.null2String(configmap.get("fjzd"));
            String fjSql = " select wm_concat_old("+fjzd+") as "+fjzd+" from "+maintable+" a,"+dttable+" b where a.id=b.mainid and htbh in("+condition+")";
            String filevalue= dbtools.getsqlonevalue(fjSql);
            if(!StringUtils.isBlank(filevalue)){
                fjlist.add(Arrays.stream(filevalue.split(",")).distinct().collect(Collectors.joining(",")));
            }
            String yzSql = " select yz,cyyz,zt  from "+maintable+"  where  htbh in("+condition+")";
            List<Map<String,Object>> signlist= dbtools.getSqlToList(yzSql);
            if (signlist!=null &&signlist.size()>0) {
                signlist.forEach((signmap)->{
                    yzlist.add(Util.null2String(signmap.get("yz")));
                    cyyzlist.add(Util.null2String(signmap.get("cyyz")));
                    ztlist.add(Util.null2String(signmap.get("zt")));

                });

            }
        });
        boolean flag= true;
        if(!ztlist.isEmpty()){
            flag= ztlist.stream().allMatch(item->(",0,6,").indexOf(","+item+",")>=0);
        }

        res.put("flag",flag);

        res.put("htfj",fjlist.stream().distinct().collect(Collectors.joining(",")));
            res.put("yz", Arrays.stream(yzlist.stream().collect(Collectors.joining(",")).split(",")).distinct().collect(Collectors.joining(",")) );
            res.put("cyyz",Arrays.stream(cyyzlist.stream().collect(Collectors.joining(",")).split(",")).distinct().collect(Collectors.joining(",")));
              return JSON.toJSONString( R.ok(res));
        }


        @Override
    public String todosealname(User user, Map<String, Object> map){
        String htlx=Util.null2String(map.get("htlx"));
        String htbh=Util.null2String(map.get("htbh"));

        String tablename= ContractUtil.getContractTableName(htlx);
        if(StringUtils.isBlank(tablename)){
            return JSON.toJSONString(R.error("参数有误"));
        }
        String signcount= ContractDao.getSealCount(tablename,htbh);
        if(StringUtils.isBlank(signcount)){
            return  JSON.toJSONString(R.error("查询数据有误"));
        }
        Map<String,Object> esealwhere=new HashMap<>(1);
        esealwhere.put("sealno",signcount);
        List<Map<String,Object>> list= esealService.getSealNoToName(esealwhere,user);
        Map<String,Object> retlist=new HashMap<>(1);
        retlist.put("data",list);
        return JSON.toJSONString(R.ok(retlist));
    }

    @Override
    public CghtMainEntity createCghtqc(CghtMainEntity cghtMainEntity) {
        //类型加前缀
        cghtMainEntity.setHtlx(addCategoryPrefix(pb, cghtMainEntity.getHtlx()));

        //生成合同编号
        Uf_ContractNoAggr contractNo = getContractNoObj(cghtMainEntity.getQcbm(),cghtMainEntity.getHtlx());
        final String htbh = genContractNo(contractNo);
        logger.info("合同编号：[{}]",htbh);
        cghtMainEntity.setHtbh(htbh);

        //插入采购合同起草主表 明细表
        CghtDao.insertCghtqcMain(contractNo,cghtMainEntity);
        return cghtMainEntity;
    }

    @Override
    public ProcessInfoDTO startContractProcess(final User user, ContractProcessDTO contractProcessDTO) {
        final List<ContractDetailDTO> contractList = contractProcessDTO.getContractList();
        if(null==contractList||contractList.isEmpty()){
            logger.error("合同详情为空");
            return null;
        }
        logger.info("创建合同数:[{}]",contractList.size());
        final Map<String, String> userInfoMap = ContractDao.getUserByWorkcodeAndDeptCode(contractProcessDTO.getUserCode(), contractProcessDTO.getUserDeptCode());

        RecordSetTrans rst=new RecordSetTrans();
        rst.setAutoCommit(false);
        try {
            //拟搞人信息
            //保存合同详情
            List<String> contractCodeList=saveContractDetailList(user, contractProcessDTO, userInfoMap, contractList, rst);
            //发起流程
            logger.info("合同数据草稿创建完成，发起流程");
            final int requestId = startProcess(contractProcessDTO, userInfoMap, contractCodeList);
            logger.info("合同创建处理结束，流程requestId：[{}]",requestId);
            if(requestId<0){
                throw new RuntimeException("发起流程失败");
            }
            final ProcessInfoDTO processInfoDTO = new ProcessInfoDTO();
            processInfoDTO.setRequestId(String.valueOf(requestId));
            processInfoDTO.setWorkflowNo(String.join(",", contractCodeList));

            rst.commit();
            logger.info("流程发起成功，合同数据已commit");
            return processInfoDTO;
        } catch (Exception e) {
            logger.error("发起流程出错，数据回滚",e);
            rst.rollback();
        }finally {
            rst.setAutoCommit(true);
        }
        return null;
    }

    private List<String> saveContractDetailList(User user, ContractProcessDTO contractProcessDTO, Map<String, String> userInfoMap,  List<ContractDetailDTO> contractList, RecordSetTrans rst) throws Exception {
        //收集合同编号
        List<String> contractCodeList=new ArrayList<>();
        for (ContractDetailDTO contractDetailDTO : contractList) {
            //主表数据
            //插入合同主表数据
            logger.info("创建合同主表数据：[{}]",contractDetailDTO.getContractName());
            final UfOtcdertra contractMain = setContractMainData(contractProcessDTO, userInfoMap, contractDetailDTO, pb);
            //生成合同编号
            Uf_ContractNoAggr contractNo = getContractNoObj(Integer.valueOf(userInfoMap.get("DEPARTMENTID")),contractMain.getHtlx());
            final String htbh = genContractNo(contractNo);
            logger.info("生成合同编号：[{}]",htbh);
            //收集合同编号
            contractCodeList.add(htbh);
            contractMain.setHtbh(htbh);

            //保存合同数据
            EntityCrudUtil.transInsert(rst,"uf_otcdertra",contractMain,UfOtcdertra.class);
            //查询合同id
            final int dataId = ContractDao.getDataIdByUuid(rst,contractMain.getModeuuid());
            contractMain.setId(dataId);

            //关联合同编号记录
            contractNo.setMbid(Util.null2String(dataId));
            //插入合同编号组合
            EntityCrudUtil.transInsert(rst,"uf_contractnoaggr",contractNo,Uf_ContractNoAggr.class);


            //插入正文文件信息 UF_OTCDERTRA_DT1
            logger.info("创建合同正文数:[{}]",contractDetailDTO.getMainFileList().size());
            final List<String> mainfileids = createAttachFiles(user, rst, contractDetailDTO, contractMain, "uf_otcdertra_dt1");
            //保存合同正文id 到主表
            contractMain.setHtzw(String.join(",",mainfileids));

            //插入附件文件信息 UF_OTCDERTRA_DT3 附件可以为空
            if(null!=contractDetailDTO.getAttachedFileList()){
                logger.info("创建合同附件数:[{}]",contractDetailDTO.getAttachedFileList().size());
                final List<String> attachFiles = createAttachFiles(user, rst, contractDetailDTO, contractMain, "uf_otcdertra_dt3");
                //保存合同附件id 到主表
                contractMain.setHtfj(String.join(",",attachFiles));
            }

            //更新主表正文和附件字段
            ContractDao.updateUfOtcdertraFiles(rst, contractMain);
            logger.info("权限重构：[{}]",dataId);
            //权限重构
            modeRight(contractMain);

        }
        return contractCodeList;
    }

    private void modeRight(UfOtcdertra contractMain) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(contractMain.getQcr(), contractMain.getFormmodeid(), contractMain.getId());
    }



    private List<String> createAttachFiles(User user, RecordSetTrans rst, ContractDetailDTO contractDetailDTO, UfOtcdertra contractMain, String tableName) throws Exception {
        List<String> fileIds=new ArrayList<>();
        for (ContractFileDTO contractFileDTO : contractDetailDTO.getMainFileList()) {
            logger.info("合同文件名称:[{}]",contractFileDTO.getFileName());

            //插入docdetail
            final Docdetail docdetail = insertDocDetail(rst, contractFileDTO);
            fileIds.add(String.valueOf(docdetail.getId()));

            //插入imagefile
            final ImagefileEntity imagefile = insertImagefile(rst, contractFileDTO);

            //插入docimagefile
            insertDocImagefile(user, rst, contractFileDTO, docdetail, imagefile);

            insertUfOtcdertraDt(rst, contractMain, tableName, contractFileDTO, docdetail);
        }
        return fileIds;
    }

    private void insertUfOtcdertraDt(RecordSetTrans rst, UfOtcdertra contractMain, String tableName, ContractFileDTO contractFileDTO, Docdetail docdetail) throws Exception {
        final UfOtcdertraDt attachFileEnty = new UfOtcdertraDt();
        attachFileEnty.setMainid(contractMain.getId());
        //wjmc	文件名称
        attachFileEnty.setWjmc(String.valueOf(docdetail.getId()));
        //yyfs	用印方式
        attachFileEnty.setYyfs(SealMethodEnum.valueOf(contractFileDTO.getSealMethod()).ordinal());
        //dzyyfs	电子用印方式
        attachFileEnty.setDzyyfs(EsealMethodEnum.valueOf(contractFileDTO.getEsealMethod()).ordinal());
        //dsmdy	单双面打印
        attachFileEnty.setDsmdy(PrintSideEnum.valueOf(contractFileDTO.getPrintBothSide()).ordinal());
        //fwdyfs/wlyyfs	"防伪打印份数/
        //物理用印份数"
        attachFileEnty.setFwdyfs(Util.null2String(contractFileDTO.getPrintCount()));
        attachFileEnty.setWlyyfs(Util.null2String(contractFileDTO.getPrintCount()));
        //用印状态默认0
        attachFileEnty.setYyzt(0);

        EntityCrudUtil.transInsert(rst, tableName,attachFileEnty,UfOtcdertraDt.class);
    }

    //文档索引不可回滚
    private Docdetail insertDocDetail(RecordSetTrans rst, ContractFileDTO contractFileDTO) throws Exception {
        //插入docdetail
        final Docdetail docdetail = new Docdetail();
        docdetail.setDocsubject(contractFileDTO.getFileName());
        docdetail.setDocextendname(contractFileDTO.getSuffix());
        docdetail.setDoclangurage(DEFAULT_DOCLANGURAGE);
        docdetail.setMaincategory(DEFAULT_MAINCATEGORY);
        final PropBean propBean = new PropBean();
        docdetail.setSeccategory(Integer.valueOf(propBean.getPropName("contract.jc.seccategory")));
        docdetail.setSubcategory(DEFAULT_SUBCATEGORY);
        int docId = new DocIdUpdate().getDocNewId();
        if (docId<0) {
            logger.error("获取 Docdetail id失败");
            throw new RuntimeException("获取 Docdetail id失败");
        }
        docdetail.setId(docId);
        logger.info("Docdetail id:[{}]",docdetail.getId());
        EntityCrudUtil.transInsert(rst,"docdetail",docdetail,Docdetail.class);
        return docdetail;
    }



    private void insertDocImagefile(User user, RecordSetTrans rst, ContractFileDTO contractFileDTO, Docdetail docdetail, ImagefileEntity imagefile) throws Exception {
        Docimagefile docimagefile=new Docimagefile();
        docimagefile.setDocid(docdetail.getId());
        docimagefile.setImagefileid(imagefile.getImagefileid());
        docimagefile.setImagefilename(contractFileDTO.getFileName());
        docimagefile.setIsextfile("1");
        final LocalDateTime now = LocalDateTime.now();
        docimagefile.setOperatedate(now.format(DateTimeFormatter.ISO_LOCAL_DATE));
        docimagefile.setOperatetime(now.format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        docimagefile.setOperateuserid(user.getUID());
        final DocImageManager docImageManager = new DocImageManager();
        int docimageId = docImageManager.getNextDocImageFileId();
        if(docimageId<0){
            throw new RuntimeException("获取 Docimagefile id 失败");
        }
        docimagefile.setId(docimageId);
        logger.info("Docimagefile id:[{}]",docimagefile.getId());

        int versionId = new VersionIdUpdate().getVersionNewId();
        docimagefile.setVersionid(versionId);
        logger.info("Docimagefile versionid:[{}]",docimagefile.getId());
        EntityCrudUtil.transInsert(rst,"DocImageFile",docimagefile,Docimagefile.class);
    }

    private ImagefileEntity insertImagefile(RecordSetTrans rst, ContractFileDTO contractFileDTO) throws Exception {
        final ImagefileEntity imagefile = new ImagefileEntity();
        int imagefileId=new ImageFileIdUpdate().getImageFileNewId();
        if(imagefileId<0){
            throw new RuntimeException("获取imagefileId失败");
        }
        logger.info("imagefile id:[{}]",imagefileId);
        imagefile.setImagefileid(imagefileId);
        imagefile.setImagefilename(contractFileDTO.getFileName());
        imagefile.setFileid(contractFileDTO.getFileId());
        imagefile.setImagefiletype("application/octet-stream");
        imagefile.setIszip(IS_NOT_ZIP);
        EntityCrudUtil.transInsert(rst,"imagefile",imagefile, ImagefileEntity.class);
        return imagefile;
    }


    /**
     * 业务类建模默认值：
     * @param contractProcessDTO
     * @param userInfo
     * @param contractDetailDTO
     * @param pb
     * @return
     */
    private UfOtcdertra setContractMainData(ContractProcessDTO contractProcessDTO, Map<String,String> userInfo, ContractDetailDTO contractDetailDTO, PropBean pb) {
        //建模主表
        final UfOtcdertra contractMain = EntityCrudUtil.createModeBaseAttributes("uf_otcdertra", UfOtcdertra.class);
        //设置默认值
        //币种（bz）默认=0 人民币
        contractMain.setBz(CurrencyEnum.CNY.ordinal());
        //不含税金额 （bhsje） 默认=0.00
        contractMain.setBhsje(BHSJE_DEFAULT);
        //向境外收付款（sfxjwfk）默认=1
        contractMain.setSfxjwfk(SFXJWFK_NO);
        //无明确对手方（sfwdsf） 默认=0
        contractMain.setSfwdsf(SFWDSF_DEFAULT);

        contractMain.setModedatacreater(Integer.valueOf(userInfo.get("USERID")));
        //htmc	合同名称
        contractMain.setHtmc(contractDetailDTO.getContractName());

        //htdsf	合同对手方
        final List<CounterPartyDTO> counterPartyList = contractDetailDTO.getCounterPartyList();
        final List<String> idCardList = counterPartyList.stream().map(CounterPartyDTO::getCertNo).collect(Collectors.toList());
        final List<String> codeList = ContractDao.selectCounterPartyByCertCode(idCardList);
        contractMain.setHtdsf(String.join(",", codeList));

        //bmdj	保密等级
        contractMain.setBmdj(SecretLevelEnum.NORMAL_BUSINESS_SECRET.ordinal());
        //htlx	合同类型
        if(StringUtils.isBlank(contractProcessDTO.getContractCategoryId())){
            contractMain.setHtlx(pb.getPropName("contract.jc.categoryId"));
        }else{
            contractMain.setHtlx(addCategoryPrefix(pb, contractProcessDTO.getContractCategoryId()));
        }
        //qcbm	起草部门
        contractMain.setQcbm(Integer.valueOf(userInfo.get("DEPARTMENTID")));
        //qcr	起草人
        contractMain.setQcr(Integer.valueOf(userInfo.get("USERID")));
        //qcrq	起草日期
        contractMain.setQcrq(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
        //htjexz	合同金额性质
        contractMain.setHtjexz(AmountTypeEnum.NO_AMOUNT.ordinal());
        //sfsw	是否涉外
        contractMain.setSfsw(ConcerningForeignEnum.NO_CONCERNING_FOREIGN.ordinal());
        //htxz	合同性质
        contractMain.setHtxz(ContractNatureEnum.MAIN_CONTRACT.ordinal());
        //beizhu	备注
        contractMain.setBeizhu(contractDetailDTO.getContractComment());
        //yz	印章
        //查询印章是否存在
        contractMain.setYz(String.join(",", contractDetailDTO.getSeals()));

        //sfsymbfb	是否使用模板范本
        final String textSource = contractDetailDTO.getTextSource();
        if(TextSourceEnum.LOCAL.name().equals(textSource)){
            contractMain.setSfsymbfb(UseTextEnum.NO_TEXT.ordinal());
        }else{
            contractMain.setSfsymbfb(UseTextEnum.USE_TEXT.ordinal());
        }
        //wsymbyy	未使用模板原因
        contractMain.setWsymbyy(contractDetailDTO.getUnusedTextReason());
        //dqbb	当前版本
        contractMain.setDqbb(Util.getIntValue(pb.getPropName("contract.currentVersion"),1));
        //zt	合同状态
        contractMain.setZt(ContractStatusEnum.DRAFT.ordinal());
        //autoSealFlag 字段用印
        contractMain.setAutosealflag(contractProcessDTO.getAutoSealFlag()?1:0);
        return contractMain;
    }

    private String genContractNo(Uf_ContractNoAggr contractNo) {
        return contractNo.getQz()+ contractNo.getZzjgjc()+ contractNo.getYear()+ contractNo.getMonth()+ contractNo.getDay()+String.format("%05d", contractNo.getZzbh());
    }

    /**
     * 获取合同编号
     * @param deptId
     * @param htlx
     * @return
     */
    private Uf_ContractNoAggr getContractNoObj(int deptId,String htlx) {
        final String deptAbbr = ContractDao.getDeptAbbrByDeptId(deptId);
        final DateTime now = DateTime.now();
        String year= DateUtil.format(now,"yyyy");
        String month=DateUtil.format(now,"MM");
        String day=DateUtil.format(now,"dd");
        final String prefix = pb.getPropName("contract.prefix");
        final int zzbh = ContractDao.getMaxNum(deptAbbr, year, prefix);

        Uf_ContractNoAggr contractNo=new Uf_ContractNoAggr();
        contractNo.setDay(day);
        contractNo.setMonth(month);
        contractNo.setYear(year);
        contractNo.setZzbh(zzbh);
        contractNo.setZzjgjc(deptAbbr);
        contractNo.setQz(prefix);
        contractNo.setHtlx(htlx);
        return contractNo;
    }




    /**
     *
     *
     * {
     *     "requestnam": "流程标题",
     *     "creatorid": "拟稿人",
     *     "szbm": "所在部门",
     *     "szjg": "所在机构",
     *     "jjcd": "缓急程度",
     *     "lxfs": "联系方式",
     *     "ngrq": "拟稿时间",
     *     "nbsh": "内部审核",
     *     "bmld": "部门领导",
     *     "sqjh": "授权简化",
     *     "qttzyddx": "通知阅读对象",
     *     "shfs": "审核方式:默认：0",
     *     "lkrqsfytsyq": "落款日期是否有特殊要求 = 否",
     *     "xzhtlb": "选择合同列表,DAS创建建模表成功后，存合同编码",
     *     "yz": "印章"
     * }
     * @param contractProcessDTO
     * @param contractCodeList
     * @return
     */
    private int startProcess(ContractProcessDTO contractProcessDTO, Map<String,String> userInfo, List<String> contractCodeList) {

        Set<String> sealSet=new HashSet<>();
        contractProcessDTO.getContractList().forEach(contractDetailDTO -> sealSet.addAll(contractDetailDTO.getSeals()));
        AutoApproval autoApproval=new AutoApproval();
        autoApproval.setCreatorid(userInfo.get("USERID"));
        autoApproval.setRequestname(contractProcessDTO.getProcessTitle());
        autoApproval.setSzbm(userInfo.get("DEPARTMENTID"));
        autoApproval.setSzjg(BaseUtil.getusertoszjg(userInfo.get("USERID")));
        //紧急程度默认0
        autoApproval.setJjcd(String.valueOf(UrgencyEum.NORMAL.ordinal()));
        autoApproval.setLxfs(contractProcessDTO.getTelephone());
        autoApproval.setNgrq(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
        //内部审核
        if(contractProcessDTO.getInternalAuditIds()!=null&&!contractProcessDTO.getInternalAuditIds().isEmpty()){
            autoApproval.setNbsh(ContractDao.getUsersByWorkcodeAndJobCodeList(contractProcessDTO.getInternalAuditIds()).stream().map(user->Util.null2String(user.getUserid())).collect(Collectors.joining(",")));
        }
        //部门领导
        if(null!=contractProcessDTO.getDeptHeadIds()&&!contractProcessDTO.getDeptHeadIds().isEmpty()){
            autoApproval.setBmld(ContractDao.getUsersByWorkcodeAndJobCodeList(contractProcessDTO.getDeptHeadIds()).stream().map(user->Util.null2String(user.getUserid())).collect(Collectors.joining(",")));
        }

        //授权简化
        autoApproval.setSqjh(Util.null2String(AuthoritySimplifyEnum.NO_SIMPLIFY.ordinal()));
        //通知阅读
        if(null!=contractProcessDTO.getNoticeReaderIds()&&!contractProcessDTO.getNoticeReaderIds().isEmpty()){
            autoApproval.setQttzyddx(ContractDao.getUsersByWorkcodeAndJobCodeList(contractProcessDTO.getNoticeReaderIds()).stream().map(user->Util.null2String(user.getUserid())).collect(Collectors.joining(",")));
        }
        //审核方式 默认1 并发
        autoApproval.setShfs(String.valueOf(ApprovalWayEnum.PARALLEL.ordinal()));
        //落款日期默认0
        autoApproval.setLkrqsfytsyq(LKRQSFYTSYQ_DEFAULT);
        autoApproval.setXzhtlb(String.join(",", contractCodeList));
        if(StringUtils.isBlank(contractProcessDTO.getContractCategoryId())){
            autoApproval.setHtlx(pb.getPropName("contract.jc.categoryId"));
        }else{
            autoApproval.setHtlx(addCategoryPrefix(pb, contractProcessDTO.getContractCategoryId()));
        }
        autoApproval.setYz(String.join(",", sealSet));
        return ServiceUtil.getService(AutoApprovalServiceImpl.class).create(autoApproval);
    }

    private String addCategoryPrefix(PropBean pb, String contractCategoryId) {
        return pb.getPropName("contract.jc.categoryPrefix") + "_" + contractCategoryId;
    }


    @Override
    public Map<String, Object> saveBankInfoToCounterparty(Map<String, Object> paramMap) {
        List<Map<String,Object>> data =(List<Map<String,Object>>)paramMap.get("data");
        Map<String ,Object> apiData = Maps.newHashMap();
        apiData.put("code","200");
        List<String> errorData = Lists.newArrayList();
        String sql = "select id from uf_dsfgl where dsfbm=? and scbs!=1 and fid is null";
        try {
            data.forEach(e -> {
                String htdsf = e.get("htdsf") == null?"":e.get("htdsf").toString();
                String yhzh = e.get("yxzh") == null?"":e.get("yxzh").toString();
                String khh = e.get("khx") == null?"":e.get("khx").toString();
                if (!"".equals(htdsf)){
                    List<Map<String, Object>> idList = dbtools.getSqlToList(sql,htdsf);
                    if (idList.size() > 0){
                        String mainid = idList.get(0).get("id").toString();
                        String ifexistSql = "select count(0) num from uf_dsfgl_dt2 where mainid ="+mainid+" and yxzh="+yhzh;
                        int num = dbtools.ifExist(ifexistSql);
                        //当银行账户不存在时不存在时才插入新数据
                        if (num == 0){
                            Map<String, String> map = Maps.newHashMap();
                            map.put("htdsf",htdsf);
                            map.put("yxzh",yhzh);
                            map.put("khx",khh);
                            map.put("mainid",mainid);
                            boolean result = dbtools.insert("uf_dsfgl_dt2",map);
                            if (!result){
                                errorData.add(yhzh);
                            }
                        }
                    }
                }
            });
        }catch (Exception e){
            apiData.put("code","400");
            apiData.put("message",e.getMessage());
        }
        if (errorData.size() > 0){
            apiData.put("code","400");
            apiData.put("message","添加失败");
            apiData.put("errorData",errorData);
        }

        return apiData;
    }
}
