package com.yc.ship.module.trade.job;

import com.yc.ship.framework.quartz.core.handler.JobHandler;
import com.yc.ship.framework.tenant.core.aop.TenantIgnore;
import com.yc.ship.framework.tenant.core.util.TenantUtils;
import com.yc.ship.module.trade.service.insurance.InsuranceService;
import com.yc.ship.module.trade.service.order.TradeOrderRepositoryService;
import com.yc.ship.module.trade.service.order.TradeOrderService;
import com.yc.ship.module.trade.service.order.TradeVisitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 保险购买定时任务
 * 1. 查询需要购买保险的订单，只有确认状态并且开航前一天才可购买保险
 */
@Component
@Slf4j
public class InsuranceApplyJob implements JobHandler {

    @Resource
    private InsuranceService insuranceService;

    @Resource
    private TradeOrderService tradeOrderService;

    @Resource
    private TradeVisitorService tradeVisitorService;

    @Resource
    private TradeOrderRepositoryService tradeOrderRepositoryService;

    /**
     * 执行定时任务
     * 定时购买保险
     */
    @Override
    public String execute(String param) {
        log.info("开始执行保险购买定时任务");
        TenantUtils.execute(1L, () -> {
            List<Long> orderIdList = tradeOrderService.getCanBuyInsuranceOrder();
            List<Long> visitorIdList = tradeVisitorService.getNotInsureByOrderIds(orderIdList);
            visitorIdList.stream().forEach(visitorId -> {
                log.info("开始执行保险购买定时任务,visitorId{}", visitorId);
                try {
                    insuranceService.applyInsuranceNew(visitorId);
                }catch (Exception e) {
                    log.error("保险购买定时任务异常,游客id{}", visitorId, e);
                }
            });
        });
        log.info("结束执行保险购买定时定时任务");
        return "success";
    }
}
