package com.ruoyi.web.controller.wocom;

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.CorpContextHolder;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.excel.wecom.domain.CustomerExportData;
import com.ruoyi.excel.wecom.service.CustomerExportAsyncService;
import com.ruoyi.excel.wecom.service.ICustomerExportDataService;
import com.ruoyi.excel.wecom.vo.CustomerExportDataVO;
import com.ruoyi.system.domain.SysExportTask;
import com.ruoyi.system.service.ISysExportTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * 客户统计数据Controller
 */
@RestController
@RequestMapping("/wecom/customerExport")
public class CustomerExportDataController extends BaseController
{
    @Autowired
    private ICustomerExportDataService customerExportDataService;

    @Autowired
    private CustomerExportAsyncService customerExportAsyncService;

    @Autowired
    private ISysExportTaskService exportTaskService;

    /**
     * 查询客户统计数据列表
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerExport:list')")
    @GetMapping("/list")
    public TableDataInfo list(
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(value = "customerName", required = false) String customerName)
    {
        String corpId = CorpContextHolder.getCurrentCorpId();

        startPage();
        List<CustomerExportData> list = customerExportDataService.selectCustomerExportDataList(corpId, startDate, endDate, customerName);
        return getDataTable(list);
    }

    /**
     * 导出客户统计数据列表（同步方式，保留兼容）
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerExport:export')")
    @Log(title = "客户统计数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                       @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                       @RequestParam(value = "customerName", required = false) String customerName)
    {
        String corpId = CorpContextHolder.getCurrentCorpId();

        List<CustomerExportDataVO> list = customerExportDataService.selectCustomerExportDataVOList(corpId, startDate, endDate, customerName);
        ExcelUtil<CustomerExportDataVO> util = new ExcelUtil<>(CustomerExportDataVO.class);
        util.exportExcel(response, list, "客户统计数据");
    }

    /**
     * 异步导出客户统计数据列表
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerExport:export')")
    @Log(title = "客户统计数据-异步导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAsync")
    public AjaxResult exportAsync(
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
            @RequestParam(value = "customerName", required = false) String customerName)
    {
        String corpId = CorpContextHolder.getCurrentCorpId();

        SysExportTask task = new SysExportTask();
        task.setTaskName("客户统计数据导出");
        task.setTaskType("customer_export");
        task.setCorpId(corpId);
        task.setCreateBy(getUsername());

        Long taskId = exportTaskService.createExportTask(task);

        customerExportAsyncService.executeExport(taskId, corpId, startDate, endDate, customerName);

        return AjaxResult.success("导出任务已创建，请稍后查看进度", taskId);
    }

    /**
     * 查询导出任务状态
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerExport:export')")
    @GetMapping("/export/status/{taskId}")
    public AjaxResult getExportStatus(@PathVariable Long taskId)
    {
        SysExportTask task = exportTaskService.selectExportTaskById(taskId);
        if (task == null)
        {
            return AjaxResult.error("任务不存在");
        }
        return AjaxResult.success(task);
    }

    /**
     * 下载导出文件
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerExport:export')")
    @GetMapping("/export/download/{taskId}")
    public void downloadExportFile(@PathVariable Long taskId, HttpServletResponse response)
    {
        SysExportTask task = exportTaskService.selectExportTaskById(taskId);
        if (task == null)
        {
            return;
        }

        if (!SysExportTask.STATUS_SUCCESS.equals(task.getStatus()))
        {
            return;
        }

        String filePath = task.getFilePath();
        if (filePath == null || filePath.isEmpty())
        {
            return;
        }

        File file = new File(filePath);
        if (!file.exists())
        {
            return;
        }

        try
        {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode(task.getFileName(), StandardCharsets.UTF_8.toString()).replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";filename*=utf-8''" + fileName);
            response.setHeader("Content-Length", String.valueOf(file.length()));

            java.io.FileInputStream fis = new java.io.FileInputStream(file);
            java.io.OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1)
            {
                os.write(buffer, 0, bytesRead);
            }
            fis.close();
            os.flush();
        }
        catch (Exception e)
        {
            logger.error("下载文件失败", e);
        }
    }

    /**
     * 查询导出任务列表
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerExport:export')")
    @GetMapping("/export/list")
    public TableDataInfo exportTaskList(SysExportTask task)
    {
        String corpId = CorpContextHolder.getCurrentCorpId();
        task.setCorpId(corpId);
        task.setCreateBy(getUsername());
        startPage();
        List<SysExportTask> list = exportTaskService.selectExportTaskList(task);
        return getDataTable(list);
    }

    /**
     * 删除导出任务
     */
    @PreAuthorize("@ss.hasPermi('wecom:customerExport:export')")
    @Log(title = "客户统计数据-删除导出任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/export/{taskId}")
    public AjaxResult deleteExportTask(@PathVariable Long taskId)
    {
        SysExportTask task = exportTaskService.selectExportTaskById(taskId);
        if (task == null)
        {
            return AjaxResult.error("任务不存在");
        }

        if (task.getFilePath() != null && !task.getFilePath().isEmpty())
        {
            File file = new File(task.getFilePath());
            if (file.exists())
            {
                file.delete();
            }
        }

        return toAjax(exportTaskService.deleteExportTaskById(taskId));
    }
}
