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.BdcZsBhMapper;
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.model.server.core.*;
import cn.gtmap.estateplat.utils.CalendarUtil;
import com.gtis.common.util.UUIDGenerator;
import com.gtis.config.AppConfig;
import com.gtis.web.SessionUtil;
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.text.DecimalFormat;
import java.util.*;

/**
 * @version 1.0, 2017/6/26.
 * @auto <a href="mailto:zhouwanqing@gtmap.cn">zhouwanqing</a>
 * @description
 */
@Service
public class BdcZsbhServiceImpl implements BdcZsbhService {
    @Autowired
    private BdcZsBhMapper bdcZsBhMapper;
    @Autowired
    private EntityMapper entityMapper;
    @Autowired
    private BdcXtConfigService bdcXtConfigService;
    @Autowired
    private BdcZsMapper bdcZsMapper;
    @Autowired
    private QllxService qllxService;
    @Autowired
    private BdcFdcqService bdcFdcqService;
    @Autowired
    private BdcDelZszhMapper bdcDelZszhMapper;
    @Autowired
    private BdcZsService bdcZsService;


    @Override
    public List<BdcZsbh> getBdcZsBhListByBhfw(Map map) {
        return bdcZsBhMapper.getBdcZsBhListByBhfw(map);
    }

    @Override
    public String checkAndSaveZsh(List<BdcZsbh> bdcZsbhList, BdcZsbh bdcZsbh, String qsbh, String jsbh) {
        String msg = "保存失败";
        if (CollectionUtils.isNotEmpty(bdcZsbhList)) {
            return "您所需要新增证书编号在系统中已存在，请重新选择";
        } else {
            if (StringUtils.isNotBlank(qsbh) && StringUtils.isNotBlank(jsbh)) {
                String prefixConfig = AppConfig.getProperty("zsbhgl.dzzmh.rule.prefix");
                String sxhConfig = AppConfig.getProperty("zsbhgl.dzzmh.rule.sxh");
                String sqdm = "";
                if (StringUtils.length(bdcZsbh.getDwdm()) > 1) {
                    sqdm = StringUtils.substring(bdcZsbh.getDwdm(), 0, 2);
                }
                String sxh = AppConfig.getProperty("zsbhgl.rule.sxh");
                if (StringUtils.isBlank(sxh)) {
                    sxh = "000000000";
                }
                if(StringUtils.isNotBlank(sxhConfig)){
                    sxh = sxhConfig;
                }
                DecimalFormat df = new DecimalFormat(sxh);
                for (int i = 0; i < (Integer.parseInt(jsbh) - Integer.parseInt(qsbh) + 1); i++) {
                    bdcZsbh.setZsbhid(UUIDGenerator.generate18());
                    if(StringUtils.isNotBlank(prefixConfig)){
                        sqdm = prefixConfig;
                    }
                    String zsbh = sqdm + df.format(Integer.parseInt(qsbh) + i);
                    bdcZsbh.setZsbh(zsbh);
                    entityMapper.saveOrUpdate(bdcZsbh, bdcZsbh.getZsbhid());
                }
                msg = "保存成功";
            }
        }
        return msg;
    }

    @Override
    public List<BdcZsbh> getBdcZsBhListByQzBh(Map map) {
        return bdcZsBhMapper.getBdcZsBhListByQzBh(map);
    }

    @Override
    public int getCountBdcZsBhByXh(String xh) {
        return bdcZsBhMapper.getCountBdcZsBhByXh(xh);
    }

    @Override
    public String getZsbhByDwdm(HashMap hashMap) {
        return bdcZsBhMapper.getZsbhByDwdm(hashMap);
    }


