package com.chinaweal.aiccs.aiccs.statistic.schedule;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.AbnSerSmsLog;
import com.chinaweal.aiccs.aiccs.abnormal.entity.TSAbnList;
import com.chinaweal.aiccs.aiccs.abnormal.service.AbnSerSmsLogService;
import com.chinaweal.aiccs.aiccs.abnormal.service.TSAbnListService;
import com.chinaweal.aiccs.aiccs.seriousillegal.service.TSSerIllegalListService;
import com.chinaweal.aiccs.aiccs.statistic.entity.StatisticsResult;
import com.chinaweal.aiccs.aiccs.statistic.service.IStatisticsResultService;
import com.chinaweal.aiccs.aiccs.test.TestController;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.door.entity.TUserportal;
import com.chinaweal.aiccs.outside.dto.LangChaoTokenDto;
import com.chinaweal.aiccs.outside.service.SMSServiceImpl;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.dtflys.forest.http.ForestResponse;
import com.esms.common.entity.GsmsResponse;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author xjy
 * @date 2022-08-05-10:06
 */
@Configuration
public class StatisticScheduled {
    @Autowired
    private IStatisticsResultService statisticsResultService;
    @Autowired
    private TSAbnListService abnListService;
    @Resource
    private AbnSerSmsLogService abnSerSmsLogService;
    @Resource
    private SMSServiceImpl smsService;
    @Resource
    private TestController testController;

