package cn.gtmap.estateplat.config.service.core.impl;

import cn.gtmap.estateplat.config.core.service.*;
import cn.gtmap.estateplat.config.service.ArchivePostService;
import cn.gtmap.estateplat.config.service.ProjectCheckInfoService;
import cn.gtmap.estateplat.config.service.ProjectChecklimitFiledService;
import cn.gtmap.estateplat.config.service.core.ProjectGeneralService;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.config.utils.PlatformUtil;
import cn.gtmap.estateplat.config.utils.ReadXmlProps;
import cn.gtmap.estateplat.core.ex.AppException;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.core.support.mybatis.mapper.Example;
import cn.gtmap.estateplat.model.examine.BdcExamineParam;
import cn.gtmap.estateplat.model.server.core.*;
import cn.gtmap.estateplat.service.examine.BdcExamineService;
import cn.gtmap.estateplat.utils.CommonUtil;
import cn.gtmap.estateplat.utils.DateUtils;
import com.google.common.collect.Lists;
import com.gtis.common.util.UUIDGenerator;
import com.gtis.fileCenter.model.Space;
import com.gtis.fileCenter.service.NodeService;
import com.gtis.plat.service.SysSignService;
import com.gtis.plat.service.SysTaskService;
import com.gtis.plat.service.SysUserService;
import com.gtis.plat.service.SysWorkFlowInstanceService;
import com.gtis.plat.vo.PfSignVo;
import com.gtis.plat.vo.PfUserVo;
import com.gtis.plat.vo.PfWorkFlowInstanceVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
 * @version 1.0, 2016/4/20
 * @description 项目通用操作管理
 */
@Service
public class ProjectGeneralServiceImpl implements ProjectGeneralService {
    @Autowired
    protected SysUserService sysUserService;
    @Autowired
    private BdcZsbhService bdcZsbhService;
    @Autowired
    private NodeService FileCenterNodeServiceImpl;
    @Autowired
    EntityMapper entityMapper;
    @Autowired
    private BdcXmRelService bdcXmRelService;
    @Autowired
    private BdcdyService bdcdyService;
    @Autowired
    private BdcQlrService bdcQlrService;
    @Autowired
    private BdcXmService bdcXmService;
    @Autowired
    private QllxService qllxService;
    @Autowired
    private BdcSpxxService bdcSpxxService;
    @Autowired
    private BdcSjdService bdcSjdService;
    @Autowired
    private BdcXmZsRelService bdcXmZsRelService;
    @Autowired
    private BdcZsQlrRelService bdcZsQlrRelService;
    @Autowired
    private BdcZsService bdcZsService;
    @Autowired
    private ProjectCheckInfoService projectCheckInfoService;
    @Autowired
    private BdcDjbService bdcDjbService;
    @Autowired
    private ArchivePostService archivePostService;
    @Autowired
    private ProjectChecklimitFiledService projectChecklimitFiledService;
    @Autowired
    private BdcXtCheckInfoService bdcXtCheckInfoService;
    @Autowired
    private ExamineCheckInfoService examineCheckInfoService;
    @Autowired
    private BdcExamineService bdcExamineService;
    @Autowired
    private SysWorkFlowInstanceService sysWorkFlowInstanceService;
    @Autowired
    private SysSignService sysSignService;
    @Autowired
    private PlatformUtil platformUtil;


    /**
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 签名map
     */
    private Map<String, String> signKeyMap;

    /**
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 转发验证配置map
     */
    private Map<String, String> sqlxNoCheckMap;


    public Map<String, String> getSignKeyMap() {
        return signKeyMap;
    }

    public void setSignKeyMap(Map<String, String> signKeyMap) {
        this.signKeyMap = signKeyMap;
    }


    public Map<String, String> getSqlxNoCheckMap() {
        return sqlxNoCheckMap;
    }

    public void setSqlxNoCheckMap(Map<String, String> sqlxNoCheckMap) {
        this.sqlxNoCheckMap = sqlxNoCheckMap;
    }

    /**
     * @param xmxx 项目信息
     * @return 返回工作流实例
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @version 1.0, 2016/7/27
     * @description 根据项目信息创建工作流项目
     */
    @Override
    public PfWorkFlowInstanceVo createWorkflowInstance(Xmxx xmxx) {
        return null;
    }

    /**
     * @param wiid 工作流实例ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @version 1.0, 2016/7/27
     * @description 删除工作流实例
     */
    @Override
    public void deleteWorkflowInstance(String wiid) {

    }

    /**
     * @param xmxx
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 创建不动产登记项目，包括项目信息BDC_XM,收件信息BDC_SJXX,收件材料BDC_SJCL,审批信息BDC_SPXX,
     */
    @Transactional
    @Override
    public void createProject(Xmxx xmxx) {
        Project project = null;
        if (xmxx instanceof Project) {
            project = (Project) xmxx;
        }
        if (project != null && StringUtils.isNotBlank(project.getUserId())) {
            PfUserVo userVo = sysUserService.getUserVo(project.getUserId());
            String userName = "";
            if (userVo != null && StringUtils.isNotBlank(userVo.getUserName())) {
                userName = userVo.getUserName();
            }
            BdcXm bdcXm = bdcXmService.creatBdcXm(project.getProid(), userName, project.getWorkFlowDefId(), project.getWiid());  // 创建项目
            bdcSjdService.createSjxxByBdcxm(bdcXm);   // 初始化收件单
        }
    }

