package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.google.gson.JsonObject;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PDFUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ProposalInfo;
import com.ruoyi.system.domain.member.MemberInfo;
import com.ruoyi.system.domain.sqmy.SqmyInfo;
import com.ruoyi.system.domain.vo.MemberInfoVoTwo;
import com.ruoyi.system.mapper.MemberInfoMapper;
import com.ruoyi.system.mapper.ProposalInfoMapper;
import com.ruoyi.system.mapper.SqmyInfoMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.IStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: tjf
 * @Date: 2024/3/18 13:55
 * @Describe:
 */
@Service
public class StatisticsServiceImpl implements IStatisticsService {

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private ProposalInfoMapper proposalInfoMapper;

    @Autowired
    private SqmyInfoMapper sqmyInfoMapper;

    /**
     * 统计查询委员图形分析 界别
     */
    @Override
    public AjaxResult boundary() {
        Map<String, Object> mapZ = new HashMap<>(4);
        //查询界别字典值
        List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType("circles");
        if (dictDataList != null && dictDataList.size() > 0) {
            //根据委员界别分类统计
            List<MemberInfo> memberInfoList = memberInfoMapper.selectMemberInfoList(new MemberInfo());
            if (memberInfoList != null && memberInfoList.size() > 0) {
                Map<String, List<MemberInfo>> memberInfoCollect = memberInfoList.stream().collect(Collectors.groupingBy(MemberInfo::getBoundary));
                List<String> dictLabelList = new ArrayList<>();
                List<Integer> dictValueList = new ArrayList<>();
                List<MemberInfoVoTwo> memberInfoVoTwoList = new ArrayList<>();
                List<JSONObject> jsonObjsList = new ArrayList<>();
                for (SysDictData sysDictData : dictDataList) {
                    JSONObject jsonObj = new JSONObject();
                    MemberInfoVoTwo memberInfoVoTwo = new MemberInfoVoTwo();
                    memberInfoVoTwo.setSort(sysDictData.getDictSort());
                    String dictLabel = sysDictData.getDictLabel();
                    String dictValue = sysDictData.getDictValue();
                    jsonObj.put("name", dictLabel);
                    memberInfoVoTwo.setBoundary(dictLabel);
                    //柱状图
                    dictLabelList.add(dictLabel);
                    List<MemberInfo> memberInfoListV = memberInfoCollect.get(dictValue);
                    //如果没这个界别就输入0
                    if (memberInfoListV != null && memberInfoListV.size() > 0) {
                        dictValueList.add(memberInfoListV.size());
                        memberInfoVoTwo.setNum(memberInfoListV.size());
                        jsonObj.put("value", memberInfoListV.size());

                    } else {
                        dictValueList.add(0);
                        memberInfoVoTwo.setNum(0);
                        jsonObj.put("value", 0);
                    }
                    memberInfoVoTwoList.add(memberInfoVoTwo);
                    jsonObjsList.add(jsonObj);
                }
                mapZ.put("x", dictLabelList);
                mapZ.put("y", dictValueList);
                mapZ.put("pieData", jsonObjsList);
                mapZ.put("total", memberInfoList.size());
                mapZ.put("list", memberInfoVoTwoList);
            }
        }
        return AjaxResult.success(mapZ);
    }

