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

import cn.gtmap.estateplat.config.core.mapper.config.BdcDelZszhMapper;
import cn.gtmap.estateplat.config.core.mapper.config.BdcZdGlMapper;
import cn.gtmap.estateplat.config.core.mapper.config.BdcZsMapper;
import cn.gtmap.estateplat.config.core.service.*;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.core.support.mybatis.mapper.Example;
import cn.gtmap.estateplat.model.server.core.*;
import cn.gtmap.estateplat.utils.CalendarUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gtis.common.util.CommonUtil;
import com.gtis.common.util.UUIDGenerator;
import com.gtis.config.AppConfig;
import com.gtis.plat.service.SysWorkFlowInstanceService;
import com.gtis.plat.vo.PfWorkFlowInstanceVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * @version 1.0, 2017/6/28.
 * @auto <a href="mailto:zhouwanqing@gtmap.cn">zhouwanqing</a>
 * @description
 */
@Service
public class BdcZsServiceImpl implements BdcZsService {

    @Autowired
    private BdcXmService bdcXmService;
    @Autowired
    private QllxService qllxService;
    @Autowired
    private BdcQlrService bdcQlrService;
    @Autowired
    private BdcdyService bdcdyService;
    @Autowired
    private BdcXtQlqtzkConfigService bdcXtQlqtzkConfigService;
    @Autowired
    private BdcZsMapper bdcZsMapper;
    @Autowired
    private EntityMapper entityMapper;
    @Autowired
    private DataManagerService dataManagerService;
    @Autowired
    private LogService logService;
    @Autowired
    private BdcDelZszhMapper bdcDelZszhMapper;
    @Autowired
    private BdcXmZsRelService bdcXmZsRelService;
    @Autowired
    private BdcZsQlrRelService bdcZsQlrRelService;
    @Autowired
    private SysWorkFlowInstanceService sysWorkFlowInstanceService;
    @Autowired
    private BdcZdGlService bdcZdGlService;
    @Autowired
    private BdcLshService bdcLshService;
    @Autowired
    BdcFdcqService bdcFdcqSeice;
    @Autowired
    BdcZsCreatZsInfoServiceImpl bdcZsCreatZsInfoService;
    @Autowired
    BdcZsbhService bdcZsbhService;
    @Autowired
    BdcTdService bdcTdService;
    @Autowired
    BdcZdGlMapper bdcZdGlMapper;

    @Override
    public List<BdcZs> getBdcZsByProid(final String proid) {
        List<BdcZs> bdcZsList = null;
        if (StringUtils.isNotBlank(proid)) {
            bdcZsList = bdcZsMapper.getBdcZsByProid(proid);
        }
        return bdcZsList;
    }

    @Override
    public List<BdcZs> getPlZsByWiid(final String wiid) {
        List<BdcZs> bdcZsList = null;
        if (StringUtils.isNotBlank(wiid)) {
            bdcZsList = bdcZsMapper.getPlZsByWiid(wiid);
        }
        return bdcZsList;
    }

    @Override
    public BdcZs queryBdcZsByQlrid(final String zsid) {
        return entityMapper.selectByPrimaryKey(BdcZs.class, zsid);
    }

