package com.ruoyi.web.controller.wocom;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.CorpContextHolder;
import com.ruoyi.excel.wecom.helper.HandleAllData;
import com.ruoyi.excel.wecom.mapper.CustomerExportDataMapper;
import com.ruoyi.excel.wecom.mapper.CustomerStatisticsDataMapper;
import com.ruoyi.excel.wecom.mapper.DepartmentStatisticsDataMapper;
import com.ruoyi.excel.wecom.service.WecomTagService;
import com.ruoyi.excel.wecom.vo.CustomerExportDataVO;
import com.ruoyi.excel.wecom.vo.CustomerStatisticsDataVO;
import com.ruoyi.excel.wecom.vo.DepartmentStatisticsDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 企业微信客户联系Controller
 */
@RestController
@RequestMapping("/wecom/contact")
public class WecomContactController {
    @Autowired
    private WecomTagService wecomTagService;

    @Autowired
    private HandleAllData handleAllData;

    @Autowired
    private CustomerExportDataMapper customerExportDataMapper;

    @Autowired
    private DepartmentStatisticsDataMapper departmentStatisticsDataMapper;

    @Autowired
    private CustomerStatisticsDataMapper customerStatisticsDataMapper;

    @Autowired
    private RedisCache redisCache;


    @GetMapping("/init")
    public AjaxResult init(HttpServletRequest request) throws IOException {
        try {
            handleAllData.initData();
            return AjaxResult.success();
        } finally {
            CorpContextHolder.clear();
        }
    }

    @GetMapping("/test")
    public AjaxResult test(HttpServletRequest request) throws IOException {
        try {
            handleAllData.handleAllData();
            return AjaxResult.success();
        } finally {
            CorpContextHolder.clear();
        }
    }

    @GetMapping("/createAllReportData")
    public AjaxResult createAllReportData(HttpServletRequest request) throws IOException {
        try {
            handleAllData.createAllReportData();
            return AjaxResult.success();
        } finally {
            CorpContextHolder.clear();
        }
    }

    @GetMapping("/createAllDepartmentReportData")
    public AjaxResult createAllDepartmentReportData(HttpServletRequest request) throws IOException {
        try {
            handleAllData.createAllDepartmentReportData();
            return AjaxResult.success();
        } finally {
            CorpContextHolder.clear();
        }
    }

    @GetMapping("/createAllDepartmentReportByDate")
    public AjaxResult createAllDepartmentReportByDate(@RequestParam(value = "date", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) throws IOException {
        try {
            String corpId = CorpContextHolder.getCurrentCorpId();
            handleAllData.createDepartmentReportData(corpId,date);
            return AjaxResult.success();
        } finally {
            CorpContextHolder.clear();
        }
    }

    /**
     * 导出客户数据
     *
     * @param response HttpServletResponse
     * @param startDate 开始日期(可选)
     * @param endDate 结束日期(可选)
     */
    @GetMapping("/exportCustomerData")
    public void exportCustomerData(
            HttpServletResponse response,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        try {
            String corpId = CorpContextHolder.getCurrentCorpId();

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("客户数据_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel流式导出
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), CustomerExportDataVO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("客户数据").build();

            // 分批查询并写入,避免内存溢出
            List<CustomerExportDataVO> dataList = customerExportDataMapper.selectCustomerExportDataVOList(corpId,startDate, endDate,null);
            excelWriter.write(dataList, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println("{\"code\":500,\"msg\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {
            CorpContextHolder.clear();
        }
    }

    /**
     * 导出流量看板统计数据
     *
     * @param response HttpServletResponse
     * @param startDate 开始日期(可选)
     * @param endDate 结束日期(可选)
     * @param indicatorName 指标(可选)
     */
    @GetMapping("/exportCustomerStatistics")
    public void exportCustomerStatistics(
            HttpServletResponse response,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) String indicatorName) {
        try {
            String corpId = CorpContextHolder.getCurrentCorpId();

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("部门统计数据_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel流式导出
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), CustomerStatisticsDataVO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("流量看板统计数据").build();

            // 分批查询并写入,避免内存溢出
            List<CustomerStatisticsDataVO> dataList = customerStatisticsDataMapper.selectCustomerStatisticsDataVOList(corpId,
                    startDate, endDate, indicatorName);
            excelWriter.write(dataList, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println("{\"code\":500,\"msg\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {
            CorpContextHolder.clear();
        }
    }

    /**
     * 导出部门统计数据
     *
     * @param response HttpServletResponse
     * @param startDate 开始日期(可选)
     * @param endDate 结束日期(可选)
     * @param departmentPath 部门路径(可选)
     */
    @GetMapping("/exportDepartmentStatistics")
    public void exportDepartmentStatistics(
            HttpServletResponse response,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(required = false) String departmentPath) {
        try {
            String corpId = CorpContextHolder.getCurrentCorpId();

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("部门统计数据_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel流式导出
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), DepartmentStatisticsDataVO.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("部门统计数据").build();

            // 分批查询并写入,避免内存溢出
            List<DepartmentStatisticsDataVO> dataList = departmentStatisticsDataMapper.selectDepartmentStatisticsDataVOList(corpId,
                    startDate, endDate, departmentPath);
            excelWriter.write(dataList, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            try {
                response.getWriter().println("{\"code\":500,\"msg\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {
            CorpContextHolder.clear();
        }
    }

}