    /**
     * 导出pdf
     *
     * @param response
     */
    @Override
    public void exportForm(HttpServletResponse response, MemberInfo memberInfo) {
        // 1.创建文档,设置文档页面大小,页边距
        Document document = new Document(PageSize.A4, Float.parseFloat("0"), Float.parseFloat("5"),
                Float.parseFloat("34"), Float.parseFloat("50"));

        // 2.解析前台传来的echart图，生成pdf段落元素
        Paragraph pictureEle = PDFUtil.createImageFromEncodeBase64(memberInfo.getEle(), "柱状统计图", Float.parseFloat("34"),
                Float.parseFloat("50"), true);
        Paragraph picturePie = PDFUtil.createImageFromEncodeBase64(memberInfo.getPie(), "柱状统计图", Float.parseFloat("34"),
                Float.parseFloat("100"), true);
        //查询界别字典值
        List<SysDictData> dictDataList = dictDataMapper.selectDictDataByType("circles");
        List<MemberInfoVoTwo> memberInfoVoTwoList = new ArrayList<>();
        if (dictDataList != null && dictDataList.size() > 0) {
            //根据委员界别分类统计
            List<MemberInfo> memberInfoList = memberInfoMapper.selectMemberInfoList(new MemberInfo());
            if (memberInfoList != null && memberInfoList.size() > 0) {
                Map<String, List<MemberInfo>> memberInfoCollect = memberInfoList.stream().collect(Collectors.groupingBy(MemberInfo::getBoundary));
                for (SysDictData sysDictData : dictDataList) {
                    MemberInfoVoTwo memberInfoVoTwo = new MemberInfoVoTwo();
                    memberInfoVoTwo.setSort(sysDictData.getDictSort());
                    String dictLabel = sysDictData.getDictLabel();
                    String dictValue = sysDictData.getDictValue();
                    memberInfoVoTwo.setBoundary(dictLabel);
                    List<MemberInfo> memberInfoListV = memberInfoCollect.get(dictValue);
                    //如果没这个界别就输入0
                    if (memberInfoListV != null && memberInfoListV.size() > 0) {
                        memberInfoVoTwo.setNum(memberInfoListV.size());
                    } else {
                        memberInfoVoTwo.setNum(0);
                    }
                    memberInfoVoTwoList.add(memberInfoVoTwo);
                }
            }
        }
        List<String> methodNames = new ArrayList<>();
        methodNames.add("getSort");
        methodNames.add("getBoundary");
        methodNames.add("getNum");
        // 生成table表格段落
        Paragraph table = PDFUtil.createTable(memberInfoVoTwoList, "界别统计表", new String[]{"序号", "界别", "人数"}, methodNames);

        // 将所有需要放到文档里的元素，汇总
        List<Paragraph> paragraphs = new ArrayList<Paragraph>();
        paragraphs.add(pictureEle);
        paragraphs.add(table);
        paragraphs.add(picturePie);
        // 导出pdf文档：将paragraphs塞到document中，并下载document
        PDFUtil.exportDocument(document, null, paragraphs, response, "报表");
    }

    @Override
    public AjaxResult threeData() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> map = new HashMap<>();
        //获取当前时间
        String endTime = DateUtils.getTime();
        //获取三个月前的时间
        String strTime = DateUtils.lastMouth(DateUtils.getMonth(), -2) + "-01" + " 00:00:00";
        //查询近三月提案数
        ProposalInfo proposalInfo = new ProposalInfo();
        proposalInfo.setStartTime(strTime);
        proposalInfo.setEndTime(endTime);
        List<ProposalInfo> proposalInfos = proposalInfoMapper.selectProposalInfoList(proposalInfo);
        Map<String, Object> threeTaMap = new HashMap<>();
        threeTaMap.put("time", strTime.split(" ")[0] + "/" + endTime.split(" ")[0]);
        threeTaMap.put("threeTa", 0);
        if (proposalInfos != null) {
            threeTaMap.put("threeTa", proposalInfos.size());
        }
        map.put("threeTaMap", threeTaMap);


        //查询近三月社情民意数
        SqmyInfo sqmyInfo = new SqmyInfo();
        sqmyInfo.setStartTime(strTime);
        sqmyInfo.setEndTime(endTime);
        List<SqmyInfo> sqmyInfos = sqmyInfoMapper.selectSqmyInfoList(sqmyInfo);
        Map<String, Object> threeSqmyMap = new HashMap<>();
        threeSqmyMap.put("time", strTime.split(" ")[0] + "/" + endTime.split(" ")[0]);
        threeSqmyMap.put("threesqmy", 0);
        if (sqmyInfos != null) {
            threeSqmyMap.put("threesqmy", sqmyInfos.size());
        }
        map.put("threeSqmyMap", threeSqmyMap);


