package cn.com.ctop.job.kuaishou.handler;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.Project;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IProjectService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouVideoGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouProjectVideoGetService;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 清洗项目素材
 *
 * @param
 * @author ZHAOXA
 * @return
 * @throws
 */
@Slf4j
@Component
public class KuaishouProjectVideoGetJob {
    @Autowired
    private IKuaishouProjectVideoGetService projectVideoGetService;
    @Autowired
    private IKuaiShouVideoGetService videoGetService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private ICtopOauthTokenService tokenService;

    static ExecutorService executorService = Executors.newFixedThreadPool(10);

    /**
     * 清洗项目素材
     * @throws Exception
     */
    @XxlJob("kuaishouProjectVideoGetJob")
    public void execute() throws Exception {
        log.info("同步素造素材供应商-------start");
        kuaishouSupplierVideoGet();
        Thread.sleep(60000);
        log.info("清洗项目素材-------start");
        kuaishouProjectVideoGet();
    }


    /**
     * 获取供应商信息
     */
    private void kuaishouSupplierVideoGet() {
        List<JSONObject> datas = videoGetService.getAccountIds();
        for (JSONObject data : datas) {
            CtopOauthToken token = tokenService.getTokenByAccountId(data.getLong("accountId"));
            if (Check.isNull(token)) {
                continue;
            }
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    videoGetService.getSuZaoList(token.getAccessToken(), data.getLong("accountId"), 1, data.getString("startDate"));
                }
            });
        }
        XxlJobHelper.log("同步素造素材供应商完成");
    }

    /**
     * 素材清洗
     */
    private void kuaishouProjectVideoGet() {
        //2快手，1开启的项目
        List<Project> projects = projectService.listByMediaType(2, 0);
        projects.forEach(project -> executorService.submit(() -> {
            projectVideoGetService.clearProjectVideo(project.getId(), 1, null);
        }));
        XxlJobHelper.log("清洗项目素材完成");
    }

}
