package org.jeecg.modules.ctop.controller;

import cn.com.ctop.common.module.entity.*;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.service.*;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCampaignService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouDailyReportTaskService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouHistoryReportTaskService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertiserDataService;
import cn.com.ctop.toutiao.modules.report.service.IBytedancePlanDailyReportService;
import cn.com.ctop.toutiao.modules.report.service.IBytedancePlanHourlyReportService;
import cn.com.ctop.toutiao.modules.report.service.IReportService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
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.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.jeecg.common.util.DateUtils.getAnotherDay;

/**
 * @author jeecg-boot
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {
    @Autowired
    private IKuaishouWebInterfaceService kuaishouWebInterfaceService;

    @Autowired
    private CtopOauthTokenMapper oauthTokenMapper;
    @Autowired
    private IKuaiShouHistoryReportTaskService historyReportTaskService;
    @Autowired
    private IMaterialInfoService materialInfoService;
    @Autowired
    private IMaterialParameterService parameterService;
    @Autowired
    private IMaterialAscriptionService ascriptionService;
    @Autowired
    private IMaterialTagService tagService;
    @Autowired
    private IMaterialImageInfoService iMaterialImageInfoService;

    @GetMapping(value = "/t")
    public String test() {
        Result<String> result = new Result<>();
        try {
            String requestId = UUID.randomUUID().toString();
            String img = kuaishouWebInterfaceService.qrLogin(requestId);
            if (img != null) {
                result.setSuccess(true);
                result.setResult(img);
            } else {
                result.setSuccess(false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @Autowired
    private CtopOauthTokenMapper tokenMapper;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;


    @Autowired
    private ICtopOauthTokenService oauthTokenService;


    @GetMapping(value = "/getToken")
    public String getToken(Long accountId, String refreshToken, Integer agentType) {
        oauthTokenService.getKuaiShouRefreshToken(accountId, refreshToken, agentType);
        return "Success";
    }


    @GetMapping(value = "/getAccountReport")
    public String getAccountReport(Long accountId, String startDate, String endDate) throws ParseException {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sim.parse(startDate);
        Date date2 = sim.parse(endDate);
        kuaishouInterfaceService.getAdvertiserReportDaily(token, date1, date2);
        return "Success";
    }


    @GetMapping(value = "/getAccountReportList")
    public String getAccountReportList(String startDate, String endDate) {
        Result<String> result = new Result<>();
        try {
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = sim.parse(startDate);
            Date date2 = sim.parse(endDate);

            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(tokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    kuaishouInterfaceService.getAdvertiserReportDaily(token, date1, date2);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/updateCode")
    public String updateCode() {
        List<MaterialInfo> list = materialInfoService.list();
        for (MaterialInfo info : list) {
            QueryWrapper<MaterialImageInfo> imageInfoQueryWrapper = new QueryWrapper<>();
            imageInfoQueryWrapper.eq("video_id", String.valueOf(info.getId()));
            MaterialImageInfo updateMaterialImageInfo = new MaterialImageInfo();
            updateMaterialImageInfo.setVideoId(info.getCode());
            iMaterialImageInfoService.update(updateMaterialImageInfo, imageInfoQueryWrapper);
            QueryWrapper<MaterialTag> tagQueryWrapper = new QueryWrapper<>();
            tagQueryWrapper.eq("material_id", String.valueOf(info.getId()));
            MaterialTag updateTag = new MaterialTag();
            updateTag.setMaterialId(info.getCode());
            tagService.update(updateTag, tagQueryWrapper);
            QueryWrapper<MaterialAscription> materialAscriptionQuery = new QueryWrapper<>();
            materialAscriptionQuery.eq("material_id", String.valueOf(info.getId()));
            MaterialAscription updateMaterialAscription = new MaterialAscription();
            updateMaterialAscription.setMaterialId(info.getCode());
            ascriptionService.update(updateMaterialAscription, materialAscriptionQuery);
            QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
            parameterQueryWrapper.eq("material_id", String.valueOf(info.getId()));
            MaterialParameter updateMaterialParameter = new MaterialParameter();
            updateMaterialParameter.setMaterialId(info.getCode());
            parameterService.update(updateMaterialParameter, parameterQueryWrapper);
        }
        List<MaterialImageInfo> list1 = iMaterialImageInfoService.list();
        for (MaterialImageInfo imageInfo : list1) {
            QueryWrapper<MaterialParameter> parameterQueryWrapper = new QueryWrapper<>();
            parameterQueryWrapper.eq("material_id", String.valueOf(imageInfo.getId()));
            MaterialParameter updateMaterialParameter = new MaterialParameter();
            updateMaterialParameter.setMaterialId(imageInfo.getCode());
            parameterService.update(updateMaterialParameter, parameterQueryWrapper);
        }


        List<String> codeList = iMaterialImageInfoService.getCodeList();
        if (!Check.isNull(codeList)) {
            for (int i = 0; i < codeList.size(); i++) {
                String code = codeList.get(i);
                QueryWrapper<MaterialImageInfo> materialImageInfoQueryWrapper = new QueryWrapper<>();
                materialImageInfoQueryWrapper.eq("code", code);

                List<MaterialImageInfo> list2 = iMaterialImageInfoService.list(materialImageInfoQueryWrapper);
                if (list2.size() > 1) {
                    for (int j = 0; j < list2.size(); j++) {
                        if (j == 0) {
                            continue;
                        }
                        MaterialImageInfo materialImageInfo = list2.get(j);
                        iMaterialImageInfoService.removeById(String.valueOf(materialImageInfo.getId()));
                    }

                }
            }
        }
        return "SUCCESS";
    }


    @GetMapping(value = "/createTask")
    public String createTask(Long accountId) {
        Result<String> result = new Result<String>();
        try {
            QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
            oauthTokenQueryWrapper.eq("media_id", 2);
            oauthTokenQueryWrapper.eq("account_id", accountId);
            oauthTokenQueryWrapper.last("limit 1");
            CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
            String endDateStr = DateUtils.getDate("yyyy-MM-dd");
            String startDate = DateUtils.addMonth(endDateStr, -6);
            historyReportTaskService.createTask(token.getAccountId(), token.getAccessToken(), startDate, endDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/getHistoryData")
    public String getHistoryData() {
        Result<String> result = new Result<>();
        try {
            String endDateStr = DateUtils.getDate("yyyy-MM-dd");
            String startDate = DateUtils.addMonth(endDateStr, -6);
            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(tokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    historyReportTaskService.createTask(token.getAccountId(), token.getAccessToken(), startDate, endDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }


    @GetMapping(value = "/getTaskList")
    public String getTaskList() {
        Result<String> result = new Result<>();
        try {
            QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
            tokenQueryWrapper.eq("media_id", 2);
            historyReportTaskService.getTaskList();
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
        }
        return "success";
    }

    @GetMapping(value = "/getGroupData")
    public String getGroupData() {


        Date endDate = new Date();
        QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
        tokenQueryWrapper.eq("media_id", 2);
        List<CtopOauthToken> ctopOauthTokens = tokenMapper.selectList(tokenQueryWrapper);
        for (CtopOauthToken token : ctopOauthTokens) {

            for (int i = 0; i < 7; i++) {
                Date getStartDate = DateUtils.addDay(endDate, -i);
                //3：获取广告组信息数据
                kuaishouInterfaceService.getAdvertiserGroupReportHourly(token, getStartDate, getStartDate);
            }
            for (int i = 0; i < 6; i++) {
                Date getStartDate = new Date();
                Date getEndDate = new Date();
                if (i == 0) {
                    getStartDate = DateUtils.addDay(endDate, -175 + i * 30);
                    getEndDate = DateUtils.addDay(endDate, -150 + i * 30);
                } else {
                    getStartDate = DateUtils.addDay(endDate, -180 + i * 30);
                    getEndDate = DateUtils.addDay(endDate, -150 + i * 30);
                }
                //3：获取广告组信息数据
                kuaishouInterfaceService.getAdvertiserGroupReportDaily(token, getStartDate, getEndDate);
            }
        }
        return "Success";
    }

    static ExecutorService executorService = Executors.newFixedThreadPool(10);


    @GetMapping(value = "/gerCreative")
    public void gerCreative() {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(oauthTokenQueryWrapper);
        for (CtopOauthToken token : ctopOauthTokens) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        kuaishouInterfaceService.getCreativeList(token, null, null);
                        //  kuaishouInterfaceService.getVideoList2(token, null, null,1);
                        //3: 获取图片信息数据
                        // kuaishouInterfaceService.getImageList2(token, null, null,1);
                        Thread.sleep(1 * 200);
                        //  kuaishouInterfaceService.getAppList(token.getAccountId(), token.getAccessToken());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    @GetMapping("checkFile")
    public Map<String, Object> checkFile() {
        String nowDate = DateUtils.getDate("yyyy-MM-dd");
        String statDate = getAnotherDay("yyyy-MM-dd", nowDate, -1);
        //  查询快手token
        List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
        if (null == tokens || tokens.size() <= 0) {
            log.info("定时获取快手数据异常：未获取到可用的token");
        }
        for (CtopOauthToken token : tokens) {
            dailyReportTaskService.getTaskList(token.getAccountId(), token.getAccessToken(), statDate);
        }
        Map<String, Object> result = new HashMap<>();
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @Autowired
    private IKuaiShouDailyReportTaskService dailyReportTaskService;


    @Autowired
    private IKuaiShouCampaignService campaignService;


    @GetMapping("loadBytedanceHistoryData")
    public Map<String, Object> loadBytedanceHistoryData() {
        Map<String, Object> result = new HashMap<>();
        //1:查询所有头条的token数据
        List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
        if (null != tokens && tokens.size() > 0) {
            tokens.forEach(token -> {
                //拉取往期数据
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        reportService.loadBytedanceHistoryData(token);
                    }
                });
            });
        }
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }


    @Autowired
    private IUserAllocationService userAllocationService;

    @GetMapping(value = "/getPlanAndGroupByAccount")
    public void getPlanAndGroupByAccount(Long accountId) {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
        try {
            kuaishouInterfaceService.getCampaignList(token, null, null);
            //1：获取全量广告组数据
            kuaishouInterfaceService.getGroupList(token, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping(value = "/getCreativeByAccount")
    public void gerCreative(Long accountId) {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);

        try {
            kuaishouInterfaceService.getCreativeList(token, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    @Autowired
    private IBytedancePlanDailyReportService planDailyReportService;
    @Autowired
    private ICtopOauthTokenService tokenService;


    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;

    @GetMapping("getBytedanceData")
    public Map<String, Object> getBytedanceData() {
        Map<String, Object> result = new HashMap<>();
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.getTokenListByType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
        if (null == tokens || tokens.isEmpty()) {
            log.info("定时获取头条数据异常：为获取到可用的token");
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        tokens.forEach(token -> {
            advertiserDataService.getMaterialList(token);
        });
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    @Autowired
    private IReportService reportService;


    @Autowired
    private IBytedancePlanHourlyReportService planHourlyReportService;


    @GetMapping(value = "/AccountReportByAccount")
    public void AccountReportByAccount(Long accountId, String startDateStr, String endDateStr) {
        QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
        oauthTokenQueryWrapper.eq("media_id", 2);
        oauthTokenQueryWrapper.eq("account_id", accountId);
        oauthTokenQueryWrapper.last("limit 1");
        CtopOauthToken token = oauthTokenMapper.selectOne(oauthTokenQueryWrapper);
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date startDate = null;
                    Date endDate = null;
                    try {
                        startDate = simpleDateFormat.parse(startDateStr);
                        endDate = simpleDateFormat.parse(endDateStr);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    kuaishouInterfaceService.getAdvertiserReportDaily(token, startDate, endDate);

                    Thread.sleep(1 * 200);
                    //  kuaishouInterfaceService.getAppList(token.getAccountId(), token.getAccessToken());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @GetMapping(value = "/getAllCreativeList")
    public void getAllCreativeList() {

        try {


            QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
            oauthTokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(oauthTokenQueryWrapper);

            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            if (!Check.isNull(token)) {
                                log.info("获取创意，账号id:{}", token.getAccountId());
                                kuaishouInterfaceService.getCreativeList(token, null, null);
                            }
                        }
                    });

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @GetMapping(value = "/getAllGroupList")
    public void getAllGroupList() {

        try {

            QueryWrapper<CtopOauthToken> oauthTokenQueryWrapper = new QueryWrapper<>();
            oauthTokenQueryWrapper.eq("media_id", 2);
            List<CtopOauthToken> ctopOauthTokens = oauthTokenMapper.selectList(oauthTokenQueryWrapper);
            if (!Check.isNull(ctopOauthTokens)) {
                for (CtopOauthToken token : ctopOauthTokens) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            if (!Check.isNull(token)) {
                                log.info("获取组，账号id:{}", token.getAccountId());
                                kuaishouInterfaceService.getGroupList(token, null, null);
                            }
                        }
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @GetMapping(value = "/KuaishouDailyAccountReportLoadJob")
    public void KuaishouDailyAccountReportLoadJob() {
        Date getDate = DateUtils.addDay(new Date(), -2);
        //1:查询当日数据
        List<CtopOauthToken> tokens = tokenService.selectKuaiShouToken();
        if (null == tokens || tokens.size() <= 0) {
            log.info("定时获取快手数据异常：未获取到可用的token");
            return;
        }

        executorService = Executors.newFixedThreadPool(3);
        tokens.forEach(token -> {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    //1: 获取广告主信息数据
                    kuaishouInterfaceService.getAdvertiserReportDaily(token, getDate, getDate);
                }
            });
        });
    }


}
