package com.zehong.system.service.impl;

import com.alibaba.excel.EasyExcel;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.system.config.easyexcel.CustomCellWriteHeightConfig;
import com.zehong.system.config.easyexcel.CustomCellWriteWidthConfig;
import com.zehong.system.domain.TComplainDealManSysSet;
import com.zehong.system.domain.TPublicSentiment;
import com.zehong.system.domain.dto.TComplainDealDTO;
import com.zehong.system.domain.vo.ComplainDealSummaryAnalysisTableVo;
import com.zehong.system.mapper.TPublicSentimentMapper;
import com.zehong.system.service.ITPublicSentimentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 舆情处置Service业务层处理
 * 
 * @author zehong
 * @date 2025-08-15
 */
@Service
public class TPublicSentimentServiceImpl implements ITPublicSentimentService 
{
    @Autowired
    private TPublicSentimentMapper tPublicSentimentMapper;

    /**
     * 查询舆情处置
     * 
     * @param sentimentId 舆情处置ID
     * @return 舆情处置
     */
    @Override
    public TPublicSentiment selectTPublicSentimentById(Long sentimentId)
    {
        return tPublicSentimentMapper.selectTPublicSentimentById(sentimentId);
    }

    /**
     * 查询舆情处置列表
     * 
     * @param tPublicSentiment 舆情处置
     * @return 舆情处置
     */
    @Override
    public List<TPublicSentiment> selectTPublicSentimentList(TPublicSentiment tPublicSentiment)
    {
        return tPublicSentimentMapper.selectTPublicSentimentList(tPublicSentiment);
    }

    /**
     * 新增舆情处置
     * 
     * @param tPublicSentiment 舆情处置
     * @return 结果
     */
    @Override
    public int insertTPublicSentiment(TPublicSentiment tPublicSentiment)
    {
        tPublicSentiment.setCreateTime(DateUtils.getNowDate());
        return tPublicSentimentMapper.insertTPublicSentiment(tPublicSentiment);
    }

    /**
     * 修改舆情处置
     * 
     * @param tPublicSentiment 舆情处置
     * @return 结果
     */
    @Override
    public int updateTPublicSentiment(TPublicSentiment tPublicSentiment)
    {
        tPublicSentiment.setUpdateTime(new Date());
        return tPublicSentimentMapper.updateTPublicSentiment(tPublicSentiment);
    }

    /**
     * 批量删除舆情处置
     * 
     * @param sentimentIds 需要删除的舆情处置ID
     * @return 结果
     */
    @Override
    public int deleteTPublicSentimentByIds(Long[] sentimentIds)
    {
        return tPublicSentimentMapper.deleteTPublicSentimentByIds(sentimentIds);
    }

    /**
     * 删除舆情处置信息
     * 
     * @param sentimentId 舆情处置ID
     * @return 结果
     */
    @Override
    public int deleteTPublicSentimentById(Long sentimentId)
    {
        return tPublicSentimentMapper.deleteTPublicSentimentById(sentimentId);
    }