    /**
     * 定时统计所有区域的经营异常
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticAllRegionTsabnlist}")
    public void staticAllRegionTsabnlist() {
        //展示全市各区的经营异常主体情况
        List<Map<String, String>> abnRegionList = statisticsResultService.staticAllRegionTsabnlist();
        List<Map<String, String>> list = new ArrayList<>();
        int n = 0;
        int k = 0;
        for (int i = 0; i < abnRegionList.size(); i++) {
            Map<String, String> m = abnRegionList.get(i);
            if (m.containsKey("region") && m.get("region") != null) {
                if (m.get("region").equals("440110")) {
                    n = i;
                    continue;
                }
                if (m.get("region").equals("440115")) {
                    k = i;
                    continue;
                }
                Map<String, String> map = m;
                map.put("region", Constant.NM_LOC_REGION_CODE.get(m.get("region")));
                list.add(map);
            }
        }
        Map mapNS = new HashMap<>();
        mapNS.put("region", Constant.NM_LOC_REGION_CODE.get("440110"));
        mapNS.put("num", Integer.parseInt(abnRegionList.get(n).get("num")) + Integer.parseInt(abnRegionList.get(k).get("num")));
        list.add(0, mapNS);

        StatisticsResult sResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_abn"));
        sResult.setDataJson(JSON.toJSONString(list));
        statisticsResultService.updateById(sResult);
    }

    /**
     * 定时按年统计全市
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticAbnByYear}")
    public void staticAbnByYear() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> abnYearList = statisticsResultService.staticAbnByYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_abn"));
        yResult.setDataJson(JSON.toJSONString(abnYearList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时按月统计全市
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticAbnByMonth}")
    public void staticAbnByMonth() {
        //<!--    按月统计全市-->
        List<Map<String, Integer>> abnMonthList = statisticsResultService.staticAbnByMonth();
        StatisticsResult mResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "month_abn"));
        mResult.setDataJson(JSON.toJSONString(abnMonthList));
        statisticsResultService.updateById(mResult);
    }

    /**
     * 定时按周统计全市
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticAbnByWeek}")
    public void staticAbnByWeek() {
        //<!--    按周统计全市-->
        List<Map<String, Integer>> abnWeekList = statisticsResultService.staticAbnByWeek();
        List<Integer> r = new ArrayList<>(10);
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);//设置星期一为一周开始的第一天
        calendar.setTimeInMillis(System.currentTimeMillis());//获得当前的时间戳
        int weekYear = calendar.get(Calendar.YEAR);//获得当前的年
        int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR) - 1;//获得当前日期属于今年的第几周
        int w = weekYear * 100 + weekOfYear;
        int dw = 0;
        for (Map map : abnWeekList) {
            int week = Integer.parseInt(map.get("weeks").toString());
            int value = Integer.parseInt(map.get("num").toString());
            while (dw < 10) {
                if (w - week == 0) {
                    r.add(value);
                    w--;
                    dw++;
                    break;
                } else {
                    r.add(0);
                }
                w--;
                dw++;
            }
            if (dw == 10) break;
        }
        StatisticsResult wResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "week_abn"));
        wResult.setDataJson(JSON.toJSONString(r));
        statisticsResultService.updateById(wResult);
    }

    /**
     * 定时经营异常列入统计全市
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticAbnByIn}")
    public void staticAbnByIn() {
        //<!--    经营异常列入统计全市-->
        List<Map<String, String>> abnInList = statisticsResultService.staticAbnByIn();

        QueryWrapper<TSAbnList> abnWrappper = new QueryWrapper<>();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().isNotNull(TSAbnList::getEnttype);
        abnWrappper.select("DISTINCT PRIPID");
        int sum = abnListService.count(abnWrappper);

        abnWrappper.clear();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().eq(TSAbnList::getEnttype, "9910");
        abnWrappper.select("DISTINCT PRIPID");
        int individualSum = abnListService.count(abnWrappper);

        abnWrappper.clear();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().in(TSAbnList::getEnttype, "9100", "9200");
        abnWrappper.select("DISTINCT PRIPID");
        int farmerSum = abnListService.count(abnWrappper);

        abnWrappper.clear();
        abnWrappper.lambda().isNotNull(TSAbnList::getSpecause);
        abnWrappper.lambda().notIn(TSAbnList::getEnttype, "9100", "9200", "9910");
        abnWrappper.select("DISTINCT PRIPID");
        int companySum = abnListService.count(abnWrappper);

        Map<String, String> sumMap = new HashMap<>();
        sumMap.put("sum", sum + "");
        sumMap.put("individualSum", individualSum + "");
        sumMap.put("farmerSum", farmerSum + "");
        sumMap.put("companySum", companySum + "");

        abnInList.add(0, sumMap);

        StatisticsResult inResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "in_abn"));
        inResult.setDataJson(JSON.toJSONString(abnInList));
        statisticsResultService.updateById(inResult);
    }

    /**
     * 定时经营异常移出统计全市
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticAbnByOut}")
    public void staticAbnByOut() {
        //<!--    经营异常移出统计全市-->
        List<Map<String, Integer>> abnOutList = statisticsResultService.staticAbnByOut();
        StatisticsResult outResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "out_abn"));
        outResult.setDataJson(JSON.toJSONString(abnOutList));
        statisticsResultService.updateById(outResult);
    }

    /**
     * 定时全市各区的严重违法主体情况
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticAllRegionTsserill}")
    public void staticAllRegionTsserill() {
        //全市各区的严重违法主体情况
        List<Map<String, String>> illRegionList = statisticsResultService.staticAllRegionTsserill();
        List<Map<String, String>> list = new ArrayList<>();
        int n = 0;
        int k = 0;
        for (int i = 0; i < illRegionList.size(); i++) {
            Map<String, String> m = illRegionList.get(i);
            if (m.containsKey("region") && m.get("region") != null) {
                if (m.get("region").equals("440110")) {
                    n = i;
                    continue;
                }
                if (m.get("region").equals("440115")) {
                    k = i;
                    continue;
                }
                Map<String, String> map = m;
                map.put("region", Constant.NM_LOC_REGION_CODE.get(m.get("region")));
                list.add(map);
            }
        }
        Map mapNS = new HashMap<>();
        mapNS.put("region", Constant.NM_LOC_REGION_CODE.get("440110"));
        mapNS.put("num", Integer.parseInt(illRegionList.get(n).get("num")) + Integer.parseInt(illRegionList.get(k).get("num")));
        list.add(0, mapNS);

        StatisticsResult regionResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_ill"));
        regionResult.setDataJson(JSON.toJSONString(list));
        statisticsResultService.updateById(regionResult);
    }

    /**
     * 定时按年统计严重违法主体情况
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticTsserillByYear}")
    public void staticTsserillByYear() {
        //按年统计严重违法主体情况
        List<Map<String, Integer>> illYearList = statisticsResultService.staticTsserillByYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_ill"));
        yResult.setDataJson(JSON.toJSONString(illYearList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时按列入原因统计严重违法主体情况
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticTsserillByIn}")
    public void staticTsserillByIn() {
        //按列入原因统计严重违法主体情况
        List<Map<String, Integer>> illInList = statisticsResultService.staticTsserillByIn();
        StatisticsResult inResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "in_ill"));
        inResult.setDataJson(JSON.toJSONString(illInList));
        statisticsResultService.updateById(inResult);
    }

//    /**
//     * 定时按移出原因统计严重违法主体情况
//     *
//     * @author xjy
//     */
//    @Scheduled(cron = "${scheduling.cron.staticTsserillByOutRe}")
//    public void staticTsserillByOutRe() {
//        //按移出原因和地区统计严重违法主体情况
//        List<Map<String, String>> illOutByRegorgList = statisticsResultService.staticTsserillByOutRe();
//        List<Map<String, Object>> result = new ArrayList<>();
//        for (String regorg : Constant.All_REGORG_GZ) {
//            Map<String, Object> atomMap = new HashMap<>();
//            List<Map<String, String>> atomList = new ArrayList<>();
//            for (Map<String, String> m : illOutByRegorgList) {
//                if (m.containsKey("regorg") && m.get("regorg").equals(regorg)) {
//                    if (m.containsKey("REMEXCPRES")) {
//                        Map<String, String> atom = new HashMap<>();
//                        atom.put("REMEXCPRES", m.get("REMEXCPRES"));
//                        atom.put("num", m.get("num"));
//                        atomList.add(atom);
//                    }
//                }
//            }
//            if (atomList.size() > 0) {
//                atomMap.put("name", Constant.NM_LOC_REGION_CODE.get(regorg));
//                atomMap.put("detail", atomList);
//                result.add(atomMap);
//            }
//        }
//
//        Map<String, Object> atomMap = new HashMap<>();
//        List<Map<String, String>> atomList = new ArrayList<>();
//        for (Map<String, String> m : illOutByRegorgList) {
//            if (m.containsKey("regorg") && m.get("regorg").equals("全市")) {
//                if (m.containsKey("REMEXCPRES")) {
//                    Map<String, String> atom = new HashMap<>();
//                    atom.put("REMEXCPRES", m.get("REMEXCPRES"));
//                    atom.put("num", m.get("num"));
//                    atomList.add(atom);
//                }
//            }
//            if (atomList.size() > 0) {
//                atomMap.put("name", "全市");
//                atomMap.put("detail", atomList);
//                result.add(0, atomMap);
//            }
//        }
//
//        StatisticsResult outRegionResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
//                .lambda().eq(StatisticsResult::getModuleTag, "out_region_ill"));
//        outRegionResult.setDataJson(JSON.toJSONString(result));
//        statisticsResultService.updateById(outRegionResult);
//    }

