package ctop.bytedance.ad.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 ctop.bytedance.ad.advertise.dockapi.MarketingService;
import ctop.bytedance.ad.advertise.entity.ByteDanceAdvertisePlan;
import ctop.bytedance.ad.advertise.service.BytedanceRejectReasonService;
import ctop.bytedance.ad.advertise.service.IByteDanceAdvertisePlanService;
import ctop.bytedance.ad.common.entity.CtopOauthToken;
import ctop.bytedance.ad.common.service.ICtopOauthTokenService;
import ctop.bytedance.ad.common.utils.Check;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 广告计划审核建议
 * @author hxc
 * 2021-06-28
 * @version V1.0
 */
@Slf4j
@Api(tags="广告计划审核建议")
@RestController
@RequestMapping("/bytedance/ad/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()) {
            result.setCode(500);
            result.setMessage("未获取到token");
            return result;
        }
        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);
                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());
        }

}