    @Override
    public String getZsBh(final String zslx, final String zsid) {
        String zsbh = "";
        String zsbhTemp = getZsbh(zslx);
        if (StringUtils.isNotBlank(zslx)) {
            HashMap map = new HashMap();
            map.put("zsbh", zsbhTemp);
            map.put("zslx", zslx);
            List<BdcZsbh> bdcZsbhList = getBdcZsBhListByBhfw(map);
            if (CollectionUtils.isNotEmpty(bdcZsbhList)) {
                BdcZsbh bdcZsbh = bdcZsbhList.get(0);
                bdcZsbh.setSyqk("3");
                bdcZsbh.setZsid(zsid);
                bdcZsbh.setLqrid(SessionUtil.getCurrentUserId());
                bdcZsbh.setLqrid(SessionUtil.getCurrentUser().getUsername());
                entityMapper.saveOrUpdate(bdcZsbh, bdcZsbh.getZsbhid());
            }
            zsbh = zsbhTemp;
        }
        return zsbh;
    }

    @Override
    public String getZsbh(final String zslx) {
        return bdcZsBhMapper.getZsbh(zslx);
    }

    @Override
    public Map getZsYjByZslx(final String zslx) {
        return bdcZsBhMapper.getZsYjByZslx(zslx);
    }

    @Override
    public String checkZsbhNew(String proid, String zslx, String zsbh, String organName, String zsid, String syr) {
        String msg = "success";
        if (StringUtils.isNotBlank(zsbh)) {
            HashMap map = new HashMap();
            map.put("zsbh", zsbh);
            map.put("zslx", zslx);
            List<BdcZsbh> bdcZsbhList = getBdcZsBhListByBhfw(map);
            if (CollectionUtils.isNotEmpty(bdcZsbhList)) {
                BdcZsbh bdcZsbh = bdcZsbhList.get(0);
                if (StringUtils.equals(bdcZsbh.getSyqk(), "6")) {
                    msg = "证书编号未被领用，请检查录入证本编号是否正确！";
                } else if (!StringUtils.equals(bdcZsbh.getLqdw(), organName)) {
                    msg = "证书编号已被其他部门领用，请检查录入证本编号是否正确！";
                } else if (StringUtils.equals(bdcZsbh.getSyqk(), Constants.BDCZSBH_SYQK_ZF)) {
                    msg = "证书已作废，请检查录入证本编号是否正确。";
                } else if (StringUtils.equals(bdcZsbh.getSyqk(), Constants.BDCZSBH_SYQK_YS) || StringUtils.equals(bdcZsbh.getSyqk(), Constants.BDCZSBH_SYQK_XH)) {
                    msg = "证书已遗失，请检查录入证本编号是否正确。";
                } else if (StringUtils.equals(bdcZsbh.getSyqk(), Constants.BDCZSBH_SYQK_YSY) || StringUtils.equals(bdcZsbh.getSyqk(), Constants.BDCZSBH_SYQK_YDZ)) {
                    msg = "证书编号已使用";
                } else if (StringUtils.equals(bdcZsbh.getSyqk(), Constants.BDCZSBH_SYQK_WLY)) {
                    bdcZsbh.setZsid(zsid);
                    bdcZsbh.setSyqk(Constants.BDCZSBH_SYQK_YSY);
                    bdcZsbh.setSyr(syr);
                    bdcZsbh.setSysj(new Date());
                    entityMapper.saveOrUpdate(bdcZsbh, bdcZsbh.getZsbhid());
                    clearZsbhData(zsbh, zsid);
                }
            } else {
                msg = "证书编号未被领用，请检查录入证本编号是否正确！";
            }

        } else {
            msg = "请填写证书编号";
        }
        return msg;
    }

    /**
     * 修改证书编号的时候将之前的zsbh改为未使用状态
     *
     * @param zsbh
     * @param zsid
     * @return
     */
    public boolean clearZsbhData(String zsbh, String zsid) {
        List<BdcZsbh> bdcZsbhList = null;
        if (StringUtils.isNotBlank(zsid)) {
            Map m = new HashMap();
            m.put("zsid", zsid);
            bdcZsbhList = getBdcZsBhListByBhfw(m);
            BdcZsbh zs = null;
            Iterator<BdcZsbh> iterator = bdcZsbhList.iterator();
            while (iterator.hasNext()) {
                zs = iterator.next();
                if (!zsbh.equals(zs.getZsbh()) && !"0".equals(zs.getSyqk()) && ("2".equals(zs.getSyqk()) || "3".equals(zs.getSyqk()))) {
                    zs.setSyqk("0");
                    zs.setSyr(null);
                    zs.setSyrid(null);
                    zs.setSysj(null);
                    zs.setZsid(null);
                    zs.setLqr(null);
                    zs.setLqrid(null);
                    bdcZsBhMapper.updateZsSyData(zs);
                }

            }
            return true;
        }
        return false;
    }