    /**
     * 定时协同监管结果分析
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticTsusualinspectType}")
    public void staticTsusualinspectType() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> usuaTypeList = statisticsResultService.staticTsusualinspectType();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "result_usua"));
        yResult.setDataJson(JSON.toJSONString(usuaTypeList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时协同监管主体分布
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticTsusualinspectRegion}")
    public void staticTsusualinspectRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> usuaRegionList = statisticsResultService.staticTsusualinspectRegion();
        for (Map<String, String> m : usuaRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_LOC_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_usua"));
        yResult.setDataJson(JSON.toJSONString(usuaRegionList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时撤销登记涉嫌登记类型分析
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticFraudType}")
    public void staticFraudType() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> fraudTypeList = statisticsResultService.staticFraudType();

        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "type_fraud"));
        yResult.setDataJson(JSON.toJSONString(fraudTypeList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时撤销登记增长分析(年)
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticFraudYear}")
    public void staticFraudYear() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> fraudYearList = statisticsResultService.staticFraudYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_fraud"));
        yResult.setDataJson(JSON.toJSONString(fraudYearList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时撤销登记主体分布
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticFraudRegion}")
    public void staticFraudRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> fraudRegionList = statisticsResultService.staticFraudRegion();
        for (Map<String, String> m : fraudRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_LOC_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_fraud"));
        yResult.setDataJson(JSON.toJSONString(fraudRegionList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时联合惩戒来源分析
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticLockType}")
    public void staticLockType() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> lockInList = statisticsResultService.staticLockType();

        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "in_lock"));
        yResult.setDataJson(JSON.toJSONString(lockInList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时联合惩戒主体分布
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticLockRegion}")
    public void staticLockRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> lockRegionList = statisticsResultService.staticLockRegion();
        for (Map<String, String> m : lockRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_LOC_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_lock"));
        yResult.setDataJson(JSON.toJSONString(lockRegionList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时批量吊销增长分析(年)
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticRevYear}")
    public void staticRevYear() {
        //<!--    按年统计全市-->
        List<Map<String, Integer>> revYearList = statisticsResultService.staticRevYear();
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "year_rev"));
        yResult.setDataJson(JSON.toJSONString(revYearList));
        statisticsResultService.updateById(yResult);
    }

    /**
     * 定时批量吊销主体分布
     *
     * @author xjy
     */
    @Scheduled(cron = "${scheduling.cron.staticRevRegion}")
    public void staticRevRegion() {
        //<!--    按年统计全市-->
        List<Map<String, String>> revRegionList = statisticsResultService.staticRevRegion();
        for (Map<String, String> m : revRegionList) {
            if (m.containsKey("region") && m.get("region") != null) {
                m.put("region", Constant.NM_LOC_REGION_CODE.get(m.get("region")));
            }
        }
        StatisticsResult yResult = statisticsResultService.getOne(new QueryWrapper<StatisticsResult>()
                .lambda().eq(StatisticsResult::getModuleTag, "all_region_rev"));
        yResult.setDataJson(JSON.toJSONString(revRegionList));
        statisticsResultService.updateById(yResult);
    }

