package com.zc.business.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.zc.business.domain.DcPublishManage;
import com.zc.business.domain.export.AllEventNum;
import com.zc.business.domain.export.EventTypePublishManageMonth;
import com.zc.business.domain.export.StatisticsPublishManage;
import com.zc.business.domain.export.TrendsPublishManage;
import com.zc.business.enums.EventTypeEnum;
import com.zc.business.enums.UniversalEnum;
import com.zc.business.enums.ValueConverter;
import com.zc.business.service.IDcPublishManageService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 信息发布管理记录Controller
 *
 * @author ruoyi
 * @date 2024-04-19
 */
@RestController
@RequestMapping("/business/manage")
public class DcPublishManageController extends BaseController
{
    @Autowired
    private IDcPublishManageService dcPublishManageService;

    /**
     * 查询信息发布管理记录列表
     */
   // @PreAuthorize("@ss.hasPermi('business:manage:list')")
    @GetMapping("/list")
    public TableDataInfo list(DcPublishManage dcPublishManage)
    {
        startPage();
        List<DcPublishManage> list = dcPublishManageService.selectDcPublishManageList(dcPublishManage);
        return getDataTable(list);
    }
    /**
     * 查询事件发布详情,传参事件id
     */
 //   @PreAuthorize("@ss.hasPermi('business:manage:list')")
    @GetMapping("/listEvent")
    public AjaxResult listEvent(DcPublishManage dcPublishManage)
    {
        if (dcPublishManage.getEventId()==null|| StringUtils.isBlank(dcPublishManage.getEventId())){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return AjaxResult.success(dcPublishManageService.selectEventDcPublishManageList(dcPublishManage));
    }


    /**
     * 获取信息发布管理记录详细信息
     */
  //  @PreAuthorize("@ss.hasPermi('business:manage:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(dcPublishManageService.selectDcPublishManageById(id));
    }

