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

import cn.gtmap.estateplat.config.core.mapper.config.BdcCxZszmZtMapper;
import cn.gtmap.estateplat.config.core.mapper.config.GdFwMapper;
import cn.gtmap.estateplat.config.core.mapper.config.GdTdMapper;
import cn.gtmap.estateplat.config.core.mapper.config.GdXmMapper;
import cn.gtmap.estateplat.config.service.ztxx.BdcCxBdcdyZtService;
import cn.gtmap.estateplat.config.service.ztxx.BdcCxZszmZtService;
import cn.gtmap.estateplat.config.core.service.BdcZsService;
import cn.gtmap.estateplat.config.core.service.BdcdyService;
import cn.gtmap.estateplat.config.service.ztxx.ZszmZtService;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.config.utils.RuleThread;
import cn.gtmap.estateplat.core.support.mybatis.mapper.EntityMapper;
import cn.gtmap.estateplat.model.server.core.BdcCxZszmZt;
import cn.gtmap.estateplat.model.server.core.BdcZs;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * @author <a href="mailto:juyulin@gtmap.cn">juyulin</a>
 * @version 1.0, 2017/11/29
 * @description 不动产证书证明状态管理服务
 */
@Service
public class ZszmZtServiceImpl implements ZszmZtService {
    @Autowired
    BdcCxZszmZtMapper bdcCxZszmZtMapper;
    @Autowired
    BdcZsService bdcZsService;
    @Autowired
    EntityMapper entityMapper;
    @Autowired
    GdXmMapper gdXmMapper;
    @Autowired
    BdcdyService bdcdyService;
    @Autowired
    BdcCxBdcdyZtService bdcCxBdcdyZtService;
    @Autowired
    GdTdMapper gdTdMapper;
    @Autowired
    GdFwMapper gdFwMapper;
    @Autowired
    BdcCxZszmZtService bdcCxZszmZtService;
    /**
     * 线程池管理实例
     */
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    protected final Log logger = LogFactory.getLog(getClass());

    @Override
    public String initBdcCxZszmZt() {
        String msg = "fail";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("证书证明初始化开始时间："+df.format(System.currentTimeMillis()));
        //jyl 清空表
        bdcCxZszmZtMapper.deleteBdcCxZszmZt();
        //jyl 初始化不动产的证书数据
        initBdcZs();
        //jyl 初始化过渡证书数据
        initGdZs();
        //hzj 初始化zszm权属状态和权利状态
        msg=updateQlzt();
        System.out.println("证书证明初始化结束时间："+df.format(System.currentTimeMillis()));
        return msg;
    }

    public String updateQlzt() {
        String msg = "fail";
        //jyl 获取要更新的证书信息
        HashMap param = new HashMap();
        param.put("gxqlzt", "true");
        //计算bdccxzszmzt表中的数据量
        Integer bdcCxZszmZtCount=bdcCxZszmZtMapper.getBdcCxZszmZtNum(param);
        //超出该数据量大小则需要开始线程处理
        double limit=50000;
        if(bdcCxZszmZtCount > limit){
            //设置每个线程执行的数据量
            double limitcount=10000;
            double num = Math.ceil(bdcCxZszmZtCount.doubleValue() / limitcount);
            for (int k = 0; k < num; k++) {
                double begin = k * limitcount+1 ;
                double over = begin + limitcount-1;
                if (k == (int)num - 1) {
                    over = bdcCxZszmZtCount;
                }
                param.put("begin", begin);
                param.put("over", over);
                List<BdcCxZszmZt> bdcCxZszmZts = bdcCxZszmZtMapper.listBdcCxZszmZt(param);
                while (true) {
                    try {
                        int count = taskExecutor.getActiveCount();
                        if (count < taskExecutor.getMaxPoolSize()) {
                            RuleThread ruleThread = new RuleThread();
                            ruleThread.setName("更新权利状态线程" +k);
                            ruleThread.setBdcCxZszmZts(bdcCxZszmZts);
                            ruleThread.setBdcCxZszmZtService(bdcCxZszmZtService);
                            taskExecutor.execute(ruleThread);
                            break;
                        }
                        Thread.sleep(1000 * 60);
                    } catch (InterruptedException e) {
                        LoggerFactory.getLogger(getClass()).error(Constants.ERROR_IN_FUNCTION,e);
                    }
                }
            }
            msg="success";
            shutDownThread();
        }else{
            List<BdcCxZszmZt> bdcCxZszmZts = bdcCxZszmZtMapper.listBdcCxZszmZt(param);
            if (CollectionUtils.isNotEmpty(bdcCxZszmZts)) {
                for (BdcCxZszmZt bdcCxZszmZt : bdcCxZszmZts) {
                    if (StringUtils.isNotBlank(bdcCxZszmZt.getCqzh()) && StringUtils.isNotBlank(bdcCxZszmZt.getSjly())) {
                        bdcCxZszmZtService.updateZszmZtByCqzh(bdcCxZszmZt);
                    }
                }
                msg="success";
            }
        }
        return msg;
    }


