package com.chinaweal.aiccs.aiccs.abnormal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.AbnStatistics;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AbnStatDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.dto.AbnStatisticsDto;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.StatisticsAbnExcelDto;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.AbnStatisticsMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.AbnStatisticsService;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * <p>
 * 经营异常目录统计表 服务实现类
 * </p>
 *
 * @author sh
 * @since 2021-12-21
 */
@Slf4j
@Service
public class AbnStatisticsServiceImpl extends BaseServiceImpl<AbnStatisticsMapper, AbnStatistics> implements AbnStatisticsService, ServletContextListener {


    @Resource
    private TUsersService tUsersService;

    public static final List<String> XZQH_S = new ArrayList<>();

    /**线程池**/
    private final ExecutorService executorService = Executors.newFixedThreadPool(20);

    static {
        XZQH_S.add("注册二处");
        XZQH_S.add("信用处");
        XZQH_S.add("市局");
        XZQH_S.add("汇总"); // 第一层汇总分列入原因
        XZQH_S.add("汇总1"); // 第一层汇总不分列入原因
        XZQH_S.add("汇总2"); // 第二层汇总不分列入原因
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        executorService.shutdown();
    }

    @Override
    public Map<String,Object> StatisticsForAbn(Map<String, Object> customParamMap) {
        Map<String,Object> map = new HashMap<>();
        AICUser curUser = SSOUtil.getUser();
        List<AbnStatDto> abnStatDtos1 = new ArrayList<>();
        Object searchDate = customParamMap.get("searchDate");
        if (searchDate instanceof List) {
            List<String> list = (List<String>) searchDate;
            customParamMap.put("startDate", list.get(0));
            customParamMap.put("endDate", list.get(1));
        }
        Long start = System.currentTimeMillis();

        if ("440101".equals(curUser.getRegionID())) { // 市局账号
            // 辣鸡需求start-----------
            List<AbnStatDto> abnStatDtos2 = new ArrayList<>();
            List<String> xzqhs = XZQH_S;
            CountDownLatch cdl = new CountDownLatch(xzqhs.size());
//            ExecutorService executorService = Executors.newFixedThreadPool(20);

            for (String xzqh : xzqhs) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Map map = new HashMap();
                            map.put("startDate",customParamMap.get("startDate"));
                            map.put("endDate",customParamMap.get("endDate"));
                            if ("汇总1".equals(xzqh)) {
                                map.put("xzqh","汇总");
                                AbnStatDto abnStatDto = baseMapper.statisticsForAbnHz(map);
                                abnStatDto.setIndex("3");
                                abnStatDto.setXzqh(xzqh);
                                abnStatDtos1.add(abnStatDto);
                            } else if ("汇总2".equals(xzqh)) {
                                map.put("xzqh", "市局");
                                AbnStatDto abnStatDto = baseMapper.statisticsForAbnHz(map);
                                abnStatDto.setXzqh(xzqh);
                                abnStatDto.setIndex("3");
                                abnStatDtos2.add(abnStatDto);
                            } else {
                                map.put("xzqh", xzqh);
                                AbnStatDto abnStatDto = baseMapper.statisticsForAbn(map);
                                if (xzqh.equals("市局")) {
                                    abnStatDto.setXzqh("广州市市场监督管理局");
                                    abnStatDto.setIndex("2");
                                    abnStatDtos1.add(abnStatDto);
                                    abnStatDtos2.add(abnStatDto); // 第二层汇总分类型
                                } else if (xzqh.equals("注册二处") || xzqh.equals("信用处")) {
                                    abnStatDto.setIndex("1");
                                    abnStatDto.setXzqh(xzqh);
                                    abnStatDtos2.add(abnStatDto);
                                } else if (xzqh.equals("汇总")) {
                                    abnStatDto.setXzqh(xzqh);
                                    abnStatDto.setIndex("3");
                                    abnStatDtos1.add(abnStatDto);
                                } else {
                                    abnStatDto.setXzqh("广州市" + xzqh + "区市场监督管理局");
                                    abnStatDto.setIndex("3");
                                    abnStatDtos1.add(abnStatDto);
                                }
                            }
                            cdl.countDown();
                        } catch (Exception e) {
                            e.printStackTrace();
                            cdl.countDown();
                        }
                    }
                });
            }
            try {
                cdl.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            executorService.shutdown();
            List<AbnStatDto> list2 = abnStatDtos2.stream().sorted(Comparator.comparing(AbnStatDto::getIndex).thenComparing(AbnStatDto::getXzqh)).collect(Collectors.toList());
            AbnStatDto abnStathz2 = new AbnStatDto();
            for (AbnStatDto demo : list2) {
                if (demo.getXzqh().equals("广州市市场监督管理局")) {
                    abnStathz2 = demo;
                }
                if (demo.getXzqh().equals("汇总2")) {
                    demo.setQyyy(abnStathz2.getQyyy());
                    demo.setGtyy(abnStathz2.getGtyy());
                    demo.setNhyy(abnStathz2.getNhyy());
                }
            }
            map.put("abnStatisticsDtos2",list2);
            // 辣鸡需求end-----------
        } else { // 区所账号
            String xzqh = curUser.getOrgName().substring(3,5);
            customParamMap.put("xzqh", xzqh);
            customParamMap.put("orgCode", curUser.getRegionID());

            // 查区
            if (curUser.getRegionID().length() == 6) {
                AbnStatDto abnStatDto = baseMapper.statisticsForAbn(customParamMap);
                abnStatDto.setXzqh(curUser.getOrgName());
                abnStatDto.setIndex("1");
                abnStatDtos1.add(abnStatDto);
            }

            // 查所
            List<AbnStatDto> abnStatDtoList = baseMapper.statisticsForAbnQJ(customParamMap);
            abnStatDtos1.addAll(abnStatDtoList);
        }
        List<AbnStatDto> list1 = abnStatDtos1.stream().sorted(Comparator.comparing(AbnStatDto::getIndex).thenComparing(AbnStatDto::getXzqh)).collect(Collectors.toList());
        log.info("专项统计耗时：{}ms", System.currentTimeMillis() - start);
        if (list1.size() > 2) {
            AbnStatDto abnStathz1 = new AbnStatDto();
            for (AbnStatDto demo : list1) {
                if (demo.getXzqh().equals("汇总")) {
                    abnStathz1 = demo;
                }
                if (demo.getXzqh().equals("汇总1")) {
                    demo.setQyyy(abnStathz1.getQyyy());
                    demo.setGtyy(abnStathz1.getGtyy());
                    demo.setNhyy(abnStathz1.getNhyy());
                }
            }
        }
        map.put("abnStatisticsDtos1",list1);
        return map;
    }

    @Override
    public Map<String,Object> queryStatAll(Map<String, Object> customParamMap, AICUser aicUser) {
        Map<String,Object> map = new HashMap<>();
        Boolean containToday = false;
        Object searchDate = customParamMap.get("searchDate");
        Date date = new Date();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sbf.format(date);
        if(searchDate instanceof List){
            List<String> list = (List<String>) searchDate;
            String startStr = list.get(0);
            String endStr = list.get(1);
            customParamMap.put("startDate", startStr);
            customParamMap.put("endDate", endStr);
            try {
                Date today = sbf.parse(dateStr);
                Date startD = sbf.parse(startStr);
                Date endD = sbf.parse(endStr);
                if (today.compareTo(startD)>=0 || today.compareTo(endD)<=0) { //包含今天
                    containToday = true;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            containToday = true;
        }
        String xzqh = aicUser.getOrgName().substring(3,5);
        customParamMap.put("xzqh", xzqh);
        List<AbnStatisticsDto> abnStatisticsDtos = baseMapper.queryStatAll(customParamMap);
        if (containToday) { //需加上含当天数量
            abnStatisticsDtos.forEach(each -> {
                AbnStatistics abnStatisticsqy = baseMapper.queryStatByDate(each.getXzqh(), dateStr, "qy");
                AbnStatistics abnStatisticsgt = baseMapper.queryStatByDate(each.getXzqh(), dateStr, "gt");
                //企业
                each.setType1(each.getType1() + abnStatisticsqy.getType1());
                each.setType2(each.getType2() + abnStatisticsqy.getType2());
                each.setType3(each.getType3() + abnStatisticsqy.getType3());
                each.setType4(each.getType4() + abnStatisticsqy.getType4());
                each.setType5(each.getType5() + abnStatisticsqy.getType5());
                each.setType6(each.getType6() + abnStatisticsqy.getType6());
                each.setType7(each.getType7() + abnStatisticsqy.getType7());
                each.setType8(each.getType8() + abnStatisticsqy.getType8());
                each.setType9(each.getType9() + abnStatisticsqy.getType9());
                each.setType10(each.getType10() + abnStatisticsqy.getType10());
                //个体户
                each.setType11(each.getType11() + abnStatisticsgt.getType1());
                each.setType12(each.getType12() + abnStatisticsgt.getType2());
                each.setType13(each.getType13() + abnStatisticsgt.getType3());
                each.setType14(each.getType14() + abnStatisticsgt.getType4());
                each.setType15(each.getType15() + abnStatisticsgt.getType5());
                each.setType16(each.getType16() + abnStatisticsgt.getType6());
                each.setType17(each.getType17() + abnStatisticsgt.getType7());
                each.setType18(each.getType18() + abnStatisticsgt.getType8());
                each.setType19(each.getType19() + abnStatisticsgt.getType9());
                each.setType20(each.getType20() + abnStatisticsgt.getType10());
            });
        }
        List<AbnStatisticsDto> abnStatisticsDtos1 = new LinkedList<>();
        List<AbnStatisticsDto> abnStatisticsDtos2 = new ArrayList<>(); //市局第二层统计
        AbnStatisticsDto sj = new AbnStatisticsDto(); //市局
        sj.setXzqh("广州市市场监督管理局");
        AbnStatisticsDto summary = new AbnStatisticsDto();
        AbnStatisticsDto summary1 = new AbnStatisticsDto(); //汇总
        summary1.setXzqh("汇总1");
        for (AbnStatisticsDto abnStatisticsDto : abnStatisticsDtos) {
            if (abnStatisticsDto.getXzqh().equals("汇总")) {
                summary1 = sumAbnStatisticsDto(summary1, abnStatisticsDto);
                summary = abnStatisticsDto;
                continue;
            }
            if (!abnStatisticsDto.getXzqh().equals("信用处") && !abnStatisticsDto.getXzqh().equals("注册二处")) { //区局
                abnStatisticsDto.setXzqh(abnStatisticsDto.getXzqh() + "市场监督管理局");
                abnStatisticsDtos1.add(abnStatisticsDto);
            } else {  //市局
                abnStatisticsDtos2.add(abnStatisticsDto);
                sj.setType1(sj.getType1() + abnStatisticsDto.getType1());
                sj.setType2(sj.getType2() + abnStatisticsDto.getType2());
                sj.setType3(sj.getType3() + abnStatisticsDto.getType3());
                sj.setType4(sj.getType4() + abnStatisticsDto.getType4());
                sj.setType5(sj.getType5() + abnStatisticsDto.getType5());
                sj.setType6(sj.getType6() + abnStatisticsDto.getType6());
                sj.setType7(sj.getType7() + abnStatisticsDto.getType7());
                sj.setType8(sj.getType8() + abnStatisticsDto.getType8());
                sj.setType9(sj.getType9() + abnStatisticsDto.getType9());
                sj.setType10(sj.getType10() + abnStatisticsDto.getType10());
                sj.setType11(sj.getType11() + abnStatisticsDto.getType11());
                sj.setType12(sj.getType12() + abnStatisticsDto.getType12());
                sj.setType13(sj.getType13() + abnStatisticsDto.getType13());
                sj.setType14(sj.getType14() + abnStatisticsDto.getType14());
                sj.setType15(sj.getType15() + abnStatisticsDto.getType15());
                sj.setType16(sj.getType16() + abnStatisticsDto.getType16());
                sj.setType17(sj.getType17() + abnStatisticsDto.getType17());
                sj.setType18(sj.getType18() + abnStatisticsDto.getType18());
                sj.setType19(sj.getType19() + abnStatisticsDto.getType19());
                sj.setType20(sj.getType20() + abnStatisticsDto.getType20());
            }
        }
        // 第二层的汇总计算
        AbnStatisticsDto summarydrc2 = new AbnStatisticsDto();
        summarydrc2.setXzqh("汇总1");
        summarydrc2 = sumAbnStatisticsDto(summarydrc2,sj);
        abnStatisticsDtos2.add(sj);
        abnStatisticsDtos2.add(summarydrc2);

        //第一层市局用户
        if (aicUser.getOrgName().equals("广州市市场监督管理局")) {
            abnStatisticsDtos1.add(0,sj);
        }
        abnStatisticsDtos1.add(summary);
        abnStatisticsDtos1.add(summary1);
        map.put("abnStatisticsDtos1",abnStatisticsDtos1);
        map.put("abnStatisticsDtos2",abnStatisticsDtos2);
        return map;
    }

    @Override
    public IPage<StatisticsAbnExcelDto> getEntListByStatistics(PageRequestDto pageRequestDto) {
        // 组装查询参数 --start
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        String[] searchDate = String.valueOf(customParamMap.get("searchDate")).split(","); // 查询日期
        String content = (String) customParamMap.get("content");  // 查询内容
        String orgName = (String) customParamMap.get("orgName");  // 单位

        OrgUnits orgUnits = tUsersService.byOrgUnitName(orgName);

        // 查询企业类型qy、gt、nh
        String entType = content.substring(0, 2);
        // 查询业务类型 列入、移出、异常
        String operateStatus = null;
        // 查询原因
        String cause = null;
        if (content.contains("lr")) {
            cause = content.substring(content.length() - 1);
            customParamMap.put("startDate", searchDate[0]);
            customParamMap.put("endDate", searchDate[1]);
        } else if (content.contains("yc")) {
            operateStatus = "0";
            cause = content.substring(content.length() - 1);
            customParamMap.put("remStartDate", searchDate[0]);
            customParamMap.put("remEndDate", searchDate[1]);
        } else {
            operateStatus = "2";
            customParamMap.put("startDate", searchDate[0]);
            customParamMap.put("endDate", searchDate[1]);
        }
        customParamMap.put("entType", entType);
        customParamMap.put("operateStatus", operateStatus);
        customParamMap.put("cause", cause);
        customParamMap.put("content", content);
        customParamMap.put("orgCode", orgUnits.getOrgNumber());
        customParamMap.put("xzqh", "广州市市场监督管理局".equals(orgName) ? "市局" : orgName.substring(3,5)); // 行政区划
        // 组装查询参数 --end

        IPage<StatisticsAbnExcelDto> data = baseMapper.getEntListByStatistics(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), customParamMap);
        return data;
    }

    // 汇总计算
    public AbnStatisticsDto sumAbnStatisticsDto(AbnStatisticsDto source, AbnStatisticsDto target){
        source.setType1(target.getType1() + target.getType2() + target.getType3() + target.getType4() + target.getType5());
        source.setType2(target.getType6() + target.getType7() + target.getType8() + target.getType9() + target.getType10());
        source.setType4(target.getType11() + target.getType12() + target.getType13() + target.getType14() + target.getType15());
        source.setType3(target.getType16() + target.getType17() + target.getType18() + target.getType19() + target.getType20());
        return source;
    }
}