    /**
     * 舆情 统计分析 table 方式 方法
     * @return list
     */
    @Override
    public List<ComplainDealSummaryAnalysisTableVo> sentimentSummaryAnalysisMethodTableViews(ComplainDealSummaryAnalysisTableVo complainDealSummaryAnalysisTableVo) {
        //规定办结时间
        long duration = 7 * 24L * 60 * 60 * 1000;
        //总发生量
        BigDecimal totalAmount = BigDecimal.ZERO;

        //总办结量
        BigDecimal totalCompletionRate = BigDecimal.ZERO;

        //总及时办结量
        BigDecimal totalTimelyCompletionRate = BigDecimal.ZERO;

        String date1 = complainDealSummaryAnalysisTableVo.getDate();
        if(StringUtils.isEmpty(date1)) {
            return initEmptyList();
        }

        //查询当前年的开始时间和结束时间
        Date startOfMonth = DateUtils.parseDate(date1 + "-01-01 00:00:00");
        Date endOfMonth = DateUtils.parseDate(date1 + "-12-31 23:59:59");;
        String township = complainDealSummaryAnalysisTableVo.getTownship();

        //所有所有发生的投诉
        List<TComplainDealDTO> tComplainDeals = tPublicSentimentMapper.queryAllByNotDeleteAndCreateTime(startOfMonth,endOfMonth,township);

        List<ComplainDealSummaryAnalysisTableVo> complainDealSummaryAnalysisTableVos = new ArrayList<>();

        //先初始化一个空的，然后再循环往里面放值
        List<ComplainDealSummaryAnalysisTableVo> complainDealSummaryAnalysisTableVosEmpty = initEmptyList();
        //如果没数据，就返回一个都是null的数据的集合
        if(tComplainDeals.size() == 0) {
            return complainDealSummaryAnalysisTableVosEmpty;
        }

        Map<String, List<TComplainDealDTO>> collect = tComplainDeals.stream().collect(Collectors.groupingBy(TComplainDealDTO::getCreateTimeYear));
        ComplainDealSummaryAnalysisTableVo complainDealSummaryAnalysisTableVo1;
        for (Map.Entry<String, List<TComplainDealDTO>> stringListEntry : collect.entrySet()) {
            String key = stringListEntry.getKey();
            List<TComplainDealDTO> value = stringListEntry.getValue();
            BigDecimal count = new BigDecimal(value.size());

            // 发生量统计
            totalAmount = totalAmount.add(count);

            complainDealSummaryAnalysisTableVo1 = new ComplainDealSummaryAnalysisTableVo();
            complainDealSummaryAnalysisTableVo1.setDate(key + "月");
            // 发生量
            complainDealSummaryAnalysisTableVo1.setAmount(value.size() + "");

            // 如果有发生量
            if (value.size() > 0) {
                //办结率
                List<TComplainDealDTO> completionRateCollect = value.stream().filter(item -> "1".equals(item.getComplainStatus())).collect(Collectors.toList());

                if (completionRateCollect.size() == 0) {
                    complainDealSummaryAnalysisTableVo1.setCompletionRate("0");
                } else {
                    BigDecimal completedCount = new BigDecimal(completionRateCollect.size());

                    BigDecimal divide = completedCount.multiply(new BigDecimal(100)).divide(count, 2, BigDecimal.ROUND_HALF_UP);

                    //统计 发生率
                    totalCompletionRate = totalCompletionRate.add(completedCount);

                    complainDealSummaryAnalysisTableVo1.setCompletionRate(divide.toString());
                }

                // 及时办结率
                if( completionRateCollect.size() == 0) {
                    complainDealSummaryAnalysisTableVo1.setTimelyCompletionRate("0");
                } else {
                    int timelyCompletionRateInt = 0;
                    for (TComplainDealDTO tComplainDealDTO : completionRateCollect) {
                        String complainType = tComplainDealDTO.getComplainType();
                        Date createTime = tComplainDealDTO.getCreateTime();
                        Date updateTime = tComplainDealDTO.getUpdateTime();

                        if (complainType != null && !"".equals(complainType)
                                && createTime != null && updateTime != null) {
                            long diff = updateTime.getTime() - createTime.getTime();
                            if (diff - duration < 0) {
                                timelyCompletionRateInt ++;
                            }
                        }
                    }

                    if (timelyCompletionRateInt > 0) {
                        BigDecimal CompletionRateIntDecimal = new BigDecimal(timelyCompletionRateInt);

                        BigDecimal divide = CompletionRateIntDecimal.multiply(new BigDecimal(100)).divide(count, 2, BigDecimal.ROUND_HALF_UP);

                        //统计 及时办结率
                        totalTimelyCompletionRate = totalTimelyCompletionRate.add(CompletionRateIntDecimal);

                        complainDealSummaryAnalysisTableVo1.setTimelyCompletionRate(divide.toString());
                    } else {
                        complainDealSummaryAnalysisTableVo1.setTimelyCompletionRate("0");
                    }
                }
                // 如果没有发生量则别的都是0
            } else {
                complainDealSummaryAnalysisTableVo1.setCompletionRate("0");
                complainDealSummaryAnalysisTableVo1.setTimelyCompletionRate("0");
            }

            complainDealSummaryAnalysisTableVos.add(complainDealSummaryAnalysisTableVo1);
        }
        // 如果有数据，则往 empty集合里面放值
        if (complainDealSummaryAnalysisTableVos.size() > 0) {
            for (int i = 0; i < complainDealSummaryAnalysisTableVosEmpty.size(); i++) {
                ComplainDealSummaryAnalysisTableVo dealSummaryAnalysisTableVo = complainDealSummaryAnalysisTableVosEmpty.get(i);
                for (ComplainDealSummaryAnalysisTableVo summaryAnalysisTableVo : complainDealSummaryAnalysisTableVos) {
                    if (dealSummaryAnalysisTableVo.getDate().equals(summaryAnalysisTableVo.getDate())) {
                        dealSummaryAnalysisTableVo.setAmount(summaryAnalysisTableVo.getAmount());
                        dealSummaryAnalysisTableVo.setCompletionRate(summaryAnalysisTableVo.getCompletionRate());
                        dealSummaryAnalysisTableVo.setTimelyCompletionRate(summaryAnalysisTableVo.getTimelyCompletionRate());
                    }
                }

                //说明是 统计
                if (i == 12 ) {
                    dealSummaryAnalysisTableVo.setAmount(totalAmount.toString());

                    // 统计 办结率
                    BigDecimal divide = totalCompletionRate.multiply(new BigDecimal(100)).divide(totalAmount, 2, BigDecimal.ROUND_HALF_UP);
                    dealSummaryAnalysisTableVo.setCompletionRate(divide.toString());

                    // 统计 及时办结率
                    BigDecimal divide1 = totalTimelyCompletionRate.multiply(new BigDecimal(100)).divide(totalAmount, 2, BigDecimal.ROUND_HALF_UP);
                    dealSummaryAnalysisTableVo.setTimelyCompletionRate(divide1.toString());
                }
            }
        }
        return complainDealSummaryAnalysisTableVosEmpty;
    }