    /**
     * 新增信息发布管理记录
     */
   // @PreAuthorize("@ss.hasPermi('business:manage:add')")
    @Log(title = "信息发布管理记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DcPublishManage dcPublishManage)
    {
        return toAjax(dcPublishManageService.insertDcPublishManage(dcPublishManage));
    }

    /**
     * 修改信息发布管理记录
     */
   // @PreAuthorize("@ss.hasPermi('business:manage:edit')")
    @Log(title = "信息发布管理记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DcPublishManage dcPublishManage)
    {
        return toAjax(dcPublishManageService.updateDcPublishManage(dcPublishManage));
    }

    /**
     * 删除信息发布管理记录
     */
   // @PreAuthorize("@ss.hasPermi('business:manage:remove')")
    @Log(title = "信息发布管理记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dcPublishManageService.deleteDcPublishManageByIds(ids));
    }
    //统计服务,今日发布渠道分析(只统计成功)
    @PostMapping("/statisticsPublishManage")
    public AjaxResult statisticsPublishManage()
    {
        return AjaxResult.success(dcPublishManageService.statisticsPublishManage());
    }
    @ApiOperation(value = "导出今日发布渠道分析",tags = {"ECharts导出"})
    @GetMapping("/exportStatisticsPublishManage")
    public void exportStatisticsPublishManage(HttpServletResponse response){

        List<HashMap<String,Object>> data = dcPublishManageService.statisticsPublishManage();
        List<StatisticsPublishManage> list = new ArrayList<>();
        if (data != null && data.size() > 0) {
            Long total = data.stream().mapToLong(item -> Long.parseLong(item.get("number").toString())).sum();
            for (HashMap<String, Object> datum : data) {
                StatisticsPublishManage statisticsPublishManage = new StatisticsPublishManage();
                if ("4".equals(datum.get("publishChannels").toString())){
                    statisticsPublishManage.setChannelName("情报板");
                } else if ("7".equals(datum.get("publishChannels").toString())){
                    statisticsPublishManage.setChannelName("语音广播");
                } else if ("8".equals(datum.get("publishChannels").toString())){
                    statisticsPublishManage.setChannelName("企业微信");
                }
                statisticsPublishManage.setNum(datum.get("number").toString());

                //计算百分比
                double ratio = (double) Long.parseLong(datum.get("number").toString()) / total * 100;
                ratio = Math.round(ratio * 100.0) / 100.0;
                statisticsPublishManage.setRatio(ratio + "%");
                list.add(statisticsPublishManage);
            }
        }
        ExcelUtil<StatisticsPublishManage> util = new ExcelUtil<>(StatisticsPublishManage.class);
        util.exportExcel(response, list, "今日发布渠道分析");
    }

    //统计服务,今日发布事件类型分析(只统计成功)
    @PostMapping("/eventTypePublishManage")
    public AjaxResult eventTypePublishManage()
    {
        return AjaxResult.success(dcPublishManageService.eventTypePublishManage());
    }

    @ApiOperation(value = "导出今日发布事件类型分析",tags = {"ECharts导出"})
    @GetMapping("/exportEventTypePublishManage")
    public void exportEventTypePublishManage(HttpServletResponse response){

        List<HashMap<String,Object>> data = dcPublishManageService.eventTypePublishManage();
        List<AllEventNum> list = new ArrayList<>();
        if (data != null && data.size() > 0) {
            Long total = data.stream().mapToLong(item -> Long.parseLong(item.get("number").toString())).sum();
            for (HashMap<String, Object> datum : data) {
                AllEventNum allEventNum = new AllEventNum();
                allEventNum.setEventName(ValueConverter.eventTypeName(datum.get("eventType").toString()));
                allEventNum.setNum(datum.get("number").toString());

                //计算百分比
                double ratio = (double) Long.parseLong(datum.get("number").toString()) / total * 100;
                ratio = Math.round(ratio * 100.0) / 100.0;
                allEventNum.setRatio(ratio + "%");
                list.add(allEventNum);
            }
        }
        ExcelUtil<AllEventNum> util = new ExcelUtil<>(AllEventNum.class);
        util.exportExcel(response, list, "今日发布事件类型分析");
    }

    //统计服务,今日发布趋势分析(只统计成功)
    @PostMapping("/trendsPublishManage")
    public AjaxResult releaseTrendsPublishManage()
    {
        return AjaxResult.success(dcPublishManageService.releaseTrendsPublishManage());
    }

    @ApiOperation(value = "导出今日发布趋势分析",tags = {"ECharts导出"})
    @GetMapping("/exportTrendsPublishManage")
    public void exportTrendsPublishManage(HttpServletResponse response){

        List<HashMap<String,Object>> data = dcPublishManageService.releaseTrendsPublishManage();
        List<TrendsPublishManage> list = new ArrayList<>();
        if (data != null && data.size() > 0) {
            Map<String,List<HashMap<String,Object>>> group = data.stream().collect(Collectors.groupingBy(item -> item.get("hour").toString()));
            for (String publishTime : group.keySet()) {
                TrendsPublishManage trendsPublishManage = new TrendsPublishManage();
                trendsPublishManage.setPublishTime(publishTime + "时");
                List<HashMap<String,Object>> groupData = group.get(publishTime);
                for (HashMap<String, Object> groupDatum : groupData) {
                    if ("4".equals(groupDatum.get("publishChannels").toString())){
                        trendsPublishManage.setBoard(groupDatum.get("number").toString());
                    } else if ("7".equals(groupDatum.get("publishChannels").toString())){
                        trendsPublishManage.setBroadcast(groupDatum.get("number").toString());
                    } else if ("8".equals(groupDatum.get("publishChannels").toString())){
                        trendsPublishManage.setWeChat(groupDatum.get("number").toString());
                    }
                }

                list.add(trendsPublishManage);
            }

            list = list.stream().sorted(Comparator.comparing(item ->{
                String publicTime = item.getPublishTime().substring(0,item.getPublishTime().length() -1);
                return Integer.parseInt(publicTime);
            })).collect(Collectors.toList());
        }

        ExcelUtil<TrendsPublishManage> util = new ExcelUtil<>(TrendsPublishManage.class);
        util.exportExcel(response, list, "今日发布趋势分析");
    }

    //统计服务,月发布渠道趋势分析(只统计成功的)
    @PostMapping("/monthTrendsPublishManage")
    public AjaxResult monthTrendsPublishManage(@RequestBody DcPublishManage dcPublishManage)
    {
        if (dcPublishManage==null||dcPublishManage.getPublishTime()==null){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return AjaxResult.success(dcPublishManageService.monthTrendsPublishManage(dcPublishManage));
    }

    @ApiOperation(value = "导出月发布渠道趋势分析",tags = {"ECharts导出"})
    @GetMapping("/exportMonthTrendsPublishManage")
    public void exportMonthTrendsPublishManage(HttpServletResponse response,DcPublishManage dcPublishManage){

        List<String> dates = new ArrayList<>();
        LocalDate currentDate = LocalDate.now();
        LocalDate publishLocalDate = dcPublishManage.getPublishTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        if (currentDate.getMonth() == publishLocalDate.getMonth() && currentDate.getYear() == publishLocalDate.getYear()) {
            for (int i = 1; i <= currentDate.getDayOfMonth(); i++) {
                dates.add(String.format("%d-%02d-%02d", currentDate.getYear(), currentDate.getMonthValue(), i));
            }
        } else {
            int daysInMonth = publishLocalDate.lengthOfMonth();
            for (int i = 1; i <= daysInMonth; i++) {
                dates.add(String.format("%d-%02d-%02d", publishLocalDate.getYear(), publishLocalDate.getMonthValue(), i));
            }
        }

        List<HashMap<String,Object>> data = dcPublishManageService.monthTrendsPublishManage(dcPublishManage);
        List<TrendsPublishManage> list = new ArrayList<>();
        if (data != null && data.size() > 0) {
            Map<String,List<HashMap<String,Object>>> group = data.stream().collect(Collectors.groupingBy(item -> item.get("publishTime").toString()));
            for (String publishTime : dates) {
                TrendsPublishManage trendsPublishManage = new TrendsPublishManage();
                trendsPublishManage.setPublishTime(publishTime);
                trendsPublishManage.setBoard("0");
                trendsPublishManage.setBroadcast("0");
                trendsPublishManage.setWeChat("0");
                if (group.containsKey(publishTime)) {
                    List<HashMap<String, Object>> groupData = group.get(publishTime);
                    for (HashMap<String, Object> groupDatum : groupData) {
                        if ("4".equals(groupDatum.get("publishChannels").toString())) {
                            trendsPublishManage.setBoard(groupDatum.get("number").toString());
                        } else if ("7".equals(groupDatum.get("publishChannels").toString())) {
                            trendsPublishManage.setBroadcast(groupDatum.get("number").toString());
                        } else if ("8".equals(groupDatum.get("publishChannels").toString())) {
                            trendsPublishManage.setWeChat(groupDatum.get("number").toString());
                        }
                    }
                }
                list.add(trendsPublishManage);
            }

            list = list.stream().sorted(Comparator.comparing(TrendsPublishManage::getPublishTime)).collect(Collectors.toList());
        }

        ExcelUtil<TrendsPublishManage> util = new ExcelUtil<>(TrendsPublishManage.class);
        util.exportExcel(response, list, "月发布渠道趋势分析");
    }

    //统计服务,事件类型对应的发布渠道发布的数量(只统计成功的)
    @PostMapping("/eventTypePublishManageSum")
    public AjaxResult eventTypePublishManageSum()
    {
        return AjaxResult.success(dcPublishManageService.eventTypePublishManageSum());
    }
    //统计服务,事件类型对应的发布渠道发布的数量按月统计(只统计成功的)
    @PostMapping("/eventTypePublishManageMonth")
    public AjaxResult eventTypePublishManageMonth(@RequestBody DcPublishManage dcPublishManage)
    {
        if (dcPublishManage==null||dcPublishManage.getPublishTime()==null){
            return AjaxResult.error(UniversalEnum.PARAMETER_ERROR.getValue());
        }
        return AjaxResult.success(dcPublishManageService.eventTypePublishManageMonth(dcPublishManage));
    }
    @ApiOperation(value = "导出各事件发布渠道分析",tags = {"ECharts导出"})
    @GetMapping("/exportEventTypePublishManageMonth")
    public void exportEventTypePublishManageMonth(HttpServletResponse response,DcPublishManage dcPublishManage){

        List<HashMap<String,Object>> data = dcPublishManageService.eventTypePublishManageMonth(dcPublishManage);
        List<EventTypePublishManageMonth> list = new ArrayList<>();
        if (data != null && data.size() > 0) {
            Map<String,List<HashMap<String,Object>>> group = data.stream().collect(Collectors.groupingBy(item -> item.get("eventType").toString()));
            for (EventTypeEnum value : EventTypeEnum.values()) {
                EventTypePublishManageMonth eventTypePublishManageMonth = new EventTypePublishManageMonth();
                eventTypePublishManageMonth.setTypeName(value.getInfo());
                if (group.containsKey(String.valueOf(value.getCode()))){
                    List<HashMap<String,Object>> groupData = group.get(String.valueOf(value.getCode()));
                    for (HashMap<String, Object> groupDatum : groupData) {
                        if ("4".equals(groupDatum.get("publishChannels").toString())){
                            eventTypePublishManageMonth.setBoard(groupDatum.get("number").toString());
                        } else if ("7".equals(groupDatum.get("publishChannels").toString())){
                            eventTypePublishManageMonth.setBroadcast(groupDatum.get("number").toString());
                        } else if ("8".equals(groupDatum.get("publishChannels").toString())){
                            eventTypePublishManageMonth.setWeChat(groupDatum.get("number").toString());
                        }
                    }
                }
                list.add(eventTypePublishManageMonth);
            }

        }

        ExcelUtil<EventTypePublishManageMonth> util = new ExcelUtil<>(EventTypePublishManageMonth.class);
        util.exportExcel(response, list, "各事件发布渠道分析");
    }

    /**
     * 公众服务统计查询
     */
    @PostMapping("/statisticsList")
    public TableDataInfo statisticsList(@RequestBody DcPublishManage dcPublishManage)
    {
        startPage();
        List<DcPublishManage> list = dcPublishManageService.selectDcPublishManageStatistics(dcPublishManage);
        return getDataTable(list);
    }

    @PostMapping("/statisticsListNoPage")
    public AjaxResult statisticsListNoPage(@RequestBody DcPublishManage dcPublishManage)
    {
        return AjaxResult.success(dcPublishManageService.selectDcPublishManageStatistics(dcPublishManage));
    }
    /**
     * 公众服务统计导出
     */
    //@PreAuthorize("@ss.hasPermi('business:manage:export')")
    @Log(title = "信息发布管理记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,@RequestBody DcPublishManage dcPublishManage) throws UnsupportedEncodingException {
        List<DcPublishManage> list = dcPublishManageService.selectDcPublishManageExport(dcPublishManage);
        ExcelUtil<DcPublishManage> util = new ExcelUtil<>(DcPublishManage.class);
        util.exportExcel(response, list, UniversalEnum.INFORMATION_RELEASE_MANAGEMENT_RECORD_DATA.getValue());
    }
    //同步位置数据
    @PostMapping("/manage")
    public void selectDcPublishManage()   {
        dcPublishManageService.selectDcPublishManage();
    }

}