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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCreativeService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@Api(tags = "快手-创意拒审重提")
@RestController
@RequestMapping("/kuaishou/creative/")
public class KuaiShouCreativeRefusalController {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private IKuaiShouUpdateService updateService;
    @Autowired
    private IMaterialCutFrameService cutFrameService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    static ExecutorService executorService = Executors.newFixedThreadPool(50);

    /**
     * 创意拒审重提
     *
     * @param requestJson
     * @return
     */
    @PostMapping(value = "again")
    public JSONObject again(@RequestBody JSONObject requestJson) {
        JSONObject returnJson = new JSONObject();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("入参不能为空");
            }
            Long accountId = requestJson.getLong("accountId");
            if (Check.isNull(accountId)) {
                throw new Exception("请输入账户id");
            }
            CtopOauthToken oauthToken = tokenService.getTokenByAccountId(accountId);
            if (Check.isNull(oauthToken)) {
                throw new Exception("未获取到账户信息");
            }
            //  0 更换封面 1 修改广告语
            Integer updateType = requestJson.getInteger("updateType");
            if (Check.isNull(updateType)) {
                throw new Exception("请输入修改类型");
            }
            JSONArray creativeIds = requestJson.getJSONArray("creativeIds");
            if (Check.isNull(creativeIds)) {
                creativeIds = creativeService.getCreativeIds(accountId);
            }
            for (int i = 0; i < creativeIds.size(); i++) {
                Long creativeId = creativeIds.getLong(i);
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        KuaiShouCreative creative = creativeService.getCreativeByCreativeId(creativeId);
                        if (!Check.isNull(creative)) {
                            JSONObject updateJson = new JSONObject();
                            updateJson.put("creativeId", creativeId);
                            if (updateType == 0) {  //  更换封面
                                JSONObject cutJson = cutFrameService.getCutFrameByVideoMd5(creative.getPhotoId(), creative.getImageToken());
                                if (!Check.isNull(cutJson)) {
                                    String signature = cutJson.getString("signature");
                                    String url = cutJson.getString("url");
                                    String imageToken = getImageToken(signature, accountId, oauthToken.getAccessToken(), url);
                                    if (!Check.isNull(imageToken)) {
                                        updateJson.put("imageToken", imageToken);
                                    }
                                }
                            } else if (updateType == 1) { // 修改广告语
                                String updateDescription = creativeService.convertMoString(creative.getDescription());
                                updateJson.put("description", updateDescription);
                            }
                            Map<String, Object> creativeMap = updateService.updateCreative(oauthToken.getAccessToken(), accountId, updateJson);
                            Integer code = (Integer) creativeMap.get("code");
                            if (code == 0) {
                                log.info("自动投放拒审重提成功,accountId:{},creativeId:{}", accountId, creativeId);
                            } else {
                                log.info("自动投放拒审重提失败,accountId:{},creativeId:{}", accountId, creativeId);
                            }
                            try {
                                Thread.sleep(1000L);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
            returnJson.put("code", 0);
            returnJson.put("message", "异步任务提交完成，请耐心等待");
            return returnJson;
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", "服务异常");
            return returnJson;
        }
    }


    private String getImageToken(String md5, Long accountId, String accessToken, String url) {
        String imageToken = null;
        QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("signature", md5);
        queryWrapper.last("limit 1");
        KuaiShouImageGet imageGet = imageGetService.getOne(queryWrapper);
        if (!Check.isNull(imageGet)) {
            imageToken = imageGet.getImageToken();
        } else {
            imageToken = uploadService.kuauiShouImageUpload(url, md5, accountId, accessToken);
        }
        return imageToken;

    }

}