    @Override
    public String getDefaultSixNumZsBh(String zslx) {
        return bdcZsBhMapper.getDefaultSixNumZsBh(zslx);
    }

    @Override
    @Transactional
    public BdcZs creatBdcqzBh(BdcXm bdcXm, BdcZs bdcZs, int zsIndex) {
        String bdcqzh = "";
        if (bdcZs == null) {
            bdcZs = new BdcZs();
        }
        if (StringUtils.isBlank(bdcZs.getBdcqzh())) {
            BdcXtConfig bdcXtConfig = bdcXtConfigService.queryBdczsBhConfig(bdcXm);
            String nf = getBhYear(bdcXtConfig);
            String sqsjc = getProvinceShortName(bdcXtConfig);
            String szsxqc = getXzqShortName(bdcXtConfig);
            QllxVo qllxVo = qllxService.makeSureQllx(bdcXm);
            String zsFont = qllxService.makeSureBdcqzlx(qllxVo);
            //lcl 从配置文件获取新增证书类型，只针对商品房及业主共有部分首次登记流程

            if(StringUtils.equals(bdcXm.getSqlx(),Constants.SQLX_SPFGYSCDJ_DM) || StringUtils.equals(bdcXm.getSqlx(),Constants.SQLX_SPFXZBG_DM)){
                List<BdcFdcq> bdcFdcqLst = bdcFdcqService.getBdcFdcqListByProid(bdcXm.getProid());
                if(CollectionUtils.isNotEmpty(bdcFdcqLst) && StringUtils.equals(bdcFdcqLst.get(0).getFzlx(),Constants.FZLX_FZM)){
                    String zsFont1 = AppConfig.getProperty("spfscdj.zstype");
                    if(StringUtils.isNotBlank(zsFont1)) {
                        zsFont = zsFont1;
                    }
                }
            }

            if (StringUtils.isNotBlank(zsFont)) {
                HashMap map = new HashMap();
                map.put("isuse", "0");
                map.put("zstype", zsFont);
                map.put("nf", nf);
                //不动产权证号配置到各乡镇，各乡镇可能不同可能相同,就需要将该项目办理乡镇的行政代码存储到bdcZs里的dwdm
                String bdcqzhFilterZhXzdm = AppConfig.getProperty("bdcqzh.filterZh.xzdm");
                if (StringUtils.equals(bdcqzhFilterZhXzdm, "true")) {
                    map.put("dwdm", bdcXm.getSsxz());
                }
                else {
                    map.put("dwdm", bdcXm.getDwdm());
                }
                List<BdcDelZszh> bdcDelZszhList = bdcDelZszhMapper.getBdcDelZszhList(map);
                if (bdcDelZszhList != null && bdcDelZszhList.size() > 0) {
                    //取删除的证号
                    BdcDelZszh bdcDelZszh = bdcDelZszhList.get(0);
                    bdcZs.setZstype(zsFont);
                    bdcZs.setZhlsh(bdcDelZszh.getZhlsh());
                    bdcZs.setNf(bdcDelZszh.getNf());
                    bdcZs.setSqsjc(bdcDelZszh.getSqsjc());
                    bdcZs.setSzsxqc(bdcDelZszh.getSzsxqc());
                    bdcZs.setBdcqzh(bdcDelZszh.getBdcqzh());
                    bdcDelZszh.setIsuse("1");
                    entityMapper.saveOrUpdate(bdcDelZszh, bdcDelZszh.getZszhid());
                } else {
                    String lsh = "";
                    String useSequence = AppConfig.getProperty("use.sequence");
                    if (StringUtils.equals(useSequence, "true")) {
                        //根据序列来获取最大流水号
                        lsh = getMaxLshBySl(bdcXtConfig, zsFont, bdcXm);
                    }
                    else {
                        lsh = getLsh(bdcXtConfig, zsFont, zsIndex, bdcXm);
                    }

                    //各乡镇代码前缀是否插入到不动产权证号
                    String bdcqzhInsertZhXzdm = AppConfig.getProperty("bdcqzh.insertZh.xzdm");
                    if (StringUtils.equals(bdcqzhInsertZhXzdm, "true")) {
                        if (StringUtils.isNotBlank(bdcXm.getSsxz()) && bdcXm.getSsxz().length() == 9) {
                            lsh = bdcXm.getSsxz().substring(7) + lsh;
                        }
                        else {
                            lsh = "00" + lsh;
                        }
                    }
                    bdcqzh = sqsjc + Constants.BDCQ_BH_LEFT_BRACKET + nf + Constants.BDCQ_BH_RIGHT_BRACKET + szsxqc + zsFont + "第" + lsh + "号";
                    bdcZs.setZstype(zsFont);
                    bdcZs.setZhlsh(lsh);
                    bdcZs.setNf(nf);
                    bdcZs.setSqsjc(sqsjc);
                    bdcZs.setSzsxqc(szsxqc);
                    bdcZs.setBdcqzh(bdcqzh);
                }
            }
        }

        return bdcZs;
    }