    @Override
    public List<BdcZs> getBdcZsByBdcqzh(String bdcqzh) {
        Example example = new Example(BdcZs.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(bdcqzh)) {
            criteria.andEqualTo("bdcqzh", bdcqzh);
            return entityMapper.selectByExample(BdcZs.class, example);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Object> getHdrqByWiid(HashMap map) {
        StringBuilder platform = new StringBuilder();
        platform.append(AppConfig.getProperty("egov.db.username"));
        platform.append(".pf_usersign");
        map.put("platFormTable", platform.toString());
        Map<String, Object> result = bdcZsMapper.getHdrqByWiid(map);
        if (result != null) {
            result.put("HDRQ", CalendarUtil.sdf_China.format((Date) result.get("HDRQ")));
        } else {
            result = new HashMap<String, Object>();
            result.put("HDRQ", CalendarUtil.sdf_China.format(new Date()));
        }
        return result;
    }

    @Override
    public List<HashMap> getViewBdcqzList(HashMap map) {
        List<HashMap> zsViewMap = bdcZsMapper.getViewBdcqzList(map);
        return zsViewMap;
    }

    @Override
    public Integer getBdcdyCountByZsid(String zsid) {
        return bdcZsMapper.getBdcdyCountByZsid(zsid);
    }

    @Override
    public String getQlqtzk(String proid) {
        String qlqtzk = "";
        try {
            BdcXm bdcXm = bdcXmService.getBdcXmByProid(proid);
            if (null != bdcXm && StringUtils.isNotBlank(bdcXm.getSqlx())) {
                //获取权利
                QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
                BdcXtQlqtzkConfig bdcXtQlqtzkConfig = new BdcXtQlqtzkConfig();
                bdcXtQlqtzkConfig.setSqlxdm(bdcXm.getSqlx());
                BdcBdcdy bdcBdcdy = null;
                if (StringUtils.isNotBlank(bdcXm.getBdcdyid())) {
                    bdcBdcdy = bdcdyService.queryBdcdyById(bdcXm.getBdcdyid());
                }
                if (StringUtils.isNoneBlank(bdcXm.getProid())) {
                    qllxVo = qllxService.queryQllxVo(qllxVo, bdcXm.getProid());

                }
                //房地产权添加fwlx过滤
                if (bdcBdcdy != null && StringUtils.isNotBlank(bdcBdcdy.getBdcdyfwlx())) {
                    bdcXtQlqtzkConfig.setQllxzlx(bdcBdcdy.getBdcdyfwlx());
                }
                //获取模板
                List<BdcXtQlqtzkConfig> listQlqtzk = bdcXtQlqtzkConfigService.getQlqtzk(bdcXtQlqtzkConfig);
                if (listQlqtzk != null && listQlqtzk.size() > 0) {
                    for (BdcXtQlqtzkConfig qlqtzkConfig : listQlqtzk) {
                        //zhouwanqing 若配置权利类型代码则需要根据权利类型来过滤
                        if (StringUtils.isBlank(qlqtzkConfig.getQllxdm()) || StringUtils.equals(qlqtzkConfig.getQllxdm(), bdcXm.getQllx())) {
                            if (qllxVo != null) {
                                qlqtzk = bdcXtQlqtzkConfigService.replaceMb(qlqtzkConfig.getQlqtzkmb(), qlqtzkConfig.getQtdb(), bdcXm, bdcBdcdy);
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            LoggerFactory.getLogger(getClass()).error("Unexpected error in getQlqtzk function ", e);
        }
        return qlqtzk;
    }

    /**
     * 获取使用期限
     *
     * @param map
     */
    @Override
    public HashMap<String, Object> getSyqx(HashMap<String, Object> map) {
        if (MapUtils.isNotEmpty(map)) {
            String result = null;
            String syksqx = null;
            String syjsqx = null;
            if ((Date) map.get("SYKSQX") != null) {
                syksqx = CalendarUtil.sdf_China.format((Date) map.get("SYKSQX"));
            }
            if ((Date) map.get("SYJSQX") != null) {
                syjsqx = CalendarUtil.sdf_China.format((Date) map.get("SYJSQX"));
            }
            if (StringUtils.isNotBlank(syksqx)) {
                result = syksqx + "至" + syjsqx;
            } else {
                result = syjsqx;
            }
            String proid = (String) map.get("PROID");
            if (StringUtils.isNotBlank(result) && StringUtils.isNotBlank(proid)) {
                StringBuilder bu = new StringBuilder();
                String djsy = bdcXmService.getDjsy(proid);
                if (StringUtils.isNotBlank(djsy)) {
                    bu.append(djsy);
                    bu.append(" ");
                    bu.append(result);
                } else {
                    bu.append(result);
                }
                result = bu.toString();
            }
            map.put("SYQX", result);
        }
        return map;
    }

    @Override
    public void saveZs(BdcZs bdcZs) {
        logService.saveOrUpdateLog(bdcZs);
        entityMapper.saveOrUpdate(bdcZs, bdcZs.getZsid());
    }

    @Override
    public String checkBdcqzh(List<BdcZs> bdcZsList) {
        String msg = "";
        if (CollectionUtils.isNotEmpty(bdcZsList)) {
            for (BdcZs bdcZs : bdcZsList) {
                if (bdcZs != null && StringUtils.isNotBlank(bdcZs.getBdcqzh())) {
                    List<BdcZs> bdcZss = getBdcZsByBdcqzh(bdcZs.getBdcqzh());
                    //zhangyu    此处进行排查 排除当前证书id
                    if (CollectionUtils.isNotEmpty(bdcZss) && !StringUtils.equals(bdcZs.getZsid(), bdcZss.get(0).getZsid())) {
                        msg = "exist";
                        break;
                    }
                }
            }
        }
        return msg;
    }

    @Override
    public String getFj(String proid) {
        String fj = "";
        try {
            BdcXm bdcXm = bdcXmService.getBdcXmByProid(proid);
            if (null != bdcXm && bdcXm.getSqlx() != null) {

                BdcBdcdy bdcBdcdy = null;
                //获取权利
                QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
                BdcXtQlqtzkConfig bdcXtQlqtzkConfig = new BdcXtQlqtzkConfig();
                bdcXtQlqtzkConfig.setSqlxdm(bdcXm.getSqlx());
                if (StringUtils.isNotBlank(bdcXm.getBdcdyid())) {
                    bdcBdcdy = bdcdyService.queryBdcdyById(bdcXm.getBdcdyid());
                }
                if (StringUtils.isNoneBlank(bdcXm.getProid())) {
                    qllxVo = qllxService.queryQllxVo(qllxVo, bdcXm.getProid());
                }

                //房地产权添加fwlx过滤
                if (bdcBdcdy != null && StringUtils.isNotBlank(bdcBdcdy.getBdcdyfwlx())) {
                    bdcXtQlqtzkConfig.setQllxzlx(bdcBdcdy.getBdcdyfwlx());
                }

                List<BdcXtQlqtzkConfig> listQlqtzk = bdcXtQlqtzkConfigService.getQlqtzk(bdcXtQlqtzkConfig);
                if (listQlqtzk != null && listQlqtzk.size() > 0) {
                    for (BdcXtQlqtzkConfig qlqtzkConfig : listQlqtzk) {

                        if (StringUtils.isBlank(qlqtzkConfig.getQllxdm()) || StringUtils.equals(qlqtzkConfig.getQllxdm(), bdcXm.getQllx())) {
                            if (qllxVo != null) {
                                fj = bdcXtQlqtzkConfigService.replaceMb(qlqtzkConfig.getFjmb(), qlqtzkConfig.getFjdb(), bdcXm, bdcBdcdy);
                                if (StringUtils.isNotBlank(fj)) {
                                    qllxVo.setFj(fj);
                                    entityMapper.updateByPrimaryKeySelective(qllxVo);
                                }
                                //刷新附记按份共有
                                List<String> gyfsList = bdcQlrService.getGyfsByProid(proid);
                                if (CollectionUtils.isNotEmpty(gyfsList) && StringUtils.equals(gyfsList.get(0), "2")) {
                                    String bz = "按份共有";
                                    String gyqk = bdcQlrService.getGyqk(proid);
                                    if (StringUtils.isNotBlank(qllxVo.getFj())) {
                                        if (qllxVo.getFj().indexOf(bz) > -1) {
                                            String[] qk = qllxVo.getFj().split("\\n");
                                            String scfj = "";
                                            if (qk[0].indexOf(bz) > -1) {
                                                scfj = gyqk;
                                            } else {
                                                scfj = qk[0];
                                            }
                                            fj = scfj;
                                            for (int j = 1; j != qk.length; j++) {
                                                if (qk[j].indexOf(bz) > -1) {
                                                    scfj = gyqk;
                                                } else {
                                                    scfj = qk[j];
                                                }
                                                fj = fj + "\n" + scfj;
                                            }
                                        } else {
                                            fj = gyqk + "\n" + qllxVo.getFj();
                                        }
                                    } else {
                                        fj = gyqk;
                                    }
                                    qllxVo.setFj(fj);
                                    entityMapper.saveOrUpdate(qllxVo, qllxVo.getQlid());
                                }
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            LoggerFactory.getLogger(getClass()).error("Unexpected error in getFj function ", e);
            e.printStackTrace();
        }
        return fj;

    }

    @Override
    public void deleteBdcZs(String zsid) {
        Example example = new Example(BdcZs.class);
        example.createCriteria().andEqualTo("zsid", zsid);
        dataManagerService.deleteByExample(example);
    }

    @Override
    public List<BdcZs> listBdcZsxx(Map map) {
        return bdcZsMapper.listBdcZsxx(map);
    }

    @Override
    public List<BdcZs> getBdcZsList(Map map) {
        List<BdcZs> bdcZsList = null;
        if (map != null && map.size() > 0) {
            bdcZsList = bdcZsMapper.getBdcZsList(map);
        }
        return bdcZsList;
    }

    @Override
    public List<String> getBdcdyhByBdcqzh(String bdcqzh) {
        return bdcZsMapper.getBdcdyhByBdcqzh(bdcqzh);
    }

    @Override
    public String getProidByBdcqzh(String bdcqzh) {
        String proid = null;
        if (StringUtils.isNotBlank(bdcqzh)) {
            List<String> proids = bdcZsMapper.getProidByBdcqzh(bdcqzh);
            if (CollectionUtils.isNotEmpty(proids)) {
                proid = proids.get(0);
            }
        }
        return proid;
    }

    @Override
    public Integer getBdczsCount() {
        return bdcZsMapper.getBdczsCount();
    }

    /**
     * @Author :<a href="mailto:juyulin@gtmap.cn">juyulin</a>
     * @Description: 根据wiid获取该流程所有证书证明号
     * @Date 9:42 2017/12/26
     */
    @Override
    public List<String> listPlZsZmhByWiid(@Param("wiid") String wiid) {
        if (StringUtils.isNotBlank(wiid)) {
            HashMap hashMap = new HashMap();
            hashMap.put("wiid", wiid);
            return bdcZsMapper.listPlZsZmh(hashMap);
        } else {
            return null;
        }
    }

    /**
     * @Author:<a href="mailto:juyulin@gtmap.cn">juyulin</a>
     * @Description: 根据proids获取该流程所有证书证明号
     * @Date 9:42 2017/12/26
     */
    @Override
    public List<String> listPlZsZmhByProids(List<String> proids) {
        if (CollectionUtils.isNotEmpty(proids)) {
            HashMap hashMap = new HashMap();
            hashMap.put("proids", proids);
            return bdcZsMapper.listPlZsZmh(hashMap);
        } else {
            return null;
        }
    }

    /**
     * @Author:<a href="mailto:juyulin@gtmap.cn">juyulin</a>
     * @Description: 获取当前项目所有证书证明号
     * @Date 9:42 2017/12/26
     */
    @Override
    public List<String> listPlZsZmhByProid(@Param("proid") String proid) {
        if (StringUtils.isNotBlank(proid)) {
            HashMap hashMap = new HashMap();
            hashMap.put("proid", proid);
            return bdcZsMapper.listPlZsZmh(hashMap);
        } else {
            return null;
        }
    }

    @Override
    public BdcXm getBdcXmByBdcqzh(String bdcqzh) {
        BdcXm bdcXm = null;
        if (StringUtils.isNotBlank(bdcqzh)) {
            Map map = Maps.newHashMap();
            map.put("bdcqzh", bdcqzh);
            List<BdcXm> bdcXmList = bdcZsMapper.getBdcXmByBdcqzh(map);
            if (CollectionUtils.isNotEmpty(bdcXmList)) {
                bdcXm = bdcXmList.get(0);
            }
        }
        return bdcXm;
    }


    @Override
    public List<BdcXm> getBdcXmByBdcqzh(List<String> bdcqzhList) {
        List<String> filteredList = new ArrayList<String>();
        if (CollectionUtils.isNotEmpty(bdcqzhList)) {
            for (String s : bdcqzhList) {
                if (StringUtils.isNotBlank(s)) {
                    filteredList.add(s);
                }
            }
        }
        List<BdcXm> bdcXmList = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(filteredList)) {
            Map map = Maps.newHashMap();
            map.put("bdcqzhList", filteredList);
            bdcXmList = bdcZsMapper.getBdcXmByBdcqzh(map);
        }
        if (CollectionUtils.isEmpty(bdcXmList)) {
            bdcXmList = Collections.EMPTY_LIST;
        }
        return bdcXmList;
    }

    @Override
    public List<BdcZs> getBdcZsByQlrid(String qlrid) {
        List<BdcZs> bdcZsList = null;
        if (StringUtils.isNotBlank(qlrid)) {
            bdcZsList = bdcZsMapper.getBdcZsByQlrid(qlrid);
        }
        return bdcZsList;
    }

    @Override
    public void delBdcZsByZsid(final String zsid) {
        if (StringUtils.isNotBlank(zsid)) {
            BdcZs bdcZs = queryBdcZsByQlrid(zsid);
            if (bdcZs != null && StringUtils.isNotBlank(bdcZs.getBdcqzh())) {
                HashMap map = new HashMap();
                map.put("bdcqzh", bdcZs.getBdcqzh());
                map.put("dwdm", bdcZs.getDwdm());
                map.put("nf", bdcZs.getNf());
                map.put("isuse", "0");
                List<BdcDelZszh> bdcDelZszhList = bdcDelZszhMapper.getBdcDelZszhList(map);
                if (bdcDelZszhList == null || bdcDelZszhList.size() == 0) {
                    BdcDelZszh bdcDelZszh = getBdcDelZszhFromBdcZs(null, bdcZs);
                    entityMapper.insertSelective(bdcDelZszh);
                }
            }
            entityMapper.deleteByPrimaryKey(BdcZs.class, zsid);
        }
    }

    private BdcDelZszh getBdcDelZszhFromBdcZs(BdcDelZszh bdcDelZszh, BdcZs bdcZs) {
        if (bdcZs != null) {
            if (bdcDelZszh == null) {
                bdcDelZszh = new BdcDelZszh();
            }
            bdcDelZszh.setBdcqzh(bdcZs.getBdcqzh());
            bdcDelZszh.setDwdm(bdcZs.getDwdm());
            bdcDelZszh.setNf(bdcZs.getNf());
            bdcDelZszh.setSqsjc(bdcZs.getSqsjc());
            bdcDelZszh.setSzsxqc(bdcZs.getSzsxqc());
            bdcDelZszh.setZslx(bdcZs.getZslx());
            bdcDelZszh.setGxrq(new Date());
            bdcDelZszh.setZhlsh(bdcZs.getZhlsh());
            bdcDelZszh.setZstype(bdcZs.getZstype());
            if (StringUtils.isBlank(bdcDelZszh.getZszhid())) {
                bdcDelZszh.setZszhid(UUIDGenerator.generate());
            }
        }
        return bdcDelZszh;
    }

    @Override
    public List<BdcZs> queryBdcZsByProid(final String proid) {
        List<BdcZs> list = null;
        if (StringUtils.isNotBlank(proid)) {
            list = bdcZsMapper.getBdcZsByProid(proid);
        }
        return list;
    }

    @Override
    public List<BdcZs> creatBdcqz(BdcXm bdcXm, List<BdcQlr> bdcQlrList) {
        return creatBdcqz(bdcXm, bdcQlrList, null);
    }

    //synchronized关键字与Transactional主键不能同时使用
    @Override
    public List<BdcZs> creatBdcqz(BdcXm bdcXm, List<BdcQlr> bdcQlrList, String userId) {
        //zx创建证书时先删除证书和权利人和证书关系
        if (bdcXm != null && StringUtils.isNotBlank(bdcXm.getProid())) {
            delBdcZsByProid(bdcXm.getProid());
        }

        List<BdcZs> list = new ArrayList<BdcZs>();
        synchronized (this) {
            if (bdcXm != null && "是".equals(bdcXm.getSqfbcz())) {
                // 生成多本证书
                if (bdcQlrList != null && bdcQlrList.size() > 0) {
                    for (int i = 0; i < bdcQlrList.size(); i++) {
                        BdcQlr bdcQlr = bdcQlrList.get(i);
                        BdcDyZs bdcDyZs = creatBdcZs(bdcXm, bdcQlr.getQlrmc(), null);
                        if (bdcDyZs == null) {
                            continue;
                        }
                        bdcDyZs.setZsid(UUIDGenerator.generate18());
                        BdcZs bdcZs = getBdcZsFromBdcDyZs(bdcDyZs);

                        //对证书表存储冗余字段
                        bdcZs.setQlrzjzl(bdcQlr.getQlrsfzjzl());
                        bdcZs.setQlrzjh(bdcQlr.getQlrzjh());

                        entityMapper.insertSelective(bdcZs);
                        BdcZs bdcZs1 = getBdcZsFromBdcDyZs(bdcDyZs);
                        list.add(bdcZs1);
                    }
                }
            } else {
                String czr = "";
                if (bdcQlrList != null) {
                    if (bdcQlrList.size() == 1) {
                        czr = bdcQlrList.get(0).getQlrmc();
                    } else if (bdcQlrList.size() > 1) {
                        for (BdcQlr bdcQlr : bdcQlrList) {
                            if (czr.equals("")) {
                                if (StringUtils.isNotBlank(bdcQlr.getQlrmc()))
                                    czr = bdcQlr.getQlrmc();
                            } else {
                                if (StringUtils.isNotBlank(bdcQlr.getQlrmc())) {
                                    czr = czr + "、" + bdcQlr.getQlrmc();
                                }
                            }
                        }
                    }

                }
                String bdcZsId = "";
                String bdcqzh = "";

                BdcDyZs bdcZs = creatBdcZs(bdcXm, czr, bdcqzh, userId);
                bdcZsId = UUIDGenerator.generate18();
                bdcZs.setZsid(bdcZsId);

                BdcZs bdcZs1 = getBdcZsFromBdcDyZs(bdcZs);
                entityMapper.insertSelective(bdcZs1);

                //保存权利人证书关系表
//                if (bdcQlrList != null && bdcQlrList.size() > 0) {
//                    for (BdcQlr bdcQlr : bdcQlrList) {
//                        BdcZsQlrRel bdcZsQlrRel = new BdcZsQlrRel();
//                        bdcZsQlrRel.setGxid(UUIDGenerator.generate18());
//                        bdcZsQlrRel.setQlrid(bdcQlr.getQlrid());
//                        bdcZsQlrRel.setZsid(bdcZsId);
//                        entityMapper.insertSelective(bdcZsQlrRel);
//
//                    }
//                }
                list.add(bdcZs1);
            }
        }
        return list;
    }


    @Override
    public void delBdcZsByProid(final String proid) {
        if (StringUtils.isNotBlank(proid)) {
            List<BdcXmzsRel> bdcXmzsRelList = bdcXmZsRelService.queryBdcXmZsRelByProid(proid);
            if (bdcXmzsRelList != null && bdcXmzsRelList.size() > 0) {
                for (BdcXmzsRel bdcXmzsRel : bdcXmzsRelList) {
                    if (bdcXmzsRel != null && StringUtils.isNotBlank(bdcXmzsRel.getZsid())) {
                        bdcZsQlrRelService.delZsQlrRelByZsid(bdcXmzsRel.getZsid());
                        delBdcZsByZsid(bdcXmzsRel.getZsid());
                    }
                }
            }
            bdcXmZsRelService.delBdcXmZsRelByProid(proid);

        }
    }


    @Override
    public BdcDyZs creatBdcZs(BdcXm bdcXm, String czr, String bdcqzh) {
        BdcDyZs bdcDyZs = new BdcDyZs();
        if (bdcXm != null) {
//            zx判断提前生成证书
            //重新生成其他权利状况
            bdcDyZs = getZsQlqtzk(bdcXm, new BdcDyZs());

            List<BdcFdcq> bdcFdcqList = bdcFdcqSeice.getBdcFdcqListByProid(bdcXm.getProid());
            if (CollectionUtils.isEmpty(bdcFdcqList) || !StringUtils.equals(bdcFdcqList.get(0).getFzlx(), Constants.FZLX_FZM)) {

                if (StringUtils.equals(bdcXm.getSqfbcz(), "是")) {
                    bdcZsCreatZsInfoService.setQygyr(bdcXm, czr, bdcDyZs);
                }
            }
            if (!StringUtils.equals(bdcXm.getSftqsczs(), "1")) {
                //生成证号
                if (StringUtils.isBlank(bdcqzh)) {
                    BdcZs bdcZs = bdcZsbhService.creatBdcqzBh(bdcXm, bdcDyZs, 0);
                    bdcDyZs = new BdcDyZs();
                    try {
                        BeanUtils.copyProperties(bdcDyZs, bdcZs);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                } else {
                    bdcDyZs.setBdcqzh(bdcqzh);
                }
            }
            QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
            String zsFont = qllxService.makeSureBdcqzlx(qllxVo);

            if (StringUtils.equals(bdcXm.getSqlx(), Constants.SQLX_SPFGYSCDJ_DM) || StringUtils.equals(bdcXm.getSqlx(), Constants.SQLX_SPFXZBG_DM)) {
                if (CollectionUtils.isNotEmpty(bdcFdcqList)) {
                    BdcFdcq bdcFdcq = bdcFdcqList.get(0);
                    String fzlx = bdcFdcq.getFzlx();
                    //首次信息表表变更登记，选择不动产单元，自动生成发证类型（信息表）
                    if (StringUtils.isBlank(fzlx) && StringUtils.equals(bdcXm.getSqlx(), Constants.SQLX_SPFXZBG_DM)) {
                        bdcFdcq.setFzlx(Constants.FZLX_FZM);
                        entityMapper.saveOrUpdate(bdcFdcq, bdcFdcq.getQlid());
                    }
                    if (StringUtils.equals(fzlx, Constants.FZLX_FZM)) {
                        String zsFont1 = AppConfig.getProperty("spfscdj.zstype");
                        if (StringUtils.isNotBlank(zsFont1) && (StringUtils.equals(zsFont1, Constants.BDCQSCDJZ_BH_FONT))) {
                            zsFont = zsFont1;
                        }
                    }
                }
            }
            bdcDyZs.setZstype(zsFont);
            //根据zstype判断是否需要持证人
            if (StringUtils.equals(bdcDyZs.getZstype(), Constants.BDCQZS_BH_FONT)) {
//                bdcZsCreatZsInfoService.setQygyr(bdcXm, czr, bdcDyZs);
                bdcZsCreatZsInfoService.setCzr(bdcXm, czr, bdcDyZs);
            }

            //不动产权证号配置到各乡镇，各乡镇可能不同可能相同,就需要将该项目办理乡镇的行政代码存储到bdcZs里的dwdm
            String bdcqzhFilterZhXzdm = AppConfig.getProperty("bdcqzh.filterZh.xzdm");
            if (StringUtils.equals(bdcqzhFilterZhXzdm, "true")) {
                bdcDyZs.setDwdm(bdcXm.getSsxz());
            } else {
                bdcDyZs.setDwdm(bdcXm.getDwdm());
            }
            bdcDyZs.setZslx(bdcXm.getQllx());
            bdcDyZs.setCzr(czr);
            bdcDyZs.setCzrq(CommonUtil.getCurrDate());

            //补充增加证书信息字段
            //qlr
            List<BdcQlr> bdcQlrList = bdcQlrService.queryBdcQlrByProid(bdcXm.getProid());
            if (StringUtils.equals(bdcXm.getSqfbcz(), "是")) {
                bdcDyZs.setQlr(czr);
            } else {
                if (CollectionUtils.isNotEmpty(bdcQlrList)) {
                    String qlr = "";
                    String qlrzjzl = "";
                    StringBuilder qlrzjh = new StringBuilder("");
                    for (BdcQlr bdcQlr : bdcQlrList) {
                        if (StringUtils.isNotBlank(qlr)) {
                            qlr = qlr + " " + bdcQlr.getQlrmc();
                            qlrzjh = qlrzjh.append(" ").append(bdcQlr.getQlrzjh());
                        } else {
                            qlr = bdcQlr.getQlrmc();
                            qlrzjh = qlrzjh.append(bdcQlr.getQlrzjh());
                        }
                        qlrzjzl = bdcQlr.getQlrsfzjzl();
                    }
                    bdcDyZs.setQlr(qlr);
                    bdcDyZs.setQlrzjh(qlrzjh.toString());
                    bdcDyZs.setQlrzjzl(qlrzjzl);
                }
            }
            //ywr
            List<BdcQlr> bdcYwrList = bdcQlrService.queryBdcYwrByProid(bdcXm.getProid());
            if (CollectionUtils.isNotEmpty(bdcYwrList)) {
                String ywr = "";
                String ywrzjzl = "";
                StringBuilder ywrzjh = new StringBuilder("");
                for (BdcQlr bdcQlr : bdcYwrList) {
                    if (StringUtils.isNotBlank(ywr)) {
                        ywr = ywr + " " + bdcQlr.getQlrmc();
                        ywrzjh = ywrzjh.append(" ").append(bdcQlr.getQlrzjh());
                    } else {
                        ywr = bdcQlr.getQlrmc();
                        ywrzjh = ywrzjh.append(bdcQlr.getQlrzjh());
                    }
                    ywrzjzl = bdcQlr.getQlrsfzjzl();
                }
                bdcDyZs.setYwr(ywr);
                bdcDyZs.setYwrzjh(ywrzjh.toString());
                bdcDyZs.setYwrzjzl(ywrzjzl);
            }
            HashMap map = Maps.newHashMap();
            //只生成一本证书的情况根据wiid查询
            if (StringUtils.equals(Constants.DJLX_PLDY_YBZS_SQLXDM, bdcXm.getSqlx())) {
                map.put("onezsproid", bdcXm.getProid());
            } else {
                map.put("proid", bdcXm.getProid());
            }
            List<HashMap> bdczsViewList = bdcZsMapper.getViewBdcqzList(map);
            String fj = "";
            if (CollectionUtils.isNotEmpty(bdczsViewList)) {
                fj = cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("FJ"));
                for (HashMap bdczsView : bdczsViewList) {
                    String tempFj = cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsView.get("FJ"));
                    if (StringUtils.isNotBlank(fj) && !StringUtils.contains(fj, tempFj)) {
                        fj += "\n" + tempFj;
                    }
                }
            }
            // gyqk
            if (CollectionUtils.isNotEmpty(bdcQlrList) && StringUtils.isNotBlank(bdcQlrList.get(0).getGyfs())) {
                List<String> gyfsList = new ArrayList<String>();
                for (BdcQlr bdcQlr : bdcQlrList) {
                    if (!gyfsList.contains(bdcQlr.getGyfs())) {
                        gyfsList.add(bdcQlr.getGyfs());
                    }
                }
                if (CollectionUtils.isNotEmpty(gyfsList) && gyfsList.size() == 2 && gyfsList.contains("2") && gyfsList.contains("1")) {
                    bdcDyZs.setGyqk("2");
                } else {
                    bdcDyZs.setGyqk(bdcQlrList.get(0).getGyfs());
                }
            } else {
                bdcDyZs.setGyqk(Constants.GYFS_DDGY_DM);
            }
            if (StringUtils.equals(bdcDyZs.getZstype(), Constants.BDCQZM_BH_FONT)) {
                //不动产权证明
                //zl、bdcdyh、mj、syqx
                if (CollectionUtils.isNotEmpty(bdczsViewList)) {
                    bdcDyZs.setZl(cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("ZL")));
                    bdcDyZs.setBdcdyh(cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("BDCDYH")));
                    bdcDyZs.setFj(fj);
                }
                bdcDyZs.setZmqlsx(bdcXm.getQllx());
            } else {
                //zl、bdcdyh、mj、syqx
                if (CollectionUtils.isNotEmpty(bdczsViewList)) {
                    bdcDyZs.setZl(cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("ZL")));
                    bdcDyZs.setBdcdyh(cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("BDCDYH")));
                    bdcDyZs.setQlxz(cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("QLXZ")));
                    bdcDyZs.setYt(cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("YT")));
                    String sfpdgyz = AppConfig.getProperty("sfpdgyz");
                    String zdMj = cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("ZSMJ"));
                    if (StringUtils.isNotBlank(sfpdgyz) && Boolean.parseBoolean(sfpdgyz)) {
                        String zdLb = bdcTdService.getZdLb(bdcXm.getProid());
                        zdMj = bdcTdService.changeMjByZdLb(zdLb, zdMj, bdcXm.getBdclx());
                    }
                    bdcDyZs.setMj(zdMj);
                    String djsy = bdcXm.getDjsy();
                    String syksqx = cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("SYKSQX"));
                    String syjsqx = cn.gtmap.estateplat.utils.CommonUtil.formatEmptyValue(bdczsViewList.get(0).get("SYJSQX"));
                    String djsymc = "";
                    String syqx = "";
                    if (StringUtils.isNotBlank(djsy) && StringUtils.length(djsy) > 0 && djsy.indexOf("/") > -1) {
                        djsymc = bdcZdGlMapper.getDjsyByDm(djsy.substring(0, djsy.indexOf("/")));
                    } else if (StringUtils.isNotBlank(djsy)) {
                        djsymc = bdcZdGlMapper.getDjsyByDm(djsy);
                    }
                    if (StringUtils.isNotBlank(syksqx) && StringUtils.isNotBlank(syjsqx)) {
                        syqx = djsymc + " " + CalendarUtil.formateToStrChinaYMDDate(CalendarUtil.formatDate(syksqx)) + "起" + CalendarUtil.formateToStrChinaYMDDate(CalendarUtil.formatDate(syjsqx)) + "止";
                    } else if (StringUtils.isNotBlank(syksqx)) {
                        syqx = djsymc + " " + CalendarUtil.formateToStrChinaYMDDate(CalendarUtil.formatDate(syksqx)) + "起";
                    } else if (StringUtils.isNotBlank(syjsqx)) {
                        syqx = djsymc + " " + CalendarUtil.formateToStrChinaYMDDate(CalendarUtil.formatDate(syjsqx)) + "止";
                    } else {
                    }
                    bdcDyZs.setSyqx(syqx);
                    bdcDyZs.setFj(fj);
                }
            }


            bdcDyZs.setQllx(bdcXm.getQllx());
            bdcDyZs.setEwmnr(bdcXm.getBh());
            bdcDyZs.setFzrq(new Date());
            bdcDyZs.setSqlxdm(bdcXm.getSqlx());
            if (StringUtils.isNotBlank(bdcXm.getSqlx())) {
                HashMap map_sqlx = Maps.newHashMap();
                map_sqlx.put("dm", bdcXm.getSqlx());
                List<BdcZdSqlx> bdcZdSqlxList = bdcZdGlService.getBdcSqlxByMap(map_sqlx);
                if (CollectionUtils.isNotEmpty(bdcZdSqlxList)) {
                    bdcDyZs.setSqlxmc(StringUtils.isNotEmpty(bdcZdSqlxList.get(0).getMc()) ? bdcZdSqlxList.get(0).getMc() : null);
                }
            }

        }

        return bdcDyZs;
    }


    @Override
    public BdcDyZs getZsQlqtzk(BdcXm bdcXm, BdcDyZs bdcZs) {
        try {
            if (bdcXm != null && bdcXm.getSqlx() != null) {
                //获取权利
                QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
                BdcXtQlqtzkConfig bdcXtQlqtzkConfig = new BdcXtQlqtzkConfig();
                bdcXtQlqtzkConfig.setSqlxdm(bdcXm.getSqlx());
                BdcBdcdy bdcBdcdy = null;
                if (StringUtils.isNotBlank(bdcXm.getBdcdyid())) {
                    bdcBdcdy = bdcdyService.queryBdcdyById(bdcXm.getBdcdyid());
                }
                if (StringUtils.isNotBlank(bdcXm.getProid())) {
                    qllxVo = qllxService.queryQllxVo(qllxVo, bdcXm.getProid());

                }

                //任意组合交叉共有方式权利附记问题
                String sqlxdm = "";
                if (StringUtils.isNotBlank(bdcXm.getWiid())) {
                    PfWorkFlowInstanceVo pfWorkFlowInstanceVo = sysWorkFlowInstanceService.getWorkflowInstance(bdcXm.getWiid());
                    if (pfWorkFlowInstanceVo != null && StringUtils.isNotBlank(pfWorkFlowInstanceVo.getWorkflowDefinitionId())) {
                        sqlxdm = bdcZdGlService.getBdcSqlxdmByWdid(pfWorkFlowInstanceVo.getWorkflowDefinitionId());
                    }
                }
                if (StringUtils.equals(sqlxdm, Constants.SQLX_HDDJ_RYZH)) {
                    List<BdcQlr> bdcQlrList = bdcQlrService.queryBdcQlrByProid(bdcXm.getProid());
                    if (bdcQlrService.isAfgyContainGtgy(bdcQlrList)) {
                        if (StringUtils.isNotBlank(qllxVo.getFj())) {
                            if (qllxVo.getFj().indexOf(Constants.GYFS_AFGY_MC) == -1) {
                                qllxVo.setFj(qllxVo.getFj() + "\n" + Constants.GYFS_AFGY_MC + "：" + bdcQlrService.getGyqk(bdcXm.getProid()));
                            }
                        } else {
                            qllxVo.setFj(Constants.GYFS_AFGY_MC + "：" + bdcQlrService.getGyqk(bdcXm.getProid()));
                        }
                    }
                }

                //房地产权添加fwlx过滤
                if (bdcBdcdy != null && StringUtils.isNotBlank(bdcBdcdy.getBdcdyfwlx())) {
                    bdcXtQlqtzkConfig.setQllxzlx(bdcBdcdy.getBdcdyfwlx());
                }
                //权利类型过滤
                if (StringUtils.isNotBlank(bdcXm.getQllx())) {
                    bdcXtQlqtzkConfig.setQllxdm(bdcXm.getQllx());
                }
                //获取模板
                List<BdcXtQlqtzkConfig> listQlqtzk = bdcXtQlqtzkConfigService.getQlqtzk(bdcXtQlqtzkConfig);
                if (listQlqtzk != null && listQlqtzk.size() > 0) {
                    for (BdcXtQlqtzkConfig qlqtzkConfig : listQlqtzk) {
                        //zhouwanqing 若配置权利类型代码则需要根据权利类型来过滤
                        if (StringUtils.isBlank(qlqtzkConfig.getQllxdm()) || StringUtils.equals(qlqtzkConfig.getQllxdm(), bdcXm.getQllx())) {
                            if (qllxVo != null) {
                                bdcZs.setQlqtzk(bdcXtQlqtzkConfigService.replaceMb(qlqtzkConfig.getQlqtzkmb(), qlqtzkConfig.getQtdb(), bdcXm, bdcBdcdy));
                                if (!AppConfig.getProperty("dwdm").equals("320900")) {
                                    String fj = bdcXtQlqtzkConfigService.replaceMb(qlqtzkConfig.getFjmb(), qlqtzkConfig.getFjdb(), bdcXm, bdcBdcdy);
                                    if (StringUtils.isNotBlank(qllxVo.getFj())) {
                                        if (-1 == StringUtils.indexOf(qllxVo.getFj() + "\n", fj)) {
                                            qllxVo.setFj(qllxVo.getFj() + "\n" + fj);
                                        }
                                    } else {
                                        qllxVo.setFj(fj);
                                    }
                                }
                                entityMapper.updateByPrimaryKeySelective(qllxVo);
                            }
                        }
                    }
                    if (!AppConfig.getProperty("dwdm").equals("320900")) {
                        //批量抵押（多抵一）每个bdc_dyaq的fj都应有值
                        if (bdcXm != null && StringUtils.isNotBlank(bdcXm.getWiid()) && StringUtils.equals(bdcXm.getSqlx(), Constants.DJLX_PLDY_YBZS_SQLXDM)) {
                            List<BdcXm> xmList = bdcXmService.getBdcXmListByWiid(bdcXm.getWiid());
                            if (CollectionUtils.isNotEmpty(xmList)) {
                                BdcXtQlqtzkConfig qlqtzkConfig = listQlqtzk.get(0);
                                String fj = bdcXtQlqtzkConfigService.replaceMb(qlqtzkConfig.getFjmb(), qlqtzkConfig.getFjdb(), bdcXm, bdcBdcdy);
                                for (BdcXm xm : xmList) {
                                    QllxVo Vo = qllxService.makeSureQllx(xm);
                                    Vo = qllxService.queryQllxVo(Vo, xm.getProid());
                                    if (Vo != null) {
                                        Vo.setFj(fj);
                                        entityMapper.updateByPrimaryKeySelective(Vo);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (bdcXm != null) {
                QllxVo qllxVo1 = qllxService.queryQllxVo(bdcXm);
                if (qllxVo1 != null) {
                    if (qllxVo1 instanceof BdcHysyq) {
                        bdcZs.setFzrq(((BdcHysyq) qllxVo1).getDjsj());
                    } else if (qllxVo1 instanceof BdcJsydzjdsyq) {
                        bdcZs.setFzrq(((BdcJsydzjdsyq) qllxVo1).getDjsj());
                    } else if (qllxVo1 instanceof BdcJzwgy) {
                        bdcZs.setFzrq(((BdcJzwgy) qllxVo1).getDjsj());
                    } else if (qllxVo1 instanceof BdcJzwsyq) {
                        bdcZs.setFzrq(((BdcJzwsyq) qllxVo1).getDjsj());
                    } else if (qllxVo1 instanceof BdcQsq) {
                        bdcZs.setFzrq(((BdcQsq) qllxVo1).getDjsj());
                    } else if (qllxVo1 instanceof BdcDyaq) {
                        bdcZs.setFzrq(((BdcDyaq) qllxVo1).getDjsj());
                    }
                }

            }
            if (bdcXm != null && StringUtils.isNotBlank(bdcXm.getBdcdyid())) {
                bdcZs.setBdcdyid(bdcXm.getBdcdyid());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bdcZs;
    }

    private BdcZs getBdcZsFromBdcDyZs(BdcDyZs bdcDyZs) {
        BdcZs bdcZs = new BdcZs();
        if (bdcDyZs != null) {
            bdcZs.setSzr(bdcDyZs.getSzr());
            bdcZs.setBdcqzh(bdcDyZs.getBdcqzh());
            bdcZs.setBh(bdcDyZs.getBh());
            bdcZs.setCzr(bdcDyZs.getCzr());
            bdcZs.setCzrq(bdcDyZs.getCzrq());
            bdcZs.setDwdm(bdcDyZs.getDwdm());
            bdcZs.setFzrq(bdcDyZs.getFzrq());
            bdcZs.setNf(bdcDyZs.getNf());
            bdcZs.setSqsjc(bdcDyZs.getSqsjc());
            bdcZs.setQlqtzk(bdcDyZs.getQlqtzk());
            bdcZs.setSzsxqc(bdcDyZs.getSzsxqc());
            bdcZs.setZhlsh(bdcDyZs.getZhlsh());
            bdcZs.setZslx(bdcDyZs.getZslx());
            bdcZs.setZstype(bdcDyZs.getZstype());
            bdcZs.setZsid(bdcDyZs.getZsid());
            bdcZs.setSyqx(bdcDyZs.getSyqx());
            bdcZs.setQlxz(bdcDyZs.getQlxz());
            bdcZs.setQllx(bdcDyZs.getQllx());
            bdcZs.setQlr(bdcDyZs.getQlr());
            bdcZs.setMj(bdcDyZs.getMj());
            bdcZs.setFj(bdcDyZs.getFj());
            bdcZs.setYwr(bdcDyZs.getYwr());
            bdcZs.setYt(bdcDyZs.getYt());
            bdcZs.setBdcdyh(bdcDyZs.getBdcdyh());
            bdcZs.setGyqk(bdcDyZs.getGyqk());
            bdcZs.setZmqlsx(bdcDyZs.getZmqlsx());
            bdcZs.setZl(bdcDyZs.getZl());
            bdcZs.setFzrq(bdcDyZs.getFzrq());
            bdcZs.setEwmnr(bdcDyZs.getEwmnr());
            bdcZs.setQlrzjh(bdcDyZs.getQlrzjh());
            bdcZs.setQlrzjzl(bdcDyZs.getQlrzjzl());
            bdcZs.setYwrzjzl(bdcDyZs.getYwrzjzl());
            bdcZs.setYwrzjh(bdcDyZs.getYwrzjh());
            bdcZs.setSqlxdm(bdcDyZs.getSqlxdm());
            bdcZs.setSqlxmc(bdcDyZs.getSqlxmc());
        }
        return bdcZs;
    }

    @Override
    public BdcDyZs creatBdcZs(BdcXm bdcXm, String czr, String bdcqzh, String userId) {
        BdcDyZs bdcDyZs = creatBdcZs(bdcXm, czr, bdcqzh);
        String bhVersion = AppConfig.getProperty("scdjxxb.bh.version");
        if (bdcDyZs != null && StringUtils.equals(bdcDyZs.getZstype(), Constants.BDCQSCDJZ_BH_FONT) && StringUtils.equals(bhVersion, "sz")) {
            //不动产首次信息表添加编号
            String nf = CalendarUtil.getCurrYear();
            String qh = bdcLshService.getQh(userId);
            String lsh = bdcLshService.getLsh(Constants.BHLX_BDCSCXXB_MC, nf, qh);
            String bh = bdcLshService.getBh(Constants.BHLX_BDCSCXXB_MC, nf, qh, lsh);
            if (StringUtils.isNotBlank(bh)) {
                bdcDyZs.setBh(bh);
                bdcDyZs.setBdcqzh(bh);
            }
        }
        return bdcDyZs;
    }

    @Override
    public Integer getMaxLsh(final Map map) {
        return bdcZsMapper.getMaxLsh(map);  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public List<BdcXmzsRel> getBdcXmzsRelByBdcqzh(String bdcqzh) {
        return bdcZsMapper.getBdcXmzsRelByBdcqzh(bdcqzh);
    }

    @Override
    public void backDelSzrByWiid(String wiid) {
        List<BdcZs> bdcZsList = bdcZsMapper.getPlZsByWiid(wiid);
        if (CollectionUtils.isNotEmpty(bdcZsList)) {
            for (BdcZs bdcZs : bdcZsList) {
                if (bdcZs != null) {
                    bdcZs.setSzr("");
                    bdcZs.setSzrq(null);
                    bdcZs.setFzr("");
                    //bdcZs.setFzrq(null);
                    bdcZs.setCzr("");
                    bdcZs.setCzrq(null);
                    bdcZs.setLzr("");
                    bdcZs.setLzrzjh("");
                    bdcZs.setLzrzjzl("");
                    entityMapper.updateByPrimaryKeyNull(bdcZs);
                }
            }
        }
    }

    @Override
    @Transactional
    public void updateBdcZsRedundantField(BdcZs bdcZs) {
        if (bdcZs != null && StringUtils.isNotBlank(bdcZs.getZsid())) {
            bdcZsMapper.updateBdcZsRedundantField(bdcZs);
        }
    }
}