    /**
     * @param wiid   工作流实例ID
     * @param taskId 任务ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @version 1.0, 2016/7/27
     * @description 自动生成项目审批签名
     */
    @Override
    public void createProjectSignature(String wiid, String taskId) {

    }

    /**
     * @param proid 工作流实例ID
     * @return
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @version 1.0, 2016/7/27
     * @description 删除生成项目审批签名
     */
    @Override
    public void deleteProjectSignature(String proid) {
        StringBuilder signKey = new StringBuilder();
        for (Map.Entry<String, String> entry : signKeyMap.entrySet()) {
            signKey.append(entry.getValue() + ",");
        }

        if (StringUtils.isNotBlank(signKey.toString())) {
            deleleSign(proid, signKey.toString());
        }
    }

    /**
     * @param wiid       工作流项目ID
     * @param activityId 退回后活动ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 撤回或取回不动产登记项目，
     * 如果已生成证书，返回到缮证前，则删除证书、更新占用的证书编号信息（使用状态、使用人和使用时间等），上一手权利权属状态。
     * 如果已生成电子签名，返回到审核前，则删除签名
     * 如果已登簿，返回到登簿前，则删除登簿信息
     */
    @Override
    public void retreatProject(String wiid, String activityId) {

    }

    /**
     * @param wiid 工作流项目ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 流转不动产登记项目，证书编号使用情况和状态，不动产登记项目状态，创建项目证书、登簿情况（人和时间）、
     * 缮证人和时间、抵押注销登簿人和注销登簿时间
     */
    @Override
    public void transmitProject(String wiid, String taskid, String userid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                for (BdcXm bdcXm : bdcXmList) {
                    //修改证书编号使用状态为已打证
                    bdcZsbhService.changeZsbhSyqk(bdcXm);

                }
            }
        }


    }

    /**
     * @param wiid 工作流项目ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @version 1.0, 2016/7/27
     * @description 对不动产登记项目的证书进行缮证，生成证书编号，缮证人和时间等
     */
    @Override
    public void certificateProject(String wiid, String userid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                for (BdcXm bdcXm : bdcXmList) {
                    List<BdcZs> bdcZsList = bdcZsService.queryBdcZsByProid(bdcXm.getProid());
                    if (CollectionUtils.isNotEmpty(bdcZsList)) {
                        for (BdcZs bdcZs : bdcZsList) {
                            if (StringUtils.isNotBlank(userid)) {
                                PfUserVo pfUserVo = sysUserService.getUserVo(userid);
                                if (pfUserVo != null) {
                                    bdcZs.setSzr(pfUserVo.getUserName());
                                }
                            }
                            bdcZs.setCzr(bdcZs.getQlr());
                            bdcZs.setCzrq(new Date());
                            bdcZs.setSzrq(new Date());
                            entityMapper.saveOrUpdate(bdcZs, bdcZs.getZsid());
                        }
                    }
                }
            }
        }


    }

    /**
     * @param wiid 工作流项目ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 办完不动产登记项目，更新项目状态、项目权属状态、上一手权属状态（包括过渡数据权属状态）、权利附记信息、
     * 证书编号使用情况、自动归档
     */
    @Override
    public void completeProject(String wiid, String userid) {
        //更新项目状态
        updateProjectStatus(wiid);
        //归档注释，采用server
//        postBdcXmToArchive(wiid, userid);

        //更新证书表发证日期\发证人
        updateBdcZsFzrq(wiid, userid);
    }

    /**
     * @param wiid 工作流项目ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 删除项目信息，包括项目所涉及的BDC_XM,BDC_SJXX,BDC_SJCL,BDC_SPXX，BDC_QLR,BDC_ZS,BDC_BDCDY,BDC_DJB
     */
    @Transactional
    @Override
    public void deleteProject(String wiid) {
        List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
        if (CollectionUtils.isNotEmpty(bdcXmList)) {
            for (BdcXm bdcXm : bdcXmList) {
                String proid = bdcXm.getProid();

                //注销\抵押注销 流程删除权利表FJ、ZXDBR和ZXDBSJ数据
                if (StringUtils.equals(bdcXm.getDjlx(), Constants.DJLX_ZXDJ_DM) || CommonUtil.indexOfStrs(Constants.SQLX_DY_ZXDJ, bdcXm.getSqlx())) {
                    List<BdcXm> ybdcXmList = bdcXmService.getYbdcXmListByProid(proid);
                    for (BdcXm ybdcXm : ybdcXmList) {
                        QllxVo yqllxVo = qllxService.makeSureQllx(ybdcXm);
                        yqllxVo = qllxService.queryQllxVo(yqllxVo, ybdcXm.getProid());
                        qllxService.updateZxQllx(yqllxVo);
                    }
                }

                //证书编号
                delZsbh(proid);
                //删除不动产项目相关信息
                deleteBdcXmxx(bdcXm);
                //BDC_XM项目主表信息
                bdcXmService.delBdcXmByProid(proid);
                //项目附件信息
                delProjectNode(proid);
                deleteProjectSignature(proid);

            }
        }
    }

    /**
     * @param bdcXm 不动产项目
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 删除不动产项目相关信息，包括项目所涉及的BDC_XM_REL,BDC_SJXX,BDC_SJCL,BDC_SPXX，BDC_QLR,BDC_ZS,BDC_BDCDY,BDC_DJB
     */
    private void deleteBdcXmxx(BdcXm bdcXm) {
        String proid = bdcXm.getProid();
        //zdd 删除项目关系表
        bdcXmRelService.delBdcXmRelByProid(proid);
        //zdd 删除收件单信息表
        List<BdcSjxx> bdcSjxxList = bdcSjdService.queryBdcSjdByWiid(bdcXm.getWiid());
        if (bdcSjxxList != null && bdcSjxxList.size() > 0) {
            for (BdcSjxx bdcSjxx : bdcSjxxList) {
                bdcSjdService.delSjclListBySjxxid(bdcSjxx.getSjxxid());
                bdcSjdService.delBdcSjxxBySjxxid(bdcSjxx.getSjxxid());
            }
        }
        //zdd 删除审批信息
        bdcSpxxService.delBdcSpxxByProid(proid);
        //zdd 删除权利人证书关系信息表以及权利人信息
        List<BdcQlr> bdcQlrList = bdcQlrService.queryBdcQlrYwrByProid(proid);
        if (bdcQlrList != null && bdcQlrList.size() > 0) {
            for (BdcQlr bdcQlr : bdcQlrList) {
                bdcZsQlrRelService.delBdcZsQlrRelByQlrid(bdcQlr.getQlrid());
                bdcQlrService.delBdcQlrByQlrid(bdcQlr.getQlrid());
            }
        }
        //zdd 删除项目证书关系表 删除证书信息
        List<BdcXmzsRel> bdcXmzsRelList = bdcXmZsRelService.queryBdcXmZsRelByProid(proid);
        if (bdcXmzsRelList != null && bdcXmzsRelList.size() > 0) {
            for (BdcXmzsRel bdcXmzsRel : bdcXmzsRelList) {
                bdcXmZsRelService.delBdcXmZsRelByXmzsgxid(bdcXmzsRel.getXmzsgxid());
                bdcZsService.delBdcZsByZsid(bdcXmzsRel.getZsid());
            }
        }
        //zdd 删除不动产单元
        if (StringUtils.isNotBlank(bdcXm.getBdcdyid())) {
            List<BdcXm> bdcXmListTemp = null;
            HashMap map = new HashMap();
            map.put("bdcdyid", bdcXm.getBdcdyid());
            bdcXmListTemp = bdcXmService.andEqualQueryBdcXm(map);
            if (bdcXmListTemp != null && bdcXmListTemp.size() == 1) {
                bdcdyService.delBdcdyById(bdcXm.getBdcdyid());
            }
        }
    }

    /**
     * @param proid 项目id
     * @author <a href="mailto:juyulin@gtmap.cn">juyulin</a>
     * @description 删除项目证书编号
     */
    private void delZsbh(String proid) {
        List<BdcZs> zsList = bdcZsService.queryBdcZsByProid(proid);
        if (CollectionUtils.isNotEmpty(zsList)) {
            for (BdcZs bdcZs : zsList) {
                HashMap map = new HashMap();
                map.put("zsid", bdcZs.getZsid());
                List<BdcZsbh> bdcZsbhList = bdcZsbhService.getBdcZsBhListByBhfw(map);
                if (CollectionUtils.isNotEmpty(bdcZsbhList)) {
                    for (BdcZsbh bdcZsbh : bdcZsbhList) {
                        bdcZsbh.setLqr("");
                        bdcZsbh.setLqrid("");
                        bdcZsbh.setZsid("");
                        bdcZsbh.setSyqk("0");
                        entityMapper.saveOrUpdate(bdcZsbh, bdcZsbh.getZsbhid());
                    }
                }
            }
        }
    }

    /**
     * @param proid 项目id
     * @author <a href="mailto:juyulin@gtmap.cn">juyulin</a>
     * @description 删除项目附件信息
     */
    private void delProjectNode(String proid) {
        Space space = FileCenterNodeServiceImpl.getWorkSpace("WORK_FLOW_STUFF");
        com.gtis.fileCenter.model.Node tempNode = FileCenterNodeServiceImpl.getNode(space.getId(), proid, true);
        FileCenterNodeServiceImpl.remove(tempNode.getId());
    }

    /**
     * @param wiid 工作流项目ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 更新项目状态，主要是项目办理状态
     */
    @Transactional
    @Override
    public void updateProjectStatus(String wiid) {
        List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
        if (CollectionUtils.isNotEmpty(bdcXmList)) {
            for (BdcXm bdcXm : bdcXmList) {
                bdcXm.setBjsj(DateUtils.now());
                bdcXm.setXmzt("1");
                entityMapper.saveOrUpdate(bdcXm, bdcXm.getProid());
                qllxService.endQllxZt(bdcXm);
            }
        }
    }

    /**
     * @param wiid 工作流项目ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 生成项目的证书信息
     */
    @Override
    public void generateProjectZs(String wiid) {
        List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
        if (CollectionUtils.isNotEmpty(bdcXmList)) {
            for (BdcXm bdcXm : bdcXmList) {
                List<BdcQlr> bdcQlrList = bdcQlrService.queryBdcQlrByProid(bdcXm.getProid());
                //创建证书  同时保存权利人证书关系表
                List<BdcZs> list = bdcZsService.creatBdcqz(bdcXm, bdcQlrList);
                if (CollectionUtils.isNotEmpty(list)) {
                    //zdd 生成权利人证书关系表
                    bdcZsQlrRelService.creatBdcZsQlrRel(bdcXm, list, bdcQlrList);
                    //zdd 生成项目证书关系表
                    bdcXmZsRelService.creatBdcXmZsRel(list, bdcXm.getProid());
                } else {
                    throw new AppException(3006);
                }
            }
        }
    }

    /**
     * @param wiid   工作流项目ID
     * @param taskId 当前工作流活动任务ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 验证不动产登记项目，包括必填项，存储值的正确性和限制条件等
     */
    @Override
    public String validateProject(String wiid, String taskId, String activityid) throws AppException {
        String activityName = platformUtil.getPfActivityNameByActivitId(activityid);
        Project project = null;
        String str = "";
        List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
        List<BdcXtCheckinfo> bdcXtCheckinfoList = null;
        BdcXm bdcXm = null;
        if (CollectionUtils.isNotEmpty(bdcXmList)) {
            bdcXm = bdcXmList.get(0);
            project = bdcXmService.getProjectFromBdcXm(bdcXm, null);
            List<BdcXmRel> bdcXmRelList = bdcXmRelService.getBdcXmRelByProid(project.getProid());
            if (CollectionUtils.isNotEmpty(bdcXmRelList)) {
                BdcXmRel bdcXmRel = bdcXmRelList.get(0);
                if (StringUtils.isNotBlank(bdcXmRel.getQjid())) {
                    project.setDjId(bdcXmRel.getQjid());
                }
                if (StringUtils.isNotBlank(bdcXmRel.getYproid())) {
                    project.setYxmid(bdcXmRel.getYproid());
                }
                BdcBdcdy bdcdy = null;
                if (StringUtils.isNotBlank(bdcXm.getBdcdyid())) {
                    bdcdy = bdcdyService.queryBdcdyById(bdcXm.getBdcdyid());
                }
                if (bdcdy != null && StringUtils.isNotBlank(bdcdy.getBdcdyh())) {
                    project.setBdcdyh(bdcdy.getBdcdyh());
                }
            }

            if (project != null) {
                //必填项验证
                List<Map> list = projectChecklimitFiledService.validateMsg(taskId, project.getProid());
                if (list != null && list.size() > 0) {
                    for (Map map : list) {
                        if (map.containsKey("error") && map.get("error") != null && StringUtils.isNotBlank(map.get("error").toString())) {
                            if (StringUtils.isNotBlank(str)) {
                                str = str + "；" + map.get("error").toString();
                            } else {
                                str = map.get("error").toString();
                            }
                        }

                    }
                }
            }


            String sqlxNoCheck = "";
            //不需要验证的节点
            if (sqlxNoCheckMap.get(bdcXm.getSqlx()) != null) {
                sqlxNoCheck = sqlxNoCheckMap.get(bdcXm.getSqlx()).toString();
            } else {
                sqlxNoCheck = sqlxNoCheckMap.get("default").toString();
            }
            if (sqlxNoCheck.contains(activityName)) {
                return str;
            }

        }


        if (project != null) {
            //e包验证
            if (StringUtils.isBlank(str)) {
                List<String> unExamineSqlx = ReadXmlProps.getUnExamineSqlxDm();
                if (CollectionUtils.isEmpty(unExamineSqlx) || (CollectionUtils.isNotEmpty(unExamineSqlx) && !unExamineSqlx.contains(bdcXm.getSqlx()))) {
                    List<BdcExamineParam> bdcExamineParamList = examineCheckInfoService.getBdcExamineParam(bdcXm.getWiid(), null);
                    Map<String, Object> examineMap = bdcExamineService.performExamine(bdcExamineParamList, bdcXm.getWiid());
                    if (examineMap != null && examineMap.containsKey("info") && examineMap.get("info") != null) {
                        str = StringUtils.indexOf(examineMap.get("checkMsg").toString(), "<br/>") > -1 ? StringUtils.replace(examineMap.get("checkMsg").toString(), "<br/>", "\\n") : examineMap.get("checkMsg").toString();
                    }
                }
            }

            //强制验证
            if (StringUtils.isBlank(str)) {
                HashMap hashMap = new HashMap();
                hashMap.put("sqlxdm", project.getSqlx());
                hashMap.put("qllxdm", project.getQllx());
                hashMap.put("notEqualCheckType", Constants.XT_CHECKTYPE_BDCDY);
                bdcXtCheckinfoList = bdcXtCheckInfoService.getBdcXtCheckInfoList(hashMap);
                if (CollectionUtils.isEmpty(bdcXtCheckinfoList)) {
                    bdcXtCheckinfoList = new ArrayList<BdcXtCheckinfo>();
                }
                List<Map<String, Object>> checkMsg = projectCheckInfoService.checkXmNew(bdcXtCheckinfoList, project);
                if (checkMsg != null && checkMsg.size() > 0) {
                    for (Map<String, Object> map : checkMsg) {
                        if (map.containsKey("checkModel") && map.get("checkModel").toString().toUpperCase().equals("ALERT")) {
                            str = map.get("checkMsg").toString();
                            break;
                        }
                    }
                }
            }
        }
        return str;
    }

    /**
     * @param wiid 工作流项目ID
     * @return
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @version 1.0, 2016/7/27
     * @description 对不动产登记项目的证书发证，生成发证人和时间等
     */
    @Override
    public void takeProject(String wiid, String userid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                for (BdcXm bdcXm : bdcXmList) {
                    List<BdcZs> bdcZsList = bdcZsService.queryBdcZsByProid(bdcXm.getProid());
                    if (CollectionUtils.isNotEmpty(bdcZsList)) {
                        for (BdcZs bdcZs : bdcZsList) {
                            if (StringUtils.isNotBlank(userid)) {
                                PfUserVo pfUserVo = sysUserService.getUserVo(userid);
                                if (pfUserVo != null) {
                                    bdcZs.setFzr(pfUserVo.getUserName());
                                }
                            }
                            bdcZs.setFzrq(new Date());
                            entityMapper.saveOrUpdate(bdcZs, bdcZs.getZsid());
                        }
                    }
                }
            }
        }

    }

    @Override
    public void takeProjectXmzt(String wiid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                for (BdcXm bdcXm : bdcXmList) {
                    bdcXm.setXmzt(Constants.XMZT_SZ);
                    entityMapper.saveOrUpdate(bdcXm, bdcXm.getProid());
                }
            }
        }
    }


    @Override
    public Project initBdcDataToBdcXmRel(Project project) {
        if (project != null && StringUtils.isNotBlank(project.getProid())) {
            //zdd 一个流程多个项目处理 选择楼盘表
            BdcXm bdcXm = bdcXmService.getBdcXmByProid(project.getProid());
            if (null != bdcXm && StringUtils.isNotBlank(bdcXm.getSqlx()) && !StringUtils.equals(bdcXm.getSqlx(), Constants.SQLX_PLFZ_DM)) {
                //针对单个流程重复选的时候执行下面方法；
                if (StringUtils.isNotBlank(bdcXm.getWiid())) {
                    project = (Project) bdcXmService.getProjectFromBdcXm(bdcXm, project);
                }

            }
            project.setBdcdyid(null);
            List<BdcXmRel> bdcXmRelList = new ArrayList<BdcXmRel>();
            //jyl 数据格式统一转换成bdc_xm_rel格式
            if (project.getBdcXmRelList() == null || project.getBdcXmRelList().size() <= 0) {
                BdcXmRel bdcXmRel1 = bdcXmRelService.creatBdcXmRelFromProject(project);
                if (bdcXmRel1 != null) {
                    bdcXmRelList.add(bdcXmRel1);
                }
                if ((StringUtils.equals(project.getSqlx(), Constants.SQLX_PLHZ_DM) || StringUtils.equals(project.getSqlx(), Constants.SQLX_PLYSBZ_DM)) && StringUtils.isNotBlank(project.getYbdcqzh())) {
                    List<BdcXmzsRel> bdcXmzsRelList = bdcZsService.getBdcXmzsRelByBdcqzh(project.getYbdcqzh());
                    if (CollectionUtils.isNotEmpty(bdcXmzsRelList)) {
                        for (int i = 0; i < bdcXmzsRelList.size(); i++) {
                            BdcXmRel bdcXmRel = new BdcXmRel();
                            bdcXmRel.setRelid(UUIDGenerator.generate18());
                            bdcXmRel.setQjid(project.getDjId());
                            bdcXmRel.setProid(project.getProid());
                            bdcXmRel.setYqlid(project.getYqlid());
                            bdcXmRel.setYdjxmly(project.getXmly());
                            bdcXmRel.setYproid(bdcXmzsRelList.get(i).getProid());
                            bdcXmRelList.add(bdcXmRel);
                            if (CollectionUtils.isNotEmpty(bdcXmRelList)) {
                                project.setBdcXmRelList(bdcXmRelList);
                            }
                        }
                    }
                } else {
                    //合并流程不动产项目关系表必须有值
                    project.setBdcXmRelList(bdcXmRelList);
                }
            }
        }
        return project;
    }

    /**
     * @param wiid 工作流项目ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @version 1.0, 2016/7/27
     * @description 撤回项目状态
     */
    @Override
    public void retreatProjectXmzt(String wiid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                for (BdcXm bdcXm : bdcXmList) {
                    bdcXm.setXmzt(Constants.XMZT_LS);
                    entityMapper.saveOrUpdate(bdcXm, bdcXm.getProid());
                }
            }
        }
    }

    /**
     * @param wiid 退回后活动ID
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 撤回或取回登簿，
     * 如果已生成证书，返回到缮证前，则删除证书、更新占用的证书编号信息（使用状态、使用人和使用时间等）。
     * 如果已登簿，返回到登簿前，则删除登簿信息
     */
    @Override
    public void retreatCertificateProject(String wiid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                for (BdcXm bdcXm : bdcXmList) {
                    //还原证书编号使用情况
                    delZsbh(bdcXm.getProid());
                    //删除证书
                    bdcZsService.delBdcZsByProid(bdcXm.getProid());
                    //删除登簿信息
                    delProjectEventDbxx(bdcXm);

                }
            }
        }

    }

    /**
     * @param wiid   工作流id
     * @param userid 用户id
     * @author <a href="mailto:liaoxiang@gtmap.cn">liaoxiang</a>
     * @description 登簿人登簿时间更新
     */
    @Override
    public void turnProjectEventDbr(String wiid, String userid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                for (BdcXm bdcXm : bdcXmList) {
                    QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
                    qllxVo = qllxService.queryQllxVo(qllxVo, bdcXm.getProid());
                    if (qllxVo != null && StringUtils.isNotBlank(qllxVo.getQlid())) {
                        qllxVo = qllxService.updateDbr(qllxVo, userid);
                        entityMapper.updateByPrimaryKeySelective(qllxVo);
                    } else {
                        //zhouwanqing   这边针对注销和解封的登簿人和登记时间
                        List<BdcXm> ybdcXmList = bdcXmService.getYbdcXmListByProid(bdcXm.getProid());
                        if (CollectionUtils.isNotEmpty(ybdcXmList)) {
                            for (BdcXm ybdcXm : ybdcXmList) {
                                QllxVo yqllxVo = qllxService.makeSureQllx(ybdcXm);
                                yqllxVo = qllxService.queryQllxVo(yqllxVo, ybdcXm.getProid());
                                if (yqllxVo != null && StringUtils.isNotBlank(yqllxVo.getQlid())) {
                                    yqllxVo = qllxService.updateZxDbr(yqllxVo, userid);
                                    entityMapper.updateByPrimaryKeySelective(yqllxVo);
                                }
                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * @param wiid   工作流id
     * @param userid 用户id
     * @author <a href="mailto:liaoxiang@gtmap.cn">liaoxiang</a>
     * @description 自动归档
     */
    public void postBdcXmToArchive(String wiid, String userid) {
        if (StringUtils.isNotBlank(wiid)) {
            List<BdcXm> bdcXmList = bdcXmService.getBdcXmListByWiid(wiid);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                String userName = "";
                if (StringUtils.isNotBlank(userid)) {
                    PfUserVo pfUserVo = sysUserService.getUserVo(userid);
                    if (pfUserVo != null) {
                        userName = pfUserVo.getUserName();
                    }
                }
                archivePostService.postPlBdcXmInfo(bdcXmList, userName);
            }
        }
    }

    @Override
    public List<Map<String, Object>> validateBdcXm(Project project) {
        List<Map<String, Object>> resultList = Lists.newArrayList();
        BdcXm bdcXm = bdcXmService.getBdcXmByProid(project.getProid());
        //e包验证
        List<String> unExamineSqlx = ReadXmlProps.getUnExamineSqlxDm();
        if (CollectionUtils.isEmpty(unExamineSqlx) || (CollectionUtils.isNotEmpty(unExamineSqlx) && bdcXm != null && !unExamineSqlx.contains(bdcXm.getSqlx()))) {
            List<BdcExamineParam> bdcExamineParamList = new ArrayList<BdcExamineParam>();
            List<String> dcbIndexList = new ArrayList<String>();
            if (bdcXm != null) {
                if (StringUtils.isNotBlank(project.getDcbIndex())) {
                    dcbIndexList.add(project.getDcbIndex());
                } else {
                    bdcExamineParamList = examineCheckInfoService.getBdcExamineParam(bdcXm.getWiid(), project);
                }
            } else {
                bdcExamineParamList = examineCheckInfoService.getBdcExamineParam(StringUtils.EMPTY, project);
            }
            Map<String, Object> examineMap = null;
            if (CollectionUtils.isNotEmpty(dcbIndexList) && bdcXm != null) {
                examineMap = bdcExamineService.performExamineLjz(dcbIndexList, bdcXm.getWiid());
            } else if (bdcXm != null) {
                examineMap = bdcExamineService.performExamine(bdcExamineParamList, bdcXm.getWiid());
            }
            if (examineMap != null && examineMap.containsKey("info") && examineMap.get("info") != null) {
                HashMap<String, Object> returnMap = new HashMap<String, Object>();
                returnMap.put("info", examineMap.get("info"));
                returnMap.put("checkModel", "alert");
                returnMap.put("checkMsg", examineMap.get("checkMsg"));
                returnMap.put("checkPorids", examineMap.get("info"));
                returnMap.put("wiid", bdcXm.getWiid());
                if (examineMap.get("xzwh") != null) {
                    returnMap.put("xzwh", examineMap.get("xzwh").toString());
                }
                if (examineMap.get("examineInfo") != null) {
                    returnMap.put("examineInfo", examineMap.get("examineInfo"));
                }
                resultList.add(returnMap);
                return resultList;
            }
        }
        BdcXm ybdcXm = new BdcXm();
        if (StringUtils.isNotBlank(project.getYxmid())) {
            ybdcXm = bdcXmService.getBdcXmByProid(project.getYxmid());
        }
        if (bdcXm != null) {
            //zdd 如果都为空  则不验证
            if (StringUtils.isNoneBlank(bdcXm.getSqlx()) || StringUtils.isNoneBlank(bdcXm.getQllx())) {
                HashMap hashMap = new HashMap();
                hashMap.put("sqlxdm", bdcXm.getSqlx());
                if (StringUtils.isNotBlank(bdcXm.getQllx())) {
                    hashMap.put("qllxdm", bdcXm.getQllx());
                } else if (StringUtils.isNotBlank(ybdcXm.getQllx())) {
                    hashMap.put("qllxdm", ybdcXm.getQllx());
                }
                hashMap.put("notEqualCheckType", Constants.XT_CHECKTYPE_ZF);
                List<BdcXtCheckinfo> bdcXtCheckinfoList = bdcXtCheckInfoService.getBdcXtCheckInfoList(hashMap);
                if (CollectionUtils.isEmpty(bdcXtCheckinfoList)) {
                    bdcXtCheckinfoList = new ArrayList<BdcXtCheckinfo>();
                }

                List<Map<String, Object>> resultListTemp = projectCheckInfoService.checkXmNew(bdcXtCheckinfoList, project);
                if (CollectionUtils.isNotEmpty(resultListTemp)) {
                    resultList = resultListTemp;
                }
            }
        }
        return resultList;

    }

    @Override
    public void updateWorkFlow(Xmxx xmxx) {
        BdcXm bdcxm = null;
        List<BdcXm> bdcXmList = null;
        HashMap map = new HashMap();
        String remark = "";
        BdcSpxx bdcSpxx = null;
        if (xmxx instanceof BdcXm) {
            bdcxm = (BdcXm) xmxx;
        }
        String sqlxDm = "";
        if (bdcxm != null && StringUtils.isNoneBlank(bdcxm.getProid())) {
            sqlxDm = bdcxm.getSqlx();
            //zwq  一个bdcdy对应一个bdcxm
            if (StringUtils.isNotBlank(bdcxm.getWiid())) {
                map.put("wiid", bdcxm.getWiid());
                bdcXmList = bdcXmService.andEqualQueryBdcXm(map);
                sqlxDm = bdcXmList.get(0).getSqlx();
            }
            bdcSpxx = bdcSpxxService.getBdcSpxxByProid(bdcxm.getProid());
            Example qlrQuery = new Example(BdcQlr.class);
            Example ywrQuery = new Example(BdcQlr.class);
            QllxVo qllxVo = qllxService.makeSureQllx(bdcxm);

            //wcz 修改

            qlrQuery.createCriteria().andEqualTo("proid", bdcxm.getProid()).andEqualTo("qlrlx", Constants.QLRLX_QLR);
            qlrQuery.setOrderByClause("sxh");
            List<BdcQlr> qlrList = entityMapper.selectByExample(BdcQlr.class, qlrQuery);

            ywrQuery.createCriteria().andEqualTo("proid", bdcxm.getProid()).andEqualTo("qlrlx", Constants.QLRLX_YWR);
            ywrQuery.setOrderByClause("sxh");
            List<BdcQlr> ywrList = entityMapper.selectByExample(BdcQlr.class, ywrQuery);

            List<String> bdcdyidList = null;
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                bdcdyidList = new ArrayList<String>();
                for (BdcXm bdcXm : bdcXmList) {
                    if (StringUtils.isNotBlank(bdcXm.getBdcdyid()) && !bdcdyidList.contains(bdcXm.getBdcdyid())) {
                        bdcdyidList.add(bdcXm.getBdcdyid());
                    }
                }
            }
            PfWorkFlowInstanceVo pfWorkFlowInstanceVo = sysWorkFlowInstanceService.getWorkflowInstance(bdcxm.getWiid());
            if (pfWorkFlowInstanceVo != null) {
                String qlr = "";
                String ywr = "";
                if (qlrList != null) {
                    for (BdcQlr bdcQlr : qlrList) {
                        if (StringUtils.isNotBlank(bdcQlr.getQlrmc())) {
                            qlr = qlr + bdcQlr.getQlrmc() + ",";
                        }
                    }
                }
                if (ywrList != null) {
                    for (BdcQlr bdcQlr : ywrList) {
                        if (StringUtils.isNotBlank(bdcQlr.getQlrmc())) {
                            ywr = ywr + bdcQlr.getQlrmc() + ",";
                        }
                    }
                }
                if (StringUtils.isNoneBlank(qlr)) {
                    qlr = StringUtils.substring(qlr, 0, qlr.lastIndexOf(","));
                }
                if (StringUtils.isNoneBlank(ywr)) {
                    ywr = StringUtils.substring(ywr, 0, ywr.lastIndexOf(","));
                }
                if (StringUtils.isNotBlank(qlr)) {
                    pfWorkFlowInstanceVo.setWorkflowIntanceName(qlr);
                }
                if (bdcSpxx != null) {
                    /**
                     * @author <a href="mailto:zhanglili@gtmap.cn">zhanglili</a>
                     * @description 修改批量查封待办任务显示权利人，显示不动产单元号等问题
                     */
                    String bhTemp = CommonUtil.formatEmptyValue(bdcxm.getBh());
                    String qlrTemp = CommonUtil.formatEmptyValue(qlr);
                    String bdcdyhTemp = CommonUtil.formatEmptyValue(bdcSpxx.getBdcdyh());
                    String zlTemp = CommonUtil.formatEmptyValue(bdcSpxx.getZl());
                    String ybhTemp = CommonUtil.formatEmptyValue(bdcxm.getYbh());
                    if ((CollectionUtils.isNotEmpty(bdcdyidList) && bdcdyidList.size() > 1)) {
                        if (StringUtils.isNotBlank(qlrTemp)) {
                            qlrTemp = qlrTemp + "等";
                        }
                        if (bdcdyidList == null || bdcdyidList.size() == 0) {
                            bdcdyhTemp = "";
                        }
                        if (StringUtils.isNotBlank(bdcdyhTemp)) {
                            bdcdyhTemp = bdcdyhTemp + "等";
                        }
                        if (StringUtils.isNotBlank(zlTemp)) {
                            zlTemp = zlTemp + "等";
                        }
                        if (StringUtils.isNotBlank(ybhTemp)) {
                            ybhTemp = ybhTemp + "等";
                        }
                    }
                    remark = bhTemp + Constants.SPLIT_STR + qlrTemp + Constants.SPLIT_STR + bdcdyhTemp + Constants.SPLIT_STR + zlTemp + Constants.SPLIT_STR + ybhTemp + Constants.SPLIT_STR + ywr;
                } else {
                    remark = CommonUtil.formatEmptyValue(bdcxm.getBh()) + Constants.SPLIT_STR + CommonUtil.formatEmptyValue(qlr) + Constants.SPLIT_STR + "" + Constants.SPLIT_STR + CommonUtil.formatEmptyValue(bdcxm.getZl()) + Constants.SPLIT_STR + CommonUtil.formatEmptyValue(bdcxm.getYbh()) + Constants.SPLIT_STR + ywr;
                }

                if (StringUtils.isNotBlank(remark)) {
                    pfWorkFlowInstanceVo.setRemark(remark);
                }
                sysWorkFlowInstanceService.updateWorkFlowInstanceRemark(pfWorkFlowInstanceVo);
                sysWorkFlowInstanceService.updateWorkFlowIntanceName(pfWorkFlowInstanceVo);
            }


        }
    }


    /**
     * @param proid                项目ID
     * @param userid               用户ID
     * @param activityid           当前活动ID
     * @param targetActivityDefids 目标活动定义ID
     * @return
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 针对工作流活动取回或退回的签名意见处理
     */
    @Override
    public void handleRetreatSign(final String proid, final String userid, final String activityid, final String targetActivityDefids) {
        PfWorkFlowInstanceVo pfWorkFlowInstanceVo = sysWorkFlowInstanceService.getWorkflowInstance(proid);
        if (null != pfWorkFlowInstanceVo) {
            //此处应该获取退回后的节点名称，而不是当前节点名称
            String targetActivityName = platformUtil.getTargetActivityName(pfWorkFlowInstanceVo.getWorkflowIntanceId(), targetActivityDefids);
            //String activityName = platformUtil.getPfActivityNameByActivitId(activityid);
            if (signKeyMap.containsKey(targetActivityName)) {
                String signKey = signKeyMap.get(targetActivityName);
                deleleSign(proid, signKey);
            }
        }
    }

    /**
     * @param proid   项目ID
     * @param signKey 签名key，多个key以逗号隔开
     * @return
     * @author <a href="mailto:shenjian@gtmap.cn">shenjian</a>
     * @description 根据签名key删除项目的某些签名
     */
    private void deleleSign(String proid, String signKey) {
        String signKeysArr[] = signKey.split(",");
        for (String tmpSignKey : signKeysArr) {
            if (StringUtils.isNotEmpty(tmpSignKey)) {
                List<PfSignVo> pfSignVoList = sysSignService.getSignList(tmpSignKey, proid);
                if (CollectionUtils.isNotEmpty(pfSignVoList)) {
                    for (PfSignVo pfSignVo : pfSignVoList) {
                        sysSignService.deleteSign(pfSignVo.getSignId());
                    }
                }
            }
        }
    }

    /**
     * @param bdcXm 项目表
     * @author <a href="mailto:liaoxiang@gtmap.cn">liaoxiang</a>
     * @description 删除登簿信息
     */
    private void delProjectEventDbxx(BdcXm bdcXm) {
        BdcBdcdy bdcdy = bdcdyService.queryBdcBdcdyByProid(bdcXm.getProid());
        if (bdcdy != null) {
            BdcBdcdjb bdcBdcdjb = bdcDjbService.selectBdcdjb(StringUtils.substring(bdcdy.getBdcdyh(), 0, 19));
            if (bdcBdcdjb != null) {
                bdcBdcdjb.setDbr("");
                bdcBdcdjb.setDjsj(null);
                entityMapper.updateByPrimaryKeyNull(bdcBdcdjb);
                QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
                qllxVo = qllxService.queryQllxVo(qllxVo, bdcXm.getProid());
                if (qllxVo != null && StringUtils.isNotBlank(qllxVo.getQlid())) {
                    qllxVo.setDbr("");
                    qllxVo.setDjsj(null);
                    qllxVo.setQlqssj(null);
                    // 抵押权缮证退回 清空权利表中不动产权证明号
                    if (qllxVo instanceof BdcDyaq) {
                        BdcDyaq bdcDyaq = (BdcDyaq)qllxVo;
                        bdcDyaq.setBdcqzmh("");
                        entityMapper.updateByPrimaryKeyNull(bdcDyaq);
                    } else {
                        entityMapper.updateByPrimaryKeyNull(qllxVo);
                    }
                } else {
                    //zhouwanqing   这边针对注销和解封的登簿人和登记时间
                    List<BdcXm> ybdcXmList = bdcXmService.getYbdcXmListByProid(bdcXm.getProid());
                    if (CollectionUtils.isNotEmpty(ybdcXmList)) {
                        for (BdcXm ybdcXm : ybdcXmList) {
                            QllxVo yqllxVo = qllxService.makeSureQllx(ybdcXm);
                            yqllxVo = qllxService.queryQllxVo(yqllxVo, ybdcXm.getProid());
                            if (yqllxVo != null && StringUtils.isNotBlank(yqllxVo.getQlid())) {
                                yqllxVo.setDbr("");
                                yqllxVo.setDjsj(null);
                                entityMapper.updateByPrimaryKeyNull(yqllxVo);
                            }
                        }
                    }
                }
            }
        }
    }


    /**
     * @param wiid 流程id
     * @author <a href="mailto:zhangyu@gtmap.cn">zhangyu</a>
     * @description 更新发证日期为缮证日期\发证人
     */

    private void updateBdcZsFzrq(String wiid, String userid) {
        List<BdcZs> zsList = bdcZsService.getPlZsByWiid(wiid);
        PfUserVo pfUserVo = null;
        if (StringUtils.isNotBlank(userid)) {
            pfUserVo = sysUserService.getUserVo(userid);
        }
        if (CollectionUtils.isNotEmpty(zsList)) {
            for (BdcZs bdcZs : zsList) {
                if (null == bdcZs.getFzrq()) {
                    bdcZs.setFzrq(bdcZs.getSzrq());
                }
                if (null == bdcZs.getLzrq()) {
                    bdcZs.setLzrq(new Date());
                }
                if (pfUserVo != null && StringUtils.isEmpty(bdcZs.getFzr())) {
                    bdcZs.setFzr(pfUserVo.getUserName());
                }
                entityMapper.saveOrUpdate(bdcZs, bdcZs.getZsid());
            }
        }
    }

}