    public String getMaxLshBySl(BdcXtConfig bdcXtConfig, String zsFont, BdcXm bdcXm) {

        Integer maxLsh = null;
        Integer len = 0;
        String lsh = "";
        //根据行政代码获取不动产权证的对应的序列的最大流水号
        if (bdcXm != null && StringUtils.isNotBlank(zsFont) && StringUtils.equals(zsFont, Constants.BDCQZS_BH_FONT)) {
            HashMap map = new HashMap();
            String sqZscqzLsh =Constants.BDCQZS_BH_XL;
            if (StringUtils.isNotBlank(bdcXm.getSsxz())&&bdcXm.getSsxz().length()!=6) {
                sqZscqzLsh = sqZscqzLsh + "_" + bdcXm.getSsxz();
            }
            map.put("BdcqzLsh", sqZscqzLsh);
            maxLsh = getMaxLshByXl(map);
        }  //根据行政代码获取不动产权证明的对应的序列的最大流水号
        else if (bdcXm != null && StringUtils.isNotBlank(zsFont) && StringUtils.equals(zsFont, Constants.BDCQZM_BH_FONT)) {
            HashMap map = new HashMap();
            String sqZsczmLsh = Constants.BDCQZM_BH_XL;
            if (StringUtils.isNotBlank(bdcXm.getSsxz())) {
                sqZsczmLsh = sqZsczmLsh + "_" + bdcXm.getSsxz();
            }
            map.put("BdcqzLsh", sqZsczmLsh);
            maxLsh = getMaxLshByXl(map);
        }
        if (maxLsh != null) {
            lsh = maxLsh.toString();
        }
        if (bdcXtConfig != null) {
            if (bdcXtConfig.getBdcqzhws() != null) {
                len = bdcXtConfig.getBdcqzhws();
            }
        }

        String startQh =  StringUtils.deleteWhitespace(AppConfig.getProperty("zslsh.start.qh"));
        if(StringUtils.isNotBlank(startQh)){
            int qhLength = startQh.length();
            if (lsh.length() < len) {
                if(len > qhLength) {
                    do {
                        if(lsh.length() == len-qhLength){
                            lsh = startQh + lsh;
                        }else{
                            lsh = "0" + lsh;
                        }
                    } while (lsh.length() < len);
                }
            }else{
                if(!StringUtils.equals(startQh,lsh.substring(0,qhLength))){
                    lsh = startQh + lsh.substring(qhLength,lsh.length());
                }
            }
        }else{
            if (lsh.length() < len) {
                do {
                    lsh = "0" + lsh;
                } while (lsh.length() < len);
            }
        }

        return lsh;
    }

    private Integer getMaxLshByXl(HashMap map) {
        return bdcZsMapper.getMaxLshByXl(map);
    }

