package cn.com.ctop.kuaishou.modules.ai.controller;

import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouProjectStrategy;
import cn.com.ctop.kuaishou.modules.ai.service.IAiKuaishouProjectCreateCreativeService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouProjectStrategyService;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@Api(tags = "快手-自动投放")
@RestController
@RequestMapping("/ai/projectCreate")
public class AiKuaishouProjectCreateCreativeController {
    @Autowired
    private IAiKuaishouProjectCreateCreativeService projectCreateCreativeService;
    @Autowired
    private IKuaishouProjectStrategyService kuaishouProjectStrategyService;
    @Autowired
    private IUserAllocationService userAllocationService;


    static ExecutorService executorService = Executors.newFixedThreadPool(5);
    static ExecutorService kuaishouCustomCreativeSupplementExecutorService = Executors.newFixedThreadPool(3);

    /**
     * 检查匹配
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/projectAutomaticCreates")
    public JSONObject projectAutomaticCreates(String id, Integer operationType) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(id) || Check.isNull(operationType)) {
                throw new Exception("参数为空");
            }
            KuaishouProjectStrategy strategy = kuaishouProjectStrategyService.getById(id);
            if (Check.isNull(strategy)) {
                throw new Exception("根据id获取详细信息为空");
            }
            Long projectId = strategy.getProjectId();
            List<Long> list = userAllocationService.queryAutomaticAccounts(projectId);
            if (Check.isNull(list)) {
                throw new Exception("项目：" + projectId + "中未配置自动投放账户！");
            }
            list.forEach(accountId -> executorService.submit(() -> {
                Boolean unitOverrun = projectCreateCreativeService.getUnitOverrun(projectId.toString().concat(accountId.toString()));
                if (!unitOverrun) {
                    strategy.setAccountId(accountId);
                    // operationType 1检查反馈，2创建时信息
                    projectCreateCreativeService.projectAutomaticCreates(strategy, operationType);
                }
            }));
            returnJson.put("code", 0);
            returnJson.put("message", "自定义上新异步创建中");
        } catch (Exception e) {
            log.error("项目自动创建异常", e.fillInStackTrace());
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    /**
     * 项目自定义上新
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/projectCreative")
    public JSONObject projectCreative(String id) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(id)) {
                throw new Exception("参数为空");
            }
            KuaishouProjectStrategy strategy = kuaishouProjectStrategyService.getById(id);
            if (Check.isNull(strategy)) {
                throw new Exception("根据id获取详细信息为空");
            }
            Long projectId = strategy.getProjectId();
            List<Long> list = userAllocationService.queryAutomaticAccounts(projectId);
            if (Check.isNull(list)) {
                throw new Exception("项目：" + projectId + "中未配置自动投放账户！");
            }
            list.forEach(accountId -> executorService.submit(() -> {
                Boolean unitOverrun = projectCreateCreativeService.getUnitOverrun(projectId.toString().concat(accountId.toString()));
                if (!unitOverrun) {
                    strategy.setAccountId(accountId);
                    projectCreateCreativeService.projectAutomaticCreates(strategy);
                }
            }));
            returnJson.put("code", 0);
            returnJson.put("message", "自定义上新异步创建中");
        } catch (Exception e) {
            log.error("项目自动创建异常", e.fillInStackTrace());
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    /**
     * 项目维度自定义创意补充
     *
     * @param id
     * @param hour
     * @return
     */
    @GetMapping(value = "/projectCreativeSupplement")
    public JSONObject projectCreativeSupplement(String id, Integer hour) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(id)) {
                throw new Exception("主键id不能为空");
            }
            KuaishouProjectStrategy strategy = kuaishouProjectStrategyService.getById(id);
            if (Check.isNull(strategy)) {
                throw new Exception("根据id获取详细信息为空");
            }
            Long projectId = strategy.getProjectId();
            List<Long> list = userAllocationService.queryAutomaticAccounts(projectId);
            if (Check.isNull(list)) {
                throw new Exception("项目：" + projectId + "中未配置自动投放账户！");
            }
            list.forEach(accountId -> executorService.submit(() -> {
                Boolean unitOverrun = projectCreateCreativeService.getUnitOverrun(projectId.toString().concat(accountId.toString()));
                if (!unitOverrun) {
                    strategy.setAccountId(accountId);
                    try {
                        projectCreateCreativeService.customCreativeSupplement(strategy, hour);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }));
            returnJson.put("code", 0);
            returnJson.put("message", "自定义补充异步创建中...");
        } catch (Exception e) {
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    /**
     * 项目程序化上新
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/projectProgramAutomaticCreates")
    public JSONObject projectProgramAutomaticCreates(String id) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(id)) {
                throw new Exception("参数为空");
            }
            KuaishouProjectStrategy strategy = kuaishouProjectStrategyService.getById(id);
            if (Check.isNull(strategy)) {
                throw new Exception("根据id获取详细信息为空");
            }
            Long projectId = strategy.getProjectId();
            List<Long> list = userAllocationService.queryAutomaticAccounts(projectId);
            if (Check.isNull(list)) {
                throw new Exception("项目：" + projectId + "中未配置自动投放账户！");
            }
            list.forEach(accountId -> executorService.submit(() -> {
                Boolean unitOverrun = projectCreateCreativeService.getUnitOverrun(projectId.toString().concat(accountId.toString()));
                if (!unitOverrun) {
                    strategy.setAccountId(accountId);
                    projectCreateCreativeService.projectProgramAutomaticCreates(strategy, 1);
                }
            }));
            returnJson.put("code", 0);
            returnJson.put("message", "程序化上新异步创建中");
        } catch (Exception e) {
            log.error("项目自动创建异常", e.fillInStackTrace());
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }

    /**
     * 项目程序化高质量创意
     *
     * @param id
     * @param hour
     * @return
     */
    @GetMapping(value = "/projectProgramCreativeTop")
    public JSONObject projectProgramCreativeSupplement(String id, Integer hour) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(id)) {
                throw new Exception("参数为空");
            }
            KuaishouProjectStrategy strategy = kuaishouProjectStrategyService.getById(id);
            if (Check.isNull(strategy)) {
                throw new Exception("根据id获取详细信息为空");
            }
            Long projectId = strategy.getProjectId();
            List<Long> list = userAllocationService.queryAutomaticAccounts(projectId);
            if (Check.isNull(list)) {
                throw new Exception("项目：" + projectId + "中未配置自动投放账户！");
            }
            list.forEach(accountId -> executorService.submit(() -> {
                Boolean unitOverrun = projectCreateCreativeService.getUnitOverrun(projectId.toString().concat(accountId.toString()));
                if (!unitOverrun) {
                    strategy.setAccountId(accountId);
                    projectCreateCreativeService.projectProgramAutomaticCreates(strategy, 2);
                }
            }));
            returnJson.put("code", 0);
            returnJson.put("message", "程序化高质量异步创建中");
        } catch (Exception e) {
            log.error("项目自动创建异常", e.fillInStackTrace());
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }
}
