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.KuaishouVideoRelateCreatives;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouVideoRelateCreativesMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouVideoRelateCreativesService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
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.List;
import java.util.Map;
import java.util.*;

/**
 * 频库-视频关联创意数查询
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-01-12
 */
@Slf4j
@Service
public class KuaishouVideoRelateCreativesServiceImpl extends ServiceImpl<KuaishouVideoRelateCreativesMapper, KuaishouVideoRelateCreatives> implements IKuaishouVideoRelateCreativesService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Resource
    private KuaishouVideoRelateCreativesMapper kuaishouVideoRelateCreativesMapper;

    /**
     * 视频库-推送视频
     *
     * @param
     * @return com.alibaba.fastjson.JSONArray
     * @throws
     * @author ZHAOXA
     */
    @Override
    public Result pushVideo(JSONObject data) {
        try {
            Long accountId = data.getLong("accountId");
            if (Check.isNull(accountId)) {
                return Result.error("请选择广告主");
            }
            JSONArray photoIds = data.getJSONArray("photoIds");
            if (Check.isNull(photoIds)) {
                return Result.error("请选择视频集");
            }
            if (photoIds.size() > 10) {
                return Result.error("选择视频应少于10条");
            }
            JSONArray shareAdvertiserIds = data.getJSONArray("shareAdvertiserIds");
            if (Check.isNull(shareAdvertiserIds)) {
                return Result.error("请选择推送账户");
            }
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_SHARE;
            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);
            params.put("photo_ids", photoIds);
            params.put("share_advertiser_ids", shareAdvertiserIds);
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    return Result.ok(resultJson.getJSONObject("data"));
                } else {
                    log.info("视频库-推送视频失败，accountId：{}，返回信息：{}", accountId, resultJson);
                    return Result.error("视频库-推送视频失败，" + resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            log.error("视频库-推送视频失败", e);
        }
        return Result.error("视频库-推送视频失败");
    }

    /**
     * 频库-视频关联创意数查询
     *
     * @param
     * @return boolean
     * @throws
     * @author ZHAOXA
     */
    @Override
    public void videoRelateCreatives(Long accountId, JSONArray photoIds, Map<String, Object> statdateMap) {
        try {
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            for (int i = 0; i < photoIds.size(); i++) {
                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);
                params.put("photo_ids", photoIds.getJSONArray(i));
                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) {
                            List<KuaishouVideoRelateCreatives> videolist = new ArrayList<>();
                            for (int j = 0; j < relatedCreatives.size(); j++) {
                                KuaishouVideoRelateCreatives k = new KuaishouVideoRelateCreatives();
                                JSONObject object = relatedCreatives.getJSONObject(j);
                                k.setAccountId(accountId);
                                k.setPhotoId(object.getLong("photo_id"));
                                k.setCreativeCount(object.getInteger("creative_count"));
                                k.setStatDate((Date) statdateMap.get(object.getString("photo_id")));
                                videolist.add(k);
                            }
                            kuaishouVideoRelateCreativesMapper.insertBatch(videolist);
                        }
                    } else {
                        log.info("频库-视频关联创意数查询失败，accountId：{}，返回信息：{}", accountId, resultJson);
                    }
                }
            }
        } catch (Exception e) {
            log.error("频库-视频关联创意数查询失败", e);
        }
    }

    @Override
    public List<JSONObject> getVideoListByMap(Map<String, Object> requestMap) {
        return kuaishouVideoRelateCreativesMapper.getVideoListByMap(requestMap);
    }

    @Override
    public List<KuaishouVideoRelateCreatives> listByParams(Long accountId,Integer matNum) {
        QueryWrapper<KuaishouVideoRelateCreatives> queryWrapper = new QueryWrapper<>();
        if(null!=accountId&&accountId!=0){
            queryWrapper.eq("account_id",accountId);
        }
        if(null == matNum||matNum == 0){
            matNum = 10;
        }
        queryWrapper.le("creative_count",30);
        queryWrapper.orderByDesc("stat_date");
        queryWrapper.last("limit "+matNum);
        return this.list(queryWrapper);
    }

    @Override
    public List<JSONObject> getVideoZeroListByMap(Map<String, Object> requestMap) {
        return kuaishouVideoRelateCreativesMapper.getVideoZeroListByMap(requestMap);
    }

    @Override
    public List<JSONObject> getHistoryTopVideoList(Map<String, Object> requestMap) {
        return kuaishouVideoRelateCreativesMapper.getHistoryTopVideoList(requestMap);
    }
}