    /**
     * @return 返回信息
     * @author <a href="mailto:juyulin@gtmap.cn">juyulin</a>
     * @version
     * @description 初始化不动产的证书数据
     */
    private String initBdcZs() {
        String msg = "fail";
        //去取不动产证书的个数
        Integer bdczsNum = bdcZsService.getBdczsCount();
        //超出该数据量大小则需要开始线程处理
        double limit=50000;
        if (bdczsNum > limit) {
            //设置每个线程执行的数据量
            double limitcount=10000;
            double num = Math.ceil(bdczsNum.doubleValue() / limitcount);
            for (int k = 0; k < num; k++) {
                double begin = k * limitcount+1 ;
                double over = begin + limitcount-1;
                if (k == (int)num - 1) {
                    over = bdczsNum;
                }
                HashMap map = new HashMap();
                map.put("begin", begin);
                map.put("over", over);
                List<BdcZs> bdcZsList = bdcZsService.listBdcZsxx(map);
                while (true) {
                    try {
                        int count = taskExecutor.getActiveCount();
                        if (count < taskExecutor.getMaxPoolSize()) {
                            RuleThread ruleThread = new RuleThread();
                            ruleThread.setName("初始化不动产证书线程" +k);
                            ruleThread.setBdcZsList(bdcZsList);
                            ruleThread.setBdcCxZszmZtService(bdcCxZszmZtService);
                            taskExecutor.execute(ruleThread);
                            break;
                        }
                        Thread.sleep(1000 * 60);
                    } catch (InterruptedException e) {
                        LoggerFactory.getLogger(getClass()).error(Constants.ERROR_IN_FUNCTION,e);
                    }
                }
            }
            msg="success";
            shutDownThread();
        } else {
            List<BdcZs> bdcZsList = bdcZsService.listBdcZsxx(new HashMap());
            bdcCxZszmZtService.initBdcZs(bdcZsList);
            msg="success";
        }
        return msg;
    }

    /**
     * @return 返回信息
     * @author <a href="mailto:juyulin@gtmap.cn">juyulin</a>
     * @version
     * @description 初始化过渡证书数据
     */
    private String initGdZs() {
        String msg = "fail";
        //去取过渡证书的个数
        Integer gdzsNum = gdXmMapper.listGdZsxxsCount();
        //超出该数据量大小则需要开始线程处理
        double limit=50000;
        if(gdzsNum > limit){
            //设置每个线程执行的数据量
            double limitcount=10000;
            double num = Math.ceil(gdzsNum.doubleValue() / limitcount);
            for (int k = 0; k < num; k++) {
                double begin = k * limitcount+1 ;
                double over = begin + (limitcount-1);
                if (k == (int)num - 1) {
                    over = gdzsNum;
                }
                HashMap map = new HashMap();
                map.put("begin", begin);
                map.put("over", over);
                List<Map> gdZsList = gdXmMapper.listGdZsxx(map);
                while (true) {
                    try {
                        int count = taskExecutor.getActiveCount();
                        if (count < taskExecutor.getMaxPoolSize()) {
                            RuleThread ruleThread = new RuleThread();
                            ruleThread.setName("初始化过渡证书线程" +k);
                            ruleThread.setGdZsList(gdZsList);
                            ruleThread.setBdcCxZszmZtService(bdcCxZszmZtService);
                            taskExecutor.execute(ruleThread);
                            break;
                        }
                        Thread.sleep(1000 * 60);
                    } catch (InterruptedException e) {
                        LoggerFactory.getLogger(getClass()).error(Constants.ERROR_IN_FUNCTION,e);
                    }
                }
            }
            msg="success";
            shutDownThread();
        }else{
            List<Map> gdZsList = gdXmMapper.listGdZsxx(new HashMap());
            bdcCxZszmZtService.initGdZs(gdZsList);
            msg="success";
        }
        return msg;
    }

    private void shutDownThread() {
        while (true) {
            int count = taskExecutor.getActiveCount();
            if (count == 0) {
                taskExecutor.shutdown();
                logger.info("线程池断开连接。。。");
                break;
            } else {
                logger.info("线程池尚在工作中，当前触发" + count + "个线程");
                try {
                    Thread.sleep(1000 * 60);
                } catch (InterruptedException e) {
                    LoggerFactory.getLogger(getClass()).error(Constants.ERROR_IN_FUNCTION,e);
                }
            }
        }
    }
}
