package cn.iocoder.yudao.module.order.listener.export;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apollo.core.event.export.ExceptionOrderStatisticsExcelExportEvent;
import cn.iocoder.yudao.framework.excel.util.ExcelUtils;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO;
import cn.iocoder.yudao.module.infra.service.file.FileService;
import cn.iocoder.yudao.module.order.dto.OrderQueryDTO;
import cn.iocoder.yudao.module.order.service.order.OrderQueryService;
import cn.iocoder.yudao.module.order.vo.order.OrderQueryVO;
import cn.iocoder.yudao.module.order.vo.orderException.OrderExceptionStatisticsExcelVo;
import cn.iocoder.yudao.module.system.framework.ue.UeProperties;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static cn.iocoder.yudao.framework.excel.constant.ExportConstant.DATA_FORMAT;


/**
 * 异常订单统计excel导出监听
 *
 * @author zhengYi
 */
@Component("ExceptionOrderStatisticsExcelExportListener")
@AllArgsConstructor
@Slf4j
public class ExceptionOrderStatisticsExcelExportListener {

    private final OrderQueryService orderQueryService;
    private UeProperties ueProperties;
    private FileService fileService;
    /**
     * 订单导出监听
     *
     * @param event 编号记录
     */
    @EventListener(ExceptionOrderStatisticsExcelExportEvent.class)
    public void exceptionOrderStatisticsExcelExportEvent(ExceptionOrderStatisticsExcelExportEvent event) {
        if (StringUtils.isNotBlank(event.getRequestParams())){
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATA_FORMAT);
                String nowTime = formatter.format(LocalDateTime.now());
                OrderQueryDTO query = JSONObject.parseObject(event.getRequestParams(), OrderQueryDTO.class);
                query.setLang(event.getLang());
                List<OrderExceptionStatisticsExcelVo> list = orderQueryService.getOrderExceptionStatisticsExcel(query);
                String sheetName = event.getLang() == 0 ? "异常单统计" : "Order exception statistics";
                String dir = ueProperties.getTempDir().concat("/exception/excel/");
                String fileName = event.getUserId().toString().concat(StrUtil.DASHED).concat(event.getUserType().toString()).concat(StrUtil.DASHED).concat(nowTime).concat("exception_order.xlsx");
                String path = ExcelUtils.write(dir, fileName, sheetName, OrderExceptionStatisticsExcelVo.class, list);
                // 获取到临时文件
                File file = new File(path);
                // 创建FileInputStream对象
                FileInputStream fileInputStream = new FileInputStream(file);
                // 读取文件内容
                byte[] fileBytes = new byte[(int) file.length()];
                fileInputStream.read(fileBytes);
                // 关闭文件流
                fileInputStream.close();
                // 将文件上传到资源服务器
                FileDO fileDO = fileService.createFile(dir, fileName, fileBytes);
                event.setPath(fileDO.getPath());
                event.setFileName(fileDO.getPath());
                event.setUrl(fileDO.getUrl());
                event.setFileId(fileDO.getId());
            }catch (Exception e){
                // TODO 测试阶段打印堆栈错误信息，便于分析原因
                e.printStackTrace();
                event.setResult(e.getMessage());
            }
        }else {
            event.setResult("param fail");
        }

    }
}