        //较上周委员提案
        //获取上周第一天
        String previousWeekMonday = DateUtils.getPreviousWeekMonday();
        //获取上周最一天
        String previousWeekSunday = DateUtils.getPreviousWeekSunday();
        //上周数量
        int lastWeek = 0;
        //本周第一天
        String thisWeekMonday = DateUtils.getThisWeekMonday();
        //本周数量
        int week = 0;
        Map<String, Object> taMap = new HashMap<>();
        //0：正，1：负
        taMap.put("symbol", 0);
        taMap.put("percent", "0%");
        if (proposalInfos != null && proposalInfos.size() > 0) {
            for (ProposalInfo info : proposalInfos) {
                String str = formatter.format(info.getCreateTime());
                if (DateUtils.isEffectiveDate(str, previousWeekMonday, previousWeekSunday)) {
                    lastWeek++;
                } else if (DateUtils.isEffectiveDate(str, thisWeekMonday, endTime)) {
                    week++;
                }
            }
        }
        if (lastWeek > week) {
            taMap.put("symbol", 1);
        }
        BigDecimal num1 = new BigDecimal(lastWeek);
        BigDecimal num2 = new BigDecimal(week);
        BigDecimal subNum1 = num2.subtract(num1);
        //subNum1/num1
        taMap.put("percent", "0%");
        DecimalFormat decimalFormat = new DecimalFormat("0%"); // 创建DecimalFormat对象并设置格式化模式为"0%"
        if(lastWeek!=0){
            double result = Double.parseDouble(((subNum1.divide(num1, 2, BigDecimal.ROUND_HALF_UP))).toString());
            if (result < 0) {
                result = result * -1;
            }
            String percentage = decimalFormat.format((result)); // 使用DecimalFormat对象进行格式化操作
            taMap.put("percent", percentage);
        }

        map.put("taMap", taMap);

        //较上月上报社情民意
        //上一个月开始时间
        String lastStartMonth = DateUtils.lastMouth(DateUtils.getMonth(), -1) + "-01" + " 00:00:00";
        //上一个月结束时间
        String lastEndtMonth = DateUtils.lastMouth(DateUtils.getMonth(), -1) + "-31" + " 23:59:59";
        //上月数量
        int lastMonth = 0;
        //本月开始时间
        String startMonth = DateUtils.lastMouth(DateUtils.getMonth(), 0) + "-01" + " 00:00:00";
        //本月数量
        int month = 0;
        Map<String, Object> sqmyMap = new HashMap<>();
        //0：正，1：负
        sqmyMap.put("symbol", 0);
        sqmyMap.put("percent", "0%");
        if (sqmyInfos != null && sqmyInfos.size() > 0) {
            for (SqmyInfo info : sqmyInfos) {
                String str = formatter.format(info.getCreateTime());
                if (DateUtils.isEffectiveDate(str, lastStartMonth, lastEndtMonth)) {
                    lastMonth++;
                } else if (DateUtils.isEffectiveDate(str, startMonth, endTime)) {
                    month++;
                }
            }
        }
        BigDecimal monthNum1 = new BigDecimal(lastMonth);
        BigDecimal monthNum2 = new BigDecimal(month);
        BigDecimal monthsubNum1 = monthNum2.subtract(monthNum1);
        //subNum1/num1
        taMap.put("percent", "0%");
        if(lastMonth != 0){
            double resultMonth = Double.parseDouble(((monthsubNum1.divide(monthNum1, 2, BigDecimal.ROUND_HALF_UP))).toString());
            if (resultMonth < 0) {
                resultMonth = resultMonth * -1;
            }
            taMap.put("percent", decimalFormat.format((resultMonth)));
        }

