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

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.apollo.core.event.export.ExceptionOrderExcelExportEvent;
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.service.order.OrderQueryService;
import cn.iocoder.yudao.module.order.service.orderException.OrderExceptionService;
import cn.iocoder.yudao.module.order.vo.orderException.OrderExceptionExcelVO;
import cn.iocoder.yudao.module.order.vo.orderException.OrderExceptionQueryVO;
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 java.util.stream.Collectors;

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


/**
 * 异常订单excel导出监听
 *
 * @author paddy
 */
@Component("ExceptionOrderExcelExportListener")
@AllArgsConstructor
@Slf4j
public class ExceptionOrderExcelExportListener {
    private UeProperties ueProperties;
    private FileService fileService;
    private OrderExceptionService orderExceptionService;

    /**
     * 订单导出监听
     *
     * @param event 编号记录
     */
    @EventListener(ExceptionOrderExcelExportEvent.class)
    public void exceptionOrderExcelExportEvent(ExceptionOrderExcelExportEvent event) {
        if (StringUtils.isNotBlank(event.getRequestParams())) {
            try {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATA_FORMAT);
                String nowTime = formatter.format(LocalDateTime.now());
                OrderExceptionQueryVO query = JSONObject.parseObject(event.getRequestParams(), OrderExceptionQueryVO.class);
                if (StrUtil.isNotBlank(query.getSalesmanId())) {
                    //得到跟进客服对应的所有客户经理
                    List<String> serviceIdList = orderExceptionService.getCustomerServiceListById(Long.parseLong(query.getSalesmanId()));
                    List<String> customerServiceList = query.getCustomerIds();
                    if (null == customerServiceList) {
                        customerServiceList = new ArrayList<>();
                    }
                    customerServiceList.addAll(serviceIdList);
                    List list = customerServiceList.stream().distinct().collect(Collectors.toList());
                    query.setCustomerIds(list);
                }
                List<OrderExceptionExcelVO> list = orderExceptionService.getOrderExceptionExcelList(query);
                String sheetName = event.getLang() == 0 ? "异常订单" : "Order exception";
                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, OrderExceptionExcelVO.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) {
                event.setResult("异常订单导出错误：" + e);
            }
        } else {
            event.setResult("param fail");
        }

    }
}
