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

import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouAppPackageService;
import com.alibaba.fastjson.JSONArray;
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;

@Slf4j
@Component
public class KuaishouAutoSynchronousProjectMaterialJob {
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private IKuaishouAppPackageService kuaishouAppPackageService;
    static ExecutorService executorService = Executors.newFixedThreadPool(5);

    @XxlJob("autoSynchronousProjectMaterialJob")
    public void execute() {
        List<UserAllocation> userAllocations = userAllocationService.listByMediaId("2", 0);
        userAllocations.forEach(userAllocation -> executorService.submit(() ->
                synchronMaterials(userAllocation.getMaterialType(), userAllocation.getAccountId(), userAllocation.getProjectId())
        ));
        XxlJobHelper.log("快手物料数据同步完成");
    }


    private void synchronMaterials(String materialType, Long accountId, Long projectId) {
        if (!Check.isNull(materialType) && materialType.contains("1")) {
            JSONArray accountIds = new JSONArray();
            accountIds.add(accountId);
            //1 有效项目模板
            List<Long> ids = kuaishouAppPackageService.queryByAppVersion(projectId, null, 1);
            log.info("同步账户应用,应用模板={}", ids);
            if (!Check.isNull(ids)) {
                for (Long id : ids) {
                    kuaishouAppPackageService.pushAppPackage(id, accountIds,null);
                }
            }
        }
    }
}
