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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apollo.core.event.export.ContainerNumberOrderExcelExportEvent;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.util.ExcelUtils;
import cn.iocoder.yudao.framework.i18n.core.I18nMessage;
import cn.iocoder.yudao.framework.mybatis.core.vo.PageVO;
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.OrderCostSummaryDto;
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.OrderBackPageVO;
import cn.iocoder.yudao.module.order.vo.order.OrderQueryVO;
import cn.iocoder.yudao.module.order.vo.order.OrderSaleRepayExcelVo;
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.ArrayList;
import java.util.List;

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


/**
 * 自编号订单excel导出监听
 *
 * @author zhengYi
 */
@Component("ContainerNumberOrderExcelExportListener")
@AllArgsConstructor
@Slf4j
public class ContainerNumberOrderExcelExportListener {

    private final OrderQueryService orderQueryService;
    private UeProperties ueProperties;
    private FileService fileService;

    /**
     * 订单导出监听
     *
     * @param event 编号记录
     */
    @EventListener(ContainerNumberOrderExcelExportEvent.class)
    public void containerNumberOrderExcelExportEvent(ContainerNumberOrderExcelExportEvent event) {
        if (StringUtils.isNotBlank(event.getRequestParams())) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATA_FORMAT);
                String nowTime = formatter.format(LocalDateTime.now());
                PageVO page = new PageVO();
                page.setRows(10000);
                page.setPage(1);
                OrderQueryDTO query = JSONObject.parseObject(event.getRequestParams(), OrderQueryDTO.class);
                query.setLang(event.getLang());
                PageResult<OrderBackPageVO> orderPage = orderQueryService.myOrderPage(query, page);
                if (CollectionUtil.isNotEmpty(orderPage.getList())) {
                    String nameZh = String.format("自编号%s的订单费用汇总统计", query.getContainerNumber());
                    String nameEn = String.format("Summary Statistics of Order Expenses from ID%s", query.getContainerNumber());
                    List<OrderCostSummaryDto> orderCostSummaryDtoList = new ArrayList<>();
                    for (int i = 0; i < orderPage.getList().size(); i++) {
                        OrderBackPageVO back = orderPage.getList().get(i);
                        OrderCostSummaryDto summaryDto = orderQueryService.getOrderCostSummaryDto(null, back);
                        summaryDto.setNo(String.valueOf(i + 1));
                        orderCostSummaryDtoList.add(summaryDto);
                    }
                    String sheetName = I18nMessage.getLang() == 0 ? nameZh : nameEn;
                    String dir = ueProperties.getTempDir().concat("/container—number/excel/");
                    // TODO 文件唯一可覆盖，这里比较特别的，自编号是唯一的，文件名称不用携带用户属性，此自编号导出的excel文件始终保持最新的即可
                    String fileName = query.getContainerNumber().concat(".xlsx");
                    String path = ExcelUtils.write(dir, fileName, sheetName, OrderCostSummaryDto.class, orderCostSummaryDtoList);
                    // 获取到临时文件
                    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());
                }else {
                    event.setResult("data is empty");
                }
            } catch (Exception e) {
                // TODO 测试阶段打印堆栈错误信息，便于分析原因
                e.printStackTrace();
                event.setResult(e.getMessage());
            }
        } else {
            event.setResult("param fail");
        }

    }
}
