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

import cn.gtmap.estateplat.config.core.service.BdcXtLimitfieldService;
import cn.gtmap.estateplat.config.core.service.BdcXtQlqtzkConfigService;
import cn.gtmap.estateplat.config.core.service.BdcZsService;
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.BdcBdcdy;
import cn.gtmap.estateplat.model.server.core.BdcXm;
import cn.gtmap.estateplat.model.server.core.BdcXtQlqtzkConfig;
import cn.gtmap.estateplat.model.server.core.BdcZs;
import cn.gtmap.estateplat.utils.CalendarUtil;
import cn.gtmap.estateplat.utils.CommonUtil;
import com.gtis.config.AppConfig;
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 java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @version 1.0, 2017/6/27.
 * @auto <a href="mailto:zhouwanqing@gtmap.cn">zhouwanqing</a>
 * @description
 */
@Service
public class BdcXtQlqtzkConfigServiceImpl implements BdcXtQlqtzkConfigService {
    @Autowired
    EntityMapper entityMapper;
    @Autowired
    private BdcXtLimitfieldService bdcXtLimitfieldService;
    @Autowired
    private BdcZsService bdcZsService;


    @Override
    public List<BdcXtQlqtzkConfig> getQlqtzk(BdcXtQlqtzkConfig bdcXtQlqtzkConfig) {
        List<BdcXtQlqtzkConfig> list = null;
        if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getSqlxdm())) {
            Example example = new Example(bdcXtQlqtzkConfig.getClass());
            Example.Criteria criteria = example.createCriteria().andEqualTo("sqlxdm", bdcXtQlqtzkConfig.getSqlxdm());
            /**
             * @author <a href="mailto:sunchao@gtmap.cn">sunchao</a>
             * @description 查询时不需要根据权利类型子类型查询
             */
            //zhouwanqing 因权利类型有可能都是空，则必需准确定位一个
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getQllxzlx())) {
                criteria.andEqualTo("qllxzlx", bdcXtQlqtzkConfig.getQllxzlx());
            } else {
                criteria.andIsNull("qllxzlx");
            }
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getQllxdm())) {
                criteria.andEqualTo("qllxdm", bdcXtQlqtzkConfig.getQllxdm());
            } else {
                criteria.andIsNull("qllxdm");
            }
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getDjzxdm())) {
                criteria.andEqualTo("djzxdm", bdcXtQlqtzkConfig.getDjzxdm());
            } else {
                criteria.andIsNull("djzxdm");
            }
            if (CollectionUtils.isNotEmpty(example.getOredCriteria()) && CollectionUtils.isNotEmpty(example.getOredCriteria().get(0).getAllCriteria())) {
                list = entityMapper.selectByExample(example);
            }
        }
        if (list == null) {
            list = new ArrayList<BdcXtQlqtzkConfig>();
        }
        return list;
    }

    @Override
    public void saveOrUpdateQlqtzk(BdcXtQlqtzkConfig bdcXtQlqtzkConfig) throws Exception {
        if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getSqlxdm())) {
            Example example = new Example(bdcXtQlqtzkConfig.getClass());
            Example.Criteria criteria = example.createCriteria().andEqualTo("sqlxdm", bdcXtQlqtzkConfig.getSqlxdm());
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getQllxdm())) {
                criteria.andEqualTo("qllxdm", bdcXtQlqtzkConfig.getQllxdm());
            } else {
                criteria.andIsNull("qllxdm");
            }
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getQllxzlx())) {
                criteria.andEqualTo("qllxzlx", bdcXtQlqtzkConfig.getQllxzlx());
            } else {
                criteria.andIsNull("qllxzlx");
            }
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getDjzxdm())) {
                criteria.andEqualTo("djzxdm", bdcXtQlqtzkConfig.getDjzxdm());
            } else {
                criteria.andIsNull("djzxdm");
            }
            if (CollectionUtils.isNotEmpty(example.getOredCriteria()) && CollectionUtils.isNotEmpty(example.getOredCriteria().get(0).getAllCriteria())) {
                List<BdcXtQlqtzkConfig> newQlqtzk = entityMapper.selectByExample(example);
                if (newQlqtzk != null && newQlqtzk.size() > 0) {
                    entityMapper.deleteByExample(example);
                }
            }
            entityMapper.insertSelective(bdcXtQlqtzkConfig);
        }
    }

    @Override
    public void deleteQlqtzk(BdcXtQlqtzkConfig bdcXtQlqtzkConfig) throws Exception {
        if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getSqlxdm())) {
            Example example = new Example(bdcXtQlqtzkConfig.getClass());
            Example.Criteria criteria = example.createCriteria().andEqualTo("sqlxdm", bdcXtQlqtzkConfig.getSqlxdm());
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getQllxdm())) {
                criteria.andEqualTo("qllxdm", bdcXtQlqtzkConfig.getQllxdm());
            } else {
                criteria.andIsNull("qllxdm");
            }
            if (StringUtils.isNotBlank(bdcXtQlqtzkConfig.getQllxzlx())) {
                criteria.andEqualTo("qllxzlx", bdcXtQlqtzkConfig.getQllxzlx());
            } else {
                criteria.andIsNull("qllxzlx");
            }
            if (CollectionUtils.isNotEmpty(example.getOredCriteria()) && CollectionUtils.isNotEmpty(example.getOredCriteria().get(0).getAllCriteria())) {
                entityMapper.deleteByExample(example);
            }

        }
    }

    @Override
    public BdcXtQlqtzkConfig getQlqtzkId(String id) {
        BdcXtQlqtzkConfig bdcXtQlqtzkConfig = entityMapper.selectByPrimaryKey(BdcXtQlqtzkConfig.class, id);
        return bdcXtQlqtzkConfig;
    }

    @Override
    public String replaceMb(String mb, String sql, BdcXm bdcXm, BdcBdcdy bdcBdcdy) {
        String newMb = "";
        String mbLastTemp = "";
        String lastMb = mb;
        Boolean sfxsYbdcqzh = true;
        String dwdm = AppConfig.getProperty("dwdm");
        if (bdcXm != null && bdcBdcdy != null) {
            List<BdcZs> bdcZsList = bdcZsService.getBdcZsByProid(bdcXm.getProid());
            if (CollectionUtils.isEmpty(bdcZsList) && dwdm.equals("320900")) {
                sfxsYbdcqzh = false;//还未生成证书时不显示原不动产权证号
            }
        }
        if (StringUtils.isNotBlank(mb) && StringUtils.isNotBlank(sql) && bdcXm != null && bdcBdcdy != null) {
            String[] dbs = sql.split("；|;");
            //将数据源用;隔开成多条语句
            for (int i = 0; i < dbs.length; i++) {
                //不分大小写 替换项目id
                List<Map> list = bdcXtLimitfieldService.runSql(dbs[i].replaceAll("(?i)@proid", "'" + bdcXm.getProid() + "'").replaceAll("(?i)@bdcdyh", "'" + bdcBdcdy.getBdcdyh() + "'").replaceAll("(?i)@wiid", "'" + bdcXm.getWiid() + "'"));
                if (list != null && list.size() == 1) {
                    Map map = list.get(0);
                    Iterator j = list.get(0).keySet().iterator();
                    while (j.hasNext()) {
                        Object o = j.next();
                        String key = o.toString();
                        if (map.get(key) != null) {
                            //对时间和数值的一些处理
                            if (map.get(key) instanceof Date) {
                                mb = mb.replaceAll("(?i)@" + key, CalendarUtil.sdf_China.format((Date) map.get(key)));
                            }
                            else if (map.get(key) instanceof BigDecimal) {
                                if (!"ZCS".equals(key) && !"SZC".equals(key)) {

                                    DecimalFormat df = new DecimalFormat("##############0.00");
                                    String tempValue = df.format((((BigDecimal) map.get(key))).doubleValue());
                                    mb = mb.replaceAll("(?i)@" + key, tempValue);
                                } else {
                                    mb = mb.replaceAll("(?i)@" + key, CommonUtil.formatTwoNumber((((BigDecimal) map.get(key))).doubleValue()).toString().split("\\.")[0]);
                                }
                            } else if ("YBDCQZH".equals(key) && !sfxsYbdcqzh) {
                                String[] mbArray = mb.split("\\n");
                                if (mbArray.length > 0) {
                                    mb = "";
                                    for (String mbTemp : mbArray) {
                                        if (!(StringUtils.indexOf(StringUtils.upperCase(mbTemp), key) > -1)) {
                                            mb += mbTemp + "\n";
                                        }
                                    }
                                }
                            } else {
                                //不分大小写
                                mb = mb.replaceAll("(?i)@" + key, map.get(key).toString());
                            }
                        } else {
                            /**
                             * @author <a href="mailto:sunchao@gtmap.cn">sunchao</a>
                             * @description 如果查询不出结果则不显示这条记录
                             */
                            String[] mbArray = mb.split("\\n");
                            if (mbArray.length > 0) {
                                mb = "";
                                for (String mbTemp : mbArray) {
                                    if (!(StringUtils.indexOf(StringUtils.upperCase(mbTemp), key) > -1)) {
                                        mb += mbTemp + "\n";
                                    }
                                }
                            }
                        }
                    }
                } else {
                    //针对项目内多幢的会有多个list
                    for (int a = 0; a <= list.size(); a++) {
                        if (a >= list.size()) {
                            break;
                        }
                        if (a > 0) {
                            mb = lastMb;
                        }
                        Map map = list.get(a);
                        Iterator j = list.get(a).keySet().iterator();
                        while (j.hasNext()) {
                            Object o = j.next();
                            String key = o.toString();
                            if (map.get(key) != null) {
                                //对时间和数值的一些处理
                                if (map.get(key) instanceof Date) {
                                    mb = mb.replaceAll("(?i)@" + key, CalendarUtil.sdf_China.format((Date) map.get(key)));
                                }
                                else if (map.get(key) instanceof BigDecimal) {
                                    if (!"ZCS".equals(key) && !"SZC".equals(key)) {

                                        DecimalFormat df = new DecimalFormat("##############0.00");
                                        String tempValue = df.format((((BigDecimal) map.get(key))).doubleValue());
                                        mb = mb.replaceAll("(?i)@" + key, tempValue);
                                    } else {
                                        mb = mb.replaceAll("(?i)@" + key, CommonUtil.formatTwoNumber((((BigDecimal) map.get(key))).doubleValue()).toString().split("\\.")[0]);
                                    }
                                } else {
                                    //不分大小写
                                    mb = mb.replaceAll("(?i)@" + key, map.get(key).toString());
                                }
                            } else {
                                /**
                                 * @author <a href="mailto:sunchao@gtmap.cn">sunchao</a>
                                 * @description 如果查询不出结果则不显示这条记录
                                 */
                                String[] mbArray = mb.split("\\n");
                                if (mbArray.length > 0) {
                                    mb = "";
                                    for (String mbTemp : mbArray) {
                                        if (!(org.apache.commons.lang.StringUtils.indexOf(org.apache.commons.lang.StringUtils.upperCase(mbTemp), key) > -1)) {
                                            mb += mbTemp + "\n";
                                        }
                                    }
                                }
                            }
                        }
                        mbLastTemp += mb + "\n";
                    }
                    if (StringUtils.isNotBlank(mbLastTemp)) {
                        mb = mbLastTemp;
                    }
                }
            }

            /**
             * @author <a href="mailto:liujie@gtmap.cn">liujie</a>
             * @description sql查询结果不存在则不显示该配置模板
             */
            String[] mbArray = mb.split("\\n");
            if (mbArray.length > 0) {
                mb = "";
                for (String mbTemp : mbArray) {
                    if (mbTemp.indexOf("@") == -1) {
                        mb += mbTemp + "\n";
                    }
                }
            }
            newMb = mb;
        }
        return newMb;
    }
}