        /**
     * 定时发送短信告知企业列严列异
     * 2024-10-22
     * @author lwd
     */
//    @Scheduled(cron = "${scheduling.cron.staticAbnSerSmsLogList}")
    public void staticAbnSerSmsLogList() {

        List<AbnSerSmsLog> abnSerSmsLogList = abnSerSmsLogService.selectabnSerSmsLogList();
        if (abnSerSmsLogList.size() > 0 ) {
            for (int i = 0; i < abnSerSmsLogList.size(); i++) {
                AbnSerSmsLog abnSerSmsLog = abnSerSmsLogList.get(i);
                Set<String> set = new HashSet<>();
                set.add(abnSerSmsLog.getPhones());
                try {
                   GsmsResponse gsmsResponse = smsService.basalticSdkSendSms(abnSerSmsLog.getContent(),"内蒙古自治区市场监督管理局",set);
                   if (gsmsResponse.getResult() == 0) {
                        abnSerSmsLog.setStatus("1");
                        abnSerSmsLog.setBackinfo(gsmsResponse.getMessage());
                        abnSerSmsLogService.updateById(abnSerSmsLog);
                    } else {
                        abnSerSmsLog.setStatus("2");
                        abnSerSmsLog.setBackinfo(gsmsResponse.getMessage());
                        abnSerSmsLogService.updateById(abnSerSmsLog);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(abnSerSmsLogList.size());

    }

    /**
     * 定时获取浪潮用户
     * 2025-07-10
     * @author lwd
     */
    @Scheduled(cron = "${scheduling.cron.staticHqlcusers}")
    public void staticHqlcusers() {
        testController.hqlcusers();
    }
}
