package com.xiang.xservice.application.script.fwd.schedule;

import com.alibaba.fastjson.JSON;
import com.xiang.xmc.service.schedule.service.IDynamicTaskSchedulerService;
import com.xiang.xservice.application.script.fwd.entity.param.FwdOrderTaskParam;
import com.xiang.xservice.application.script.fwd.entity.pojo.FAudienceConfig;
import com.xiang.xservice.application.script.fwd.entity.pojo.FUserConfig;
import com.xiang.xservice.application.script.fwd.mapper.FwdAudienceConfigMapper;
import com.xiang.xservice.application.script.fwd.mapper.FwdUserConfigMapper;
import com.xiang.xservice.application.script.fwd.service.IPerformService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class TicketGrabTask implements Runnable {

    private final FwdUserConfigMapper userConfigMapper;
    private final FwdAudienceConfigMapper audienceConfigMapper;
    private final IPerformService performService;
    private final FwdOrderTaskParam param;
    private final IDynamicTaskSchedulerService dynamicTaskSchedulerService;

    public TicketGrabTask(FwdUserConfigMapper userConfigMapper, FwdAudienceConfigMapper audienceConfigMapper,
                          IPerformService performService, FwdOrderTaskParam param,
                          IDynamicTaskSchedulerService dynamicTaskSchedulerService) {
        this.userConfigMapper = userConfigMapper;
        this.audienceConfigMapper = audienceConfigMapper;
        this.performService = performService;
        this.param = param;
        this.dynamicTaskSchedulerService = dynamicTaskSchedulerService;
    }

    @Override
    public void run() {
        try {
            log.info("【TicketGrabTask】 run start. 获取到参数:{}", JSON.toJSONString(param));
            dynamicTaskSchedulerService.updateProcess(param.getTaskId());
            List<FUserConfig> availableUser = userConfigMapper.getAvailableUser();
            if (CollectionUtils.isEmpty(availableUser)) {
                return;
            }
            for (FUserConfig userConfig : availableUser) {
                List<FAudienceConfig> audiences = audienceConfigMapper.getAudienceByUserId(userConfig.getId());
                try {
                    performService.createProjectOrder(param.getProjectId(), audiences.stream().map(FAudienceConfig::getFrequentId).collect(Collectors.toList()), userConfig.getToken());
                    dynamicTaskSchedulerService.finishTask(param.getTaskId());
                } catch (Exception e) {
                    log.error("创建订单失败", e);
                    dynamicTaskSchedulerService.errTask(param.getTaskId());
                }
            }
        } catch (Exception e) {
            log.error("任务调度运行失败", e);
            dynamicTaskSchedulerService.errTask(param.getTaskId());
        }
    }
}
