package cn.gtmap.estateplat.config.web.ztxx;

/*
 * @author <a href="mailto:huangzijian@gtmap.cn">huangzijian</a>
 * @version 1.0, 2017/11/21
 * @description
 */

import cn.gtmap.estateplat.config.service.ztxx.BdcCxBdcdyZtService;
import cn.gtmap.estateplat.config.utils.Constants;
import cn.gtmap.estateplat.config.utils.RuleThread;
import cn.gtmap.estateplat.config.web.main.BaseController;
import cn.gtmap.estateplat.core.support.mybatis.page.repository.Repo;
import cn.gtmap.estateplat.model.config.BdcCxBdcdyZt;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping(value = "bdcdyZt", method = RequestMethod.GET)
public class BdcBdcdyQlztGlController extends BaseController {
    @Autowired
    private Repo repository;
    @Autowired
    private BdcCxBdcdyZtService bdcCxBdcdyZt;
    /**
     * 线程池管理实例
     */
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @RequestMapping(value = "")
    public String index(Model model) {
        return "value/bdcBdcdyQlztGl";
    }

    @ResponseBody
    @RequestMapping(value = "getBdcZtPagesJson", method = RequestMethod.GET)
    public Object getBdcZtPagesJson(Pageable pageable, String bdcdyh) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (StringUtils.isNotBlank(bdcdyh))
            map.put("bdcdyh", bdcdyh.trim());
        //对登记事由处理
        return repository.selectPaging("getBdcZtByPage", map, pageable);
    }

    /**
     * @Author:<a href="mailto:huangzijian@gtmap.cn">huangzijian</a>
     * @Description:验证是否做过不动产单元状态转换操作
     * @Date 9:48 2017/12/20
     */
    @ResponseBody
    @RequestMapping(value = "valiteBdcdy", method = RequestMethod.POST)
    public HashMap valiteBdcdy() {
        HashMap map = new HashMap();
        String result = "false";
        try {
            map.put("msg", "true");
            List<BdcCxBdcdyZt> mapList = bdcCxBdcdyZt.getBdcCxBdcdyZtList(map);
            if (null != mapList && CollectionUtils.isNotEmpty(mapList)) {
                result = "true";
            }
        } catch (Exception e) {
            result = "false";
            LoggerFactory.getLogger(getClass()).error(Constants.ERROR_IN_FUNCTION, e);
        } finally {
            map.put("result", result);
        }
        return map;
    }

    /**
     * @Author:<a href="mailto:huangzijian@gtmap.cn">huangzijian</a>
     * @Description:进行不动产单元状态转换
     * @Date 9:49 2017/12/20
     */
    @ResponseBody
    @RequestMapping(value = "lsDate", method = RequestMethod.POST)
    public HashMap lsDate() {
        HashMap map = new HashMap();
        String result = "fail";
        try {
            String tdfwResult = "fail";
            String tdResult = "fail";
            //处理土地房屋类型的不动产单元状态
            tdfwResult = initBdcdyhByRule(Constants.BDCLX_TDFW);
            //处理土地类型的不动产单元状态
            tdResult = initBdcdyhByRule(Constants.BDCLX_TD);
            if (tdfwResult.equals("success") && tdResult.equals("success")) {
                result = "success";
            }
        } catch (Exception e) {
            result = "fail";
            LoggerFactory.getLogger(getClass()).error(Constants.ERROR_IN_FUNCTION, e);
        } finally {
            map.put("result", result);
        }
        return map;
    }

    public String initBdcdyhByRule(String bdclx) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String result = "faile";
        Integer bdcdyhCount = bdcCxBdcdyZt.getBdcdyhCount(bdclx);
        //超出该数据量大小则需要开始线程处理
        double limit = 50000;
        if (bdcdyhCount > limit) {
            System.out.println("不动产单元更新开始时间：" + df.format(System.currentTimeMillis()));
            //设置每个线程执行的数据量
            double limitcount = 5000;
            double num = Math.ceil(bdcdyhCount.doubleValue() / limitcount);
            for (int k = 0; k < num; k++) {
                double begin = k * limitcount + 1;
                double over = begin + limitcount - 1;
                if (k == num - 1) {
                    over = bdcdyhCount;
                }
                Map bdcdyhMap = new ExtendedProperties();
                bdcdyhMap.put("begin", begin);
                bdcdyhMap.put("over", over);
                bdcdyhMap.put("bdclx", bdclx);
                bdcdyhMap.put("msg", "true");
                List<String> bdcdyhList = bdcCxBdcdyZt.getBdcdyh(bdcdyhMap);
                while (true) {
                    try {
                        int count = taskExecutor.getActiveCount();
                        if (count < taskExecutor.getMaxPoolSize()) {
                            RuleThread ruleThread = new RuleThread();
                            ruleThread.setName("初始化不动产单元号" + bdclx + "线程" + k);
                            ruleThread.setBdcdyhList(bdcdyhList);
                            ruleThread.setBdclx(bdclx);
                            ruleThread.setBdcCxBdcdyZtService(bdcCxBdcdyZt);
                            taskExecutor.execute(ruleThread);
                            break;
                        }
                        Thread.sleep(1000 * 60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            result = "success";
            shutDownThread();
            System.out.println("不动产单更新结束时间：" + df.format(System.currentTimeMillis()));
        } else {
            Map bdcdyhMap = new ExtendedProperties();
            bdcdyhMap.put("bdclx", bdclx);
            bdcdyhMap.put("msg", "true");
            List<String> bdcdyhList = bdcCxBdcdyZt.getBdcdyh(bdcdyhMap);
            if (null != bdcdyhList && CollectionUtils.isNotEmpty(bdcdyhList)) {
                result = bdcCxBdcdyZt.updateBdcdyZtByBdcdyh(bdcdyhList, bdclx);
            }
        }
        return result;
    }

    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) {
                    e.printStackTrace();
                }
            }
        }
    }
}