        map.put("sqmyMap", sqmyMap);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult weekData() throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> map = new HashMap<>();
        //获取当前时间
        String endTime = DateUtils.getTime();
        //本周第一天
        String strTime = DateUtils.getThisWeekMonday();
        //获取本周的所有日期
        List<String> weekList = DateUtils.getWeekData(DateUtils.getDate());
        map.put("week", weekList);
        //查询本周提案数
        ProposalInfo proposalInfo = new ProposalInfo();
        proposalInfo.setStartTime(strTime);
        proposalInfo.setEndTime(endTime);
        List<ProposalInfo> proposalInfos = proposalInfoMapper.selectProposalInfoList(proposalInfo);
        List<Integer> taInt = new ArrayList<>();
        Boolean tbl = proposalInfos != null && proposalInfos.size() > 0;
        for (int i = 0; i < weekList.size(); i++) {
            int num = 0;
            if (tbl) {
                for (ProposalInfo info : proposalInfos) {
                    String str = formatter.format(info.getCreateTime());
                    if (str.contains(weekList.get(i))) {
                        num++;
                    }
                }
            }
            taInt.add(num);
        }
        map.put("taInt", taInt);
        //查询本周社情民意数
        SqmyInfo sqmyInfo = new SqmyInfo();
        sqmyInfo.setStartTime(strTime);
        sqmyInfo.setEndTime(endTime);
        List<SqmyInfo> sqmyInfos = sqmyInfoMapper.selectSqmyInfoList(sqmyInfo);
        List<Integer> sqmyInt = new ArrayList<>();
        Boolean sbl = sqmyInfos != null && sqmyInfos.size() > 0;
        for (int i = 0; i < weekList.size(); i++) {
            int num = 0;
            if (sbl) {
                for (SqmyInfo info : sqmyInfos) {
                    String str = formatter.format(info.getCreateTime());
                    if (str.contains(weekList.get(i))) {
                        num++;
                    }
                }
            }
            sqmyInt.add(num);
        }
        map.put("sqmyInt", sqmyInt);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult quarterData() {
        Map<String, Object> map = new HashMap<>();
        //获取当前时间
        String endTime = DateUtils.getTime();
        //本季度第一天
        String strTime = DateUtils.getQuarterFirst() + " 00:00:00";
        //查询本周提案数
        ProposalInfo proposalInfo = new ProposalInfo();
        proposalInfo.setStartTime(strTime);
        proposalInfo.setEndTime(endTime);
        List<ProposalInfo> proposalInfos = proposalInfoMapper.selectProposalInfoList(proposalInfo);
        //已立案
        int yla = 0;
        Map<String, Object> ylaMap = new HashMap<>();
        ylaMap.put("percent", "0%");
        ylaMap.put("name", "已立案");
        ylaMap.put("num", yla);

        //未立案
        int wla = 0;
        Map<String, Object> wlaMap = new HashMap<>();
        wlaMap.put("percent", "0%");
        wlaMap.put("name", "已立案");
        wlaMap.put("num", wla);

        //已办结
        int ybj = 0;
        Map<String, Object> ybjMap = new HashMap<>();
        ybjMap.put("percent", "0%");
        ybjMap.put("name", "已立案");
        ybjMap.put("num", ybj);

        //未办结
        int wbj = 0;
        Map<String, Object> wbjMap = new HashMap<>();
        wbjMap.put("percent", "0%");
        wbjMap.put("name", "已立案");
        wbjMap.put("num", wbj);

        //待办理
        int dbl = 0;
        Map<String, Object> dblMap = new HashMap<>();
        dblMap.put("percent", "0%");
        dblMap.put("name", "已立案");
        dblMap.put("num", dbl);
        if (proposalInfos!=null && proposalInfos.size()>0) {
            for (ProposalInfo info : proposalInfos) {
                if (Integer.parseInt(info.getProposalProgress()) >= 2 && !"3".equals(info.getProposalProgress())) {
                    yla++;
                    if ("8".equals(info.getProposalProgress())) {
                        ybj++;
                    } else {
                        wbj++;
                    }
                }
                if ("3".equals(info.getProposalProgress())) {
                    wla++;
                }
                if ("0".equals(info.getProposalProgress()) || "1".equals(info.getProposalProgress())) {
                    dbl++;
                }
            }

            BigDecimal num1 = new BigDecimal(proposalInfos.size());
            DecimalFormat decimalFormat = new DecimalFormat("0%"); // 创建DecimalFormat对象并设置格式化模式为"0%"

            //已立案
            BigDecimal num2 = new BigDecimal(yla);
            //num2/num1
            double ylaResult = Double.parseDouble(((num2.divide(num1, 2, BigDecimal.ROUND_HALF_UP))).toString());
            ylaMap.put("percent", decimalFormat.format((ylaResult)));

            //未立案
            BigDecimal num3 = new BigDecimal(wla);
            //num2/num1
            double wlaResult = Double.parseDouble(((num3.divide(num1, 2, BigDecimal.ROUND_HALF_UP))).toString());
            wlaMap.put("percent", decimalFormat.format((wlaResult)));

            //已办结
            BigDecimal num4 = new BigDecimal(ybj);
            //num2/num1
            double ybjResult = Double.parseDouble(((num4.divide(num1, 2, BigDecimal.ROUND_HALF_UP))).toString());
            ybjMap.put("percent", decimalFormat.format((ybjResult)));

            //未办结
            BigDecimal num5 = new BigDecimal(wbj);
            //num2/num1
            double wbjResult = Double.parseDouble(((num5.divide(num1, 2, BigDecimal.ROUND_HALF_UP))).toString());
            wbjMap.put("percent", decimalFormat.format((wbjResult)));

            //待办理
            BigDecimal num6 = new BigDecimal(dbl);
            //num2/num1
            double dblResult = Double.parseDouble(((num6.divide(num1, 2, BigDecimal.ROUND_HALF_UP))).toString());
            dblMap.put("percent", decimalFormat.format((dblResult)));
        }
        map.put("ylaMap",ylaMap);
        map.put("wlaMap",wlaMap);
        map.put("ybjMap",ybjMap);
        map.put("wbjMap",wbjMap);
        map.put("dblMap",dblMap);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult personageData() {
        Map<String, Object> map = new HashMap<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        ProposalInfo proposalInfo = new ProposalInfo();
        proposalInfo.setProposalUserId(user.getUserId());
        List<ProposalInfo> proposalInfos = proposalInfoMapper.selectProposalInfoList(proposalInfo);
        Map<String, Object> taMap = new HashMap<>();
        //总提案数
        int zta = 0;
        //提案立案
        int tala = 0;
        //提案不予立案
        int tabyla = 0;
        if (proposalInfos!=null && proposalInfos.size()>0) {
            zta = proposalInfos.size();
            for (ProposalInfo info : proposalInfos) {
                if (Integer.parseInt(info.getProposalProgress()) >= 2 && !"3".equals(info.getProposalProgress())) {
                    tala++;
                }
                if ("3".equals(info.getProposalProgress())) {
                    tabyla++;
                }
            }
        }
        taMap.put("zta",zta);
        taMap.put("tala",tala);
        taMap.put("tabyla",tabyla);
        map.put("taMap",taMap);

        SqmyInfo sqmyInfo = new SqmyInfo();
        sqmyInfo.setSqmyUserId(user.getUserId());
        List<SqmyInfo> sqmyInfos = sqmyInfoMapper.selectSqmyInfoList(sqmyInfo);
        Map<String, Object> sqmyMap = new HashMap<>();
        //总社情民意数
        int zsqmy = 0;
        //社情民意立案
        int sqmyla = 0;
        //社情民意不予立案
        int sqmybyla = 0;
        if (sqmyInfos!=null && sqmyInfos.size()>0) {
            zta = sqmyInfos.size();
            for (SqmyInfo info : sqmyInfos) {
                if (Integer.parseInt(info.getSqmyProgress()) >= 2 && !"3".equals(info.getSqmyProgress())) {
                    sqmyla++;
                }
                if ("3".equals(info.getSqmyProgress())) {
                    sqmybyla++;
                }
            }
        }
        sqmyMap.put("zsqmy",zsqmy);
        sqmyMap.put("sqmyla",sqmyla);
        sqmyMap.put("sqmybyla",sqmybyla);
        map.put("sqmyMap",sqmyMap);

        return AjaxResult.success(map);
    }
}
