package com.cmeeting.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmeeting.annotation.OperLog;
import com.cmeeting.pojo.SysUserSyncCategory;
import com.cmeeting.service.IUserAccessRecordService;
import com.cmeeting.service.MeetingInfoService;
import com.cmeeting.service.SysUserSyncService;
import com.cmeeting.util.R;
import com.cmeeting.util.page.PageUtil;
import com.cmeeting.vo.StatisticVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author zhang kaishi
 * @Date 2025/7/18 9:36
 **/
@RestController
@RequestMapping("/statistics")
@Slf4j
public class StatisticsController {

    @Resource
    private MeetingInfoService meetingInfoService;
    @Resource
    private SysUserSyncService sysUserSyncService;
    @Resource
    private IUserAccessRecordService iUserAccessRecordService;

    /**
     * 纪要模板使用情况的统计
     * @param searchValue     用户部门或工号
     * @param createTimeStart 开始时间
     * @param createTimeEnd   结束时间
     * @return
     */
    @GetMapping("/recordTemplateUsingInfo")
    public R recordTemplateUsingInfo(String searchValue,
                                     @RequestParam("createTimeStart") Date createTimeStart,
                                     @RequestParam("createTimeEnd") Date createTimeEnd) {

        List<Map<String, String>> list =meetingInfoService.statistics(searchValue, createTimeStart, createTimeEnd, true);

        return PageUtil.getDataTable(list);
    }

    /**
     * 纪要模板使用情况的统计
     * @param searchValue     用户部门或工号
     * @param createTimeStart 开始时间
     * @param createTimeEnd   结束时间
     * @return
     */
    @OperLog(location = "统计日志", operation = "导出统计日志")
    @GetMapping("/exportRecordTemplateUsingInfo")
    public R exportRecordTemplateUsingInfo(String searchValue,
                                           @RequestParam("createTimeStart") Date createTimeStart,
                                           @RequestParam("createTimeEnd") Date createTimeEnd,
                                           HttpServletResponse response) {

        meetingInfoService.exportRecordTemplateUsingInfo(searchValue, createTimeStart, createTimeEnd, response);

        return R.ok();
    }

    @PostMapping("/recordByCompany")
    public R recordByCompany(@Validated @RequestBody StatisticVO vo) throws ParseException {
        List<SysUserSyncCategory> tree = sysUserSyncService.getTreeList();
        String search = vo.getSearch();
        if (StrUtil.isNotBlank(search)) {
            tree = tree.stream().filter(e -> search.equals(e.getDeptId()) || e.getPath().contains(search)).collect(Collectors.toList());
        }
        Map<String, String> collect = tree.stream().collect(Collectors.toMap(SysUserSyncCategory::getDeptId, SysUserSyncCategory::getPath));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list = meetingInfoService.statisticsEmail(
                simpleDateFormat1.parse(simpleDateFormat.format(vo.getStartTime()) + " 00:00:00"),
                simpleDateFormat1.parse(simpleDateFormat.format(vo.getEndTime()) + " 23:59:59"), collect);

        return PageUtil.getDataTable(list);
    }
    @PostMapping("/exportRecordByCompany")
    public void exportRecordByCompany(@Validated @RequestBody StatisticVO vo, HttpServletResponse response) throws ParseException, IOException {
        String search = vo.getSearch();
        List<SysUserSyncCategory> tree = sysUserSyncService.getTreeList();
        if (StrUtil.isNotBlank(search)) {
            tree = tree.stream().filter(e -> search.equals(e.getDeptId()) || e.getPath().contains(search)).collect(Collectors.toList());
        }
        Map<String, String> collect = tree.stream().collect(Collectors.toMap(SysUserSyncCategory::getDeptId, SysUserSyncCategory::getPath));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String title = "会议使用次数统计(按公司)";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = String.format("%s.xlsx", title);
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf8"));
        meetingInfoService.statisticsEmail(title,  simpleDateFormat1.parse(simpleDateFormat.format(vo.getStartTime()) + " 00:00:00"),
                simpleDateFormat1.parse(simpleDateFormat.format(vo.getEndTime()) + " 23:59:59"), response.getOutputStream(), collect);
    }

    @PostMapping("/userAccessRecord")
    public R userAccessRecord(@Validated @RequestBody StatisticVO vo){
        return R.ok(iUserAccessRecordService.statistics(vo.getSearch(), vo.getStartTime(), vo.getEndTime(), vo.getCurrent(), vo.getSize()));
    }
    @PostMapping("/exportUserAccessRecord")
    public void exportUserAccessRecord(@Validated @RequestBody StatisticVO vo, HttpServletResponse response){
        Page<Map<String, String>> statistics = iUserAccessRecordService.statistics(vo.getSearch(), vo.getStartTime(), vo.getEndTime(), vo.getCurrent(), vo.getSize());
        List<String> dateList = DateUtil.rangeToList(vo.getStartTime(), vo.getEndTime(), DateField.DAY_OF_YEAR).stream()
                .map(date -> DateUtil.format(date, "yyyy-MM-dd"))
                .collect(Collectors.toList());
        iUserAccessRecordService.exportUserAccessRecord(statistics.getRecords(), dateList, response);
    }
    @PostMapping("/userAccessRecordByCompany")
    public R userAccessRecordByCompany(@Validated @RequestBody StatisticVO vo){
        String search = vo.getSearch();
        List<SysUserSyncCategory> treeList = sysUserSyncService.getTreeList();
        if (StrUtil.isNotBlank(search)) {
            treeList = treeList.stream().filter(e -> search.equals(e.getDeptId()) || e.getPath().contains(search)).collect(Collectors.toList());
        }
        List<String> collect = treeList.stream().map(SysUserSyncCategory::getPath).collect(Collectors.toList());

        if (CollUtil.isEmpty(collect)) {
            return R.ok(new ArrayList<>());
        }
        return R.ok(iUserAccessRecordService.statisticsByCompany(vo.getStartTime(), vo.getEndTime(), collect));
    }
    @PostMapping("/exportUserAccessRecordByCompany")
    public void exportUserAccessRecordByCompany(@Validated @RequestBody StatisticVO vo, HttpServletResponse response) throws IOException {
        String search = vo.getSearch();
        List<SysUserSyncCategory> treeList = sysUserSyncService.getTreeList();
        if (StrUtil.isNotBlank(search)) {
            treeList = treeList.stream().filter(e -> search.equals(e.getDeptId()) || e.getPath().contains(search)).collect(Collectors.toList());
        }
        List<String> collect = treeList.stream().map(SysUserSyncCategory::getPath).collect(Collectors.toList());

        List<String> dateList = DateUtil.rangeToList(vo.getStartTime(), vo.getEndTime(), DateField.DAY_OF_YEAR).stream()
                .map(date -> DateUtil.format(date, "yyyy-MM-dd"))
                .collect(Collectors.toList());
        List<Map<String, String>> data = iUserAccessRecordService.statisticsByCompany(vo.getStartTime(), vo.getEndTime(), collect);
        iUserAccessRecordService.exportUserAccessRecordByCompany(data, dateList, response);
    }


}