    private List<ComplainDealSummaryAnalysisTableVo> initEmptyList() {
        List<ComplainDealSummaryAnalysisTableVo> complainDealSummaryAnalysisTableVos = new ArrayList<>(13);
        ComplainDealSummaryAnalysisTableVo complainDealSummaryAnalysisTableVo;
        for (int i = 0; i < 13; i++) {
            complainDealSummaryAnalysisTableVo = new ComplainDealSummaryAnalysisTableVo();
            if (i <12) {
                complainDealSummaryAnalysisTableVo.setDate((i + 1) + "月");
            } else {
                complainDealSummaryAnalysisTableVo.setDate("统计");
            }
            complainDealSummaryAnalysisTableVo.setAmount(null);
            complainDealSummaryAnalysisTableVo.setCompletionRate(null);
            complainDealSummaryAnalysisTableVo.setTimelyCompletionRate(null);
            complainDealSummaryAnalysisTableVos.add(complainDealSummaryAnalysisTableVo);
        }
        return complainDealSummaryAnalysisTableVos;
    }

    /**
     * 统计分析导出
     * @param complainDealSummaryAnalysisTableVo c
     */
    @Override
    public void sentimentSummaryAnalysisExport(HttpServletResponse response, ComplainDealSummaryAnalysisTableVo complainDealSummaryAnalysisTableVo) throws IOException {
        List<ComplainDealSummaryAnalysisTableVo> complainDealSummaryAnalysisTableVos = sentimentSummaryAnalysisMethodTableViews(complainDealSummaryAnalysisTableVo);
        // 设置动态头
        String dynamicTitle = complainDealSummaryAnalysisTableVo.getDynamicTitle();
        List<List<String>> headList = new ArrayList<>();
        List<String> head0 = new ArrayList<>();
        head0.add(dynamicTitle);
        head0.add("日期");
        List<String> head1 = new ArrayList<>();
        head1.add(dynamicTitle);
        head1.add("发生量");
        List<String> head2 = new ArrayList<>();
        head2.add(dynamicTitle);
        head2.add("办结率");
        List<String> head3 = new ArrayList<>();
        head3.add(dynamicTitle);
        head3.add("办结及时率");
        headList.add(head0);
        headList.add(head1);
        headList.add(head2);
        headList.add(head3);

        List<List<Object>> dataList = complainDealSummaryAnalysisTableVos.stream().map(vo -> {
            List<Object> objectList = new ArrayList<>();
            objectList.add(vo.getDate());
            objectList.add(vo.getAmount());
            objectList.add(vo.getCompletionRate());
            objectList.add(vo.getTimelyCompletionRate());
            return objectList;
        }).collect(Collectors.toList());

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 设置防止中文名乱码
        String filename = URLEncoder.encode("投诉汇总分析", "utf-8");
        response.setHeader("content-disposition", "attachment;filename=" + filename + ".xlsx");

        // 先仅仅写入头，再以不写入头的方式写入数据
        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new CustomCellWriteHeightConfig())
                .registerWriteHandler(new CustomCellWriteWidthConfig()).head(headList).sheet("投诉汇总分析列表").doWrite(dataList);
    }
}
