package org.jeecg.modules.bytedance.advertise.controller;

import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.bytedance.advertise.dockapi.MarketingService;
import org.jeecg.modules.bytedance.advertise.entity.ByteDanceAdvertisePlan;
import org.jeecg.modules.bytedance.advertise.service.BytedanceRejectReasonService;
import org.jeecg.modules.bytedance.advertise.service.IByteDanceAdvertisePlanService;
import org.jeecg.modules.bytedance.common.entity.CtopOauthToken;
import org.jeecg.modules.bytedance.common.service.ICtopOauthTokenService;
import org.jeecg.modules.bytedance.common.utils.Check;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 广告计划审核建议
 * @author hxc
 * 2021-06-28
 * @version V1.0
 */
@Slf4j
@Api(tags="广告计划审核建议")
@RestController
@RequestMapping("/ctop/bytedanceRejectReason")
public class BytedanceRejectReasonController {



    static ExecutorService executorService = Executors.newFixedThreadPool(5);
    @Autowired
    MarketingService marketingService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    IByteDanceAdvertisePlanService byteDanceAdvertisePlanService;
    @Autowired
    BytedanceRejectReasonService bytedanceRejectReasonService;

    /**
     *  编辑
     * @param hour : 获取当前时间近几个小时的数据。根据广告计划表，近hour个小时新增进来的计划信息，更新他们的审核建议
     * @return
     */
    @ApiOperation(value="广告计划审核建议-从接口获取数据落库", notes="广告计划审核建议-从接口获取数据落库")
    @GetMapping(value = "/getReasonInRecentHours")
    public Result getReasonInRecentHours(@RequestParam(value = "hour",required = false) Integer hour) {
        Result result = new Result();
        List<CtopOauthToken> tokens = tokenService.selectToutiaoToken();
        if (null == tokens || tokens.isEmpty()) {
            System.out.println("未获取到token");
            result.setCode(500);
            result.setMessage("未获取到token");
            return result;
        }

        System.out.println("---------------------------------->>"+tokens.size()+"个token<<----------------------------------");

        tokens.forEach(token -> executorService.submit(()->getRejectReasonByToken(token, hour)));


        return result.success("调用任务已开启");
    }


    public void getRejectReasonByToken(CtopOauthToken token, Integer hour){

            if(token.getAccessTokenExpiresIn().before(new Date())){
                log.info("token已过期，accountId ==> {}",token.getAccountId());
                return;
            }

            List<ByteDanceAdvertisePlan> allPlansByAccountId = byteDanceAdvertisePlanService.getAllPlansByAccountId(token.getAccountId(), Check.isNull(hour)?null:DateUtils.formatDate(DateUtils.addHour(new Date(),-hour),"yyyy-MM-dd HH:mm:ss"));

            if(Check.isNull(allPlansByAccountId) || allPlansByAccountId.size() < 1){
                return;
            }
            List<String> adids = new ArrayList<>();
            allPlansByAccountId.forEach(plan -> adids.add(plan.getId().toString()));


            while(adids.size() > 10){
                List<String> mulAdids = adids.subList(0,10);
//                System.out.println("查询的计划是"+Arrays.toString(mulAdids.toArray()));
                Result dataListResult = marketingService.getRejectReason(token, token.getAccountId().toString(), mulAdids);
                if(dataListResult.getMessage().toString().contains("No permission to operate account")){
                    return;
                }
                if(Check.isNull(dataListResult.getResult()) || dataListResult.getCode().equals(500)){
                    continue;
                }
                JSONArray jsonArray = JSONArray.parseArray(dataListResult.getResult().toString());
                bytedanceRejectReasonService.saveRejectReasonToDb(jsonArray,token.getAccountId());
                adids.removeAll(mulAdids);
            }
            Result dataListResult = marketingService.getRejectReason(token, token.getAccountId().toString(), adids);
            if(Check.isNull(dataListResult.getResult())|| dataListResult.getCode().equals(500)){
                return;
            }
            JSONArray jsonArray = JSONArray.parseArray(dataListResult.getResult().toString());
            bytedanceRejectReasonService.saveRejectReasonToDb(jsonArray,token.getAccountId());
        }

}