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

import cn.iocoder.yudao.framework.apollo.core.event.export.OrderExcelExportEvent;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO;
import cn.iocoder.yudao.module.order.service.order.OrderQueryService;
import cn.iocoder.yudao.module.order.vo.order.OrderQueryVO;
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.IOException;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;


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

    private final OrderQueryService orderQueryService;
    /**
     * 订单导出监听
     *
     * @param event 编号记录
     */
//    @EventListener(OrderExcelExportEvent.class)
//    public void orderExcelExportEvent(OrderExcelExportEvent event) throws IOException {
//        if (StringUtils.isNotBlank(event.getRequestParams())){
//            try {
//                OrderQueryVO query = JSONObject.parseObject(event.getRequestParams(), OrderQueryVO.class);
//                query.setLang(event.getLang());
//                FileDO fileDO = orderQueryService.makeOrderExcelFile(event.getUserId(), event.getUserType(), query);
//                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");
//        }
//
//    }

    @EventListener(OrderExcelExportEvent.class)
    public void MyOrderExcelExportEvent(OrderExcelExportEvent event) throws IOException {
        if (StringUtils.isNotBlank(event.getRequestParams())){
            try {
                OrderQueryVO query = JSONObject.parseObject(event.getRequestParams(), OrderQueryVO.class);
                query.setLang(event.getLang());
                FileDO fileDO = orderQueryService.makeMyOrderExcelFile(event.getUserId(), event.getUserType(), query);
                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");
        }

    }
}