    @Override
    public String getBhYear(BdcXtConfig bdcXtConfig) {
        String year = "";
        if (bdcXtConfig != null) {
            year = bdcXtConfig.getNf();
        }
        return year;
    }

    @Override
    public String getXzqShortName(BdcXtConfig bdcXtConfig) {
        String xzq = "";
        if (bdcXtConfig != null) {
            xzq = bdcXtConfig.getSzsxqc();
        }
        return xzq;
    }
    @Override
    public String getProvinceShortName(BdcXtConfig bdcXtConfig) {
        String provinceShortName = "";
        if (bdcXtConfig != null) {
            provinceShortName = bdcXtConfig.getSqsjc();
        }
        return provinceShortName;
    }

    @Override
    @Transactional(readOnly = true)
    public String getLsh(BdcXtConfig bdcXtConfig, String zsFont, int zsIndex,BdcXm bdcXm) {

        String lsh = "";
        Integer len = 0;
        if (bdcXtConfig != null) {
            len = bdcXtConfig.getBdcqzhws();
        }

        //证号流水号开头区号
        String startQh =  StringUtils.deleteWhitespace(AppConfig.getProperty("zslsh.start.qh"));

        //zdd 获取当前最大流水号        、
        //sc 根据当前年份过滤
        HashMap map = new HashMap();
        map.put("zstype", zsFont);
        map.put("nf", CalendarUtil.getCurrYear());
        map.put("dwdm",bdcXm.getDwdm());
        if(StringUtils.isNotBlank(startQh)) {
            map.put("startQh", startQh);
        }
        Integer maxLsh = bdcZsService.getMaxLsh(map);
        if (maxLsh == null) {
            maxLsh = 0;
        }
        maxLsh = ++maxLsh;
        maxLsh = maxLsh + zsIndex;
        lsh = maxLsh.toString();


        if(StringUtils.isNotBlank(startQh)){
            int qhLength = startQh.length();
            if(lsh.indexOf(startQh) == -1) {
                if (lsh.length() < len) {
                    if(len > qhLength) {
                        do {
                            lsh = "0" + lsh;
                        } while (lsh.length() < len-qhLength);
                        lsh = startQh + lsh;
                    }
                }else{
                    if(!StringUtils.equals(startQh,lsh.substring(0,qhLength))){
                        lsh = startQh + lsh.substring(qhLength,lsh.length());
                    }
                }
            }else{
                lsh = lsh.substring(qhLength,lsh.length());
                if (lsh.length() < len-qhLength) {
                    do {
                        lsh = "0" + lsh;
                    } while (lsh.length() < len-qhLength);
                }
                lsh = startQh + lsh;
            }

        }else{
            if (lsh.length() < len) {
                do {
                    lsh = "0" + lsh;
                } while (lsh.length() < len);
            }
        }

        return lsh;
    }


    @Override
    public void changeZsbhSyqk(BdcXm bdcXm) {
        //查封和注销不生成证书
        if (bdcXm != null && !StringUtils.equals(bdcXm.getDjlx(), Constants.DJLX_ZXDJ_DM) && !StringUtils.equals(bdcXm.getDjlx(), Constants.DJLX_CFDJ_DM)) {
            List<BdcZs> zsList = bdcZsService.queryBdcZsByProid(bdcXm.getProid());
            if(CollectionUtils.isNotEmpty(zsList)){
                for(BdcZs bdcZs:zsList) {
                    HashMap map = new HashMap();
                    map.put("zsid", bdcZs.getZsid());
                    map.put("syqk", Constants.BDCZSBH_SYQK_YSY);
                    List<BdcZsbh> bdcZsbhList = getBdcZsBhListByBhfw(map);
                    if (CollectionUtils.isNotEmpty(bdcZsbhList)) {
                        for (BdcZsbh bdcZsbh : bdcZsbhList) {
                            bdcZsbh.setSyqk(Constants.BDCZSBH_SYQK_YDZ);
                            entityMapper.saveOrUpdate(bdcZsbh, bdcZsbh.getZsbhid());
                        }
                    }
                }
            }
        }
    }


}
