package cn.com.ctop.kuaishou.modules.batch.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.batch.entity.DelKuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.mapper.DelKuaiShouVideoGetMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IDelKuaiShouVideoGetService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Service
public class DelKuaiShouVideoGetServiceImpl extends ServiceImpl<DelKuaiShouVideoGetMapper, DelKuaiShouVideoGet> implements IDelKuaiShouVideoGetService {
    @Resource
    private DelKuaiShouVideoGetMapper videoGetMapper;

    @Autowired
    private ICtopOauthTokenService tokenService;

    @Override
    public void insertDelVideoList(Long accountId) {
        //先删除历史记录，再添加最新数据
        videoGetMapper.deleteByAccountId(accountId);

        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        this.getDelVideoListByPage(token, 1);
    }

    private void getDelVideoListByPage(CtopOauthToken token, int page) {
        try {
            String date = DateUtils.formatDate(new Date());
            Integer pageSize = 200;
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token.getAccessToken());
            Map<String, Object> param = new HashMap<>();
            param.put("advertiser_id", token.getAccountId());
            param.put("page_size", pageSize);
            param.put("page", page);

            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (Check.isNull(resultJson)) {
                return;
            }
            Integer code = resultJson.getInteger("code");
            String message = resultJson.getString("message");
            if (null == code || code != 0) {
                log.error("获取快手视频列表数据异常:{},accountId:{}", message, token.getAccountId());
                return;
            }
            JSONArray videoList = resultJson.getJSONObject("data").getJSONArray("details");
            if (null == videoList || videoList.size() <= 0) {
                log.info("快手视频列表信息为空=》accountId:{}", token.getAccountId());
                return;
            }
            Boolean doGet = true;
            if (videoList.size() < pageSize) {
                doGet = false;
            }
            JSONArray details = new JSONArray();
            for (int i = 0; i < videoList.size(); i++) {
                JSONObject video = videoList.getJSONObject(i);
                details.add(video);
            }
            if (Check.isNull(details) || details.isEmpty()) {
                return;
            }
            List<DelKuaiShouVideoGet> videoGetList = new ArrayList<>();
            Long accountId = token.getAccountId();
            for (int i = 0; i < details.size(); i++) {
                JSONObject detailJson = details.getJSONObject(i);
                if (Check.isNull(detailJson)) {
                    continue;
                }
                DelKuaiShouVideoGet videoGet = new DelKuaiShouVideoGet();
                videoGet.setAccountId(accountId);
                videoGet.setPhotoId(detailJson.getString("photo_id"));
                videoGet.setPhotoName(detailJson.getString("photo_name"));
                videoGet.setSignature(detailJson.getString("signature"));
                videoGetList.add(videoGet);
            }
            if (!Check.isNull(videoGetList)) {
                videoGetMapper.replaceBatch(videoGetList);
            }
            if (doGet) {
                getDelVideoListByPage(token, page + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void getCreateInfo(Long accountId, String photoName) {
        try {
            List<String> phototIds = videoGetMapper.queryPhototIdsByPhotoName(accountId, photoName);
            videoRelateCreatives(accountId, phototIds);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void videoRelateCreatives(Long accountId, List<String> photoIds) {
        try {
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            for (String photoId : photoIds) {
                String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_RELATE_CREATIVES;
                Map<String, String> header = new HashMap<>();
                header.put("Access-Token", token.getAccessToken());
                header.put("Content-Type", "application/json");
                JSONObject params = new JSONObject();
                params.put("advertiser_id", accountId);
                String[] photoIdArr = new String[]{photoId};
                params.put("photo_ids", photoIdArr);
                String result = HttpUtils.httpPostRequest(url, params, header);
                JSONObject resultJson = JSONObject.parseObject(result);
                if (!Check.isNull(resultJson)) {
                    Integer code = resultJson.getInteger("code");
                    if (code == 0) {
                        JSONObject data = resultJson.getJSONObject("data");
                        JSONArray relatedCreatives = data.getJSONArray("related_creatives");
                        if (!Check.isNull(relatedCreatives) && relatedCreatives.size() > 0) {
                            JSONObject object = relatedCreatives.getJSONObject(0);
                            object.put("account_id", accountId);
                            object.put("advancedCreativeIdsStr", object.getString("advanced_creative_ids"));
                            JSONArray creatives = object.getJSONArray("creatives");
                            if (!Check.isNull(creatives) && creatives.size() > 0) {
                                videoGetMapper.replaceBatchVideoRelateCreatives(object, creatives);
                            }
                            JSONArray advancedCreativeIds = object.getJSONArray("advanced_creative_ids");
                            if (!Check.isNull(advancedCreativeIds) && advancedCreativeIds.size() > 0) {
                                videoGetMapper.replaceBatchVideoRelateAdvancedCreatives(object, advancedCreativeIds);
                            }
                        }
                    } else {
                        log.info("频库-视频关联创意数查询失败，入参：{}，返回结果：{}", params, resultJson);
                    }
                }
            }
        } catch (Exception e) {
            log.error("频库-视频关联创意数查询失败", e);
        }
    }


    @Override
    public void changeCreativesPutStatus(Long accountId) {
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        List<Long> allCreativeIds = videoGetMapper.queryCreativeIds(accountId);
        //创意
        if (!Check.isNull(allCreativeIds)) {
            //最多20个ID
//            List<List<Long>> splitVideos = Lists.newArrayList(Lists.partition(allCreativeIds, 20));
            List<List<Long>> splitVideos =Lists.partition(allCreativeIds, 20);
            for (List<Long> creativeIds : splitVideos) {
                deleteCreatives(token.getAccessToken(), accountId, creativeIds);
            }
        }
        //程序化创意
        Set<Long> allAdvancedCreativeIds = videoGetMapper.queryAdvancedCreativeIds(accountId);
        if (!Check.isNull(allAdvancedCreativeIds)) {
            List<Long> allAdvancedCreativeIdsList = new ArrayList<>(allAdvancedCreativeIds);
            //最多10个id
            List<List<Long>> splitVideos = Lists.partition(allAdvancedCreativeIdsList, 10);
            for (List<Long> unitIds : splitVideos) {
                deleteUnitStatus(token.getAccessToken(), accountId, unitIds);
            }
        }

        List<String> pids = videoGetMapper.getPhotoIds(accountId, "0");
        List<String> pids2 = videoGetMapper.getPhotoIds2(accountId, "0");
        if (Check.isNull(pids) && Check.isNull(pids2)) {
            log.info("---------状态改变完成--------- ："+accountId);
        }
        //批量删除视频
//        checkDeleteVideo(token.getAccessToken(), accountId);
    }

    //修改广告创意为删除状态
    public void deleteCreatives(String token, Long accountId, List<Long> creativeIds) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_CREATIVE_STATUS;
            Map<String, String> header = new HashMap<>();
            header.put("Access-Token", token);
            header.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("put_status", 3);//删除
            params.put("advertiser_id", accountId);
            params.put("creative_ids", creativeIds);
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                videoGetMapper.updateCreativesStatus(accountId, creativeIds);
            } else {
                log.error("修改广告创意删除状态失败，入参：{}， 结果：{}", params, resultJson);
            }
        } catch (Exception e) {
            log.error("修改广告创意删除状态异常，advertiserId：{}，creativeIds：{}", accountId, creativeIds);
            e.printStackTrace();
        }
    }

    //修改广告组为删除状态
    public void deleteUnitStatus(String token, Long accountId, List<Long> unitIds) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_UNIT_STATUS;
            Map<String, String> header = new HashMap<>();
            header.put("Access-Token", token);
            header.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("advertiser_id", accountId);
            params.put("unit_ids", unitIds);
            params.put("put_status", 3);//删除
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                videoGetMapper.updateAdvancedCreativesStatus(accountId, unitIds);
            } else {
                log.error("修改广告组删除状态失败，入参：{}， 结果：{}", params, resultJson);
            }
        } catch (Exception e) {
            log.error("修改广告组删除状态异常，advertiserId：{}，unitIds：{}", accountId, unitIds);
            e.printStackTrace();
        }
    }

    private void checkDeleteVideo(String token, Long accountId) {
        //查询   状态为0的，说明有删除失败，不执行删除视频操作
        List<String> pids = videoGetMapper.getPhotoIds(accountId, "0");
        List<String> pids2 = videoGetMapper.getPhotoIds2(accountId, "0");
        if (Check.isNull(pids) && Check.isNull(pids2)) {
            List<String> delphtotoids = videoGetMapper.getPhotoIds(accountId, "3");
            List<String> delphtotoids2 = videoGetMapper.getPhotoIds2(accountId, "3");
            //去重-转set
            Set<String> photoIds = new HashSet<>(delphtotoids);
            photoIds.addAll(delphtotoids2);
            //执行删除
            JSONObject resultJson = deleteVideo(token, accountId, photoIds);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                String message = resultJson.getString("message");
                //添加执行结果记录
                videoGetMapper.insertDelPhotoIdLog(accountId, photoIds, code, message);
            }
            log.info("删除账户视频，账户：{}， 结果：{}", accountId, resultJson);
        } else {
            log.error("创意和广告组删除状态未完全修改，不执行删除视频操作，账户accountId：{}，参考信息：1创意：{} 2程序化创意：{}", accountId, pids, pids2);
        }
    }


    //批量删除视频
    public JSONObject deleteVideo(String token, Long accountId, Set<String> photoIds) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.DELETE_CREATIVE_VIDEO;
            Map<String, String> header = new HashMap<>();
            header.put("Access-Token", token);
            header.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("advertiser_id", accountId);
            params.put("photo_ids", photoIds);
            String result = HttpUtils.httpPostRequest(url, params, header);
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            log.error("批量删除账户视频异常，accountId：{}，photoIds：{}", accountId, photoIds);
            e.printStackTrace();
        }
        return null;
    }

}
