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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.enums.MaterialEnum;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IUserAllocationService;
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.ai.entity.AiKuaishouAccountAutoVideo;
import cn.com.ctop.kuaishou.modules.ai.mapper.AiKuaishouAccountAutoVideoMapper;
import cn.com.ctop.kuaishou.modules.ai.service.IAiKuaishouAccountAutoVideoService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 自动投放账户——素材
 *
 * @author jeecg-boot
 * 2021-10-20
 * @version V1.0
 */
@Slf4j
@Service
public class AiKuaishouAccountAutoVideoServiceImpl extends ServiceImpl<AiKuaishouAccountAutoVideoMapper, AiKuaishouAccountAutoVideo> implements IAiKuaishouAccountAutoVideoService {

    @Autowired
    private AiKuaishouAccountAutoVideoMapper autoVideoMapper;

    @Autowired
    private ICtopOauthTokenService tokenService;

    @Autowired
    private IUserAllocationService userAllocationService;

    @Override
    public List<AiKuaishouAccountAutoVideo> getUpNewVideos(Long accountId, Integer channelType, List<String> keyword, Integer videoCnt, String statDate, String createType) {
        return autoVideoMapper.getUpNewVideos(accountId, channelType, keyword, videoCnt, statDate, createType);
    }

    @Override
    public List<AiKuaishouAccountAutoVideo> getHistoryTopVideos(Long accountId, Integer channelType, List<String> keyword, Integer videoCnt, String statDate, String createType) {
        return autoVideoMapper.getHistoryTopVideos(accountId, channelType, keyword, videoCnt, createType, statDate);
    }

    @Override
    public List<AiKuaishouAccountAutoVideo> getMissVideoByParams(Long accountId, Integer channelType, List<String> keyword, Integer videoCnt, String statDate) {
        return autoVideoMapper.getZeroVideoByParams(accountId, channelType, keyword, videoCnt, statDate);
    }

    @Override
    public List<AiKuaishouAccountAutoVideo> getHistoryCatchVideos(Long accountId, Integer channelType, List<String> keyword, Integer videoCnt, String statDate) {
        return autoVideoMapper.getHistoryCatchVideos(accountId, channelType, keyword, videoCnt, statDate);
    }


    @Override
    public void saveOrUpdateAutoVideoUsedCount(Long accountId, String signature, Integer videoType, String createType) {
        Integer usageTimes = autoVideoMapper.getAutoVideoUsed(accountId, signature, videoType, createType);
        String date = DateUtils.formatDate(new Date());
        if (Check.isNull(usageTimes)) {
            usageTimes = 1;
            autoVideoMapper.addAutoVideoUsed(accountId, signature, videoType, createType, usageTimes, date);
        } else {
            usageTimes += 1;
            autoVideoMapper.updateAutoVideoUsed(accountId, signature, videoType, createType, usageTimes, date);
        }
    }

    @Override
    public void insertAutoVideo(Long accountId) {
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        this.getVideoListByPage(token, 1);
    }

    private void getVideoListByPage(CtopOauthToken token, int page) {
        try {
            String date = DateUtils.formatDate(new Date());
            Integer pageSize = 500;
            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);
            param.put("start_date", date);
            param.put("end_date", date);
            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);
                if (video != null && video.getInteger("new_status") == 1) {
                    details.add(video);
                }
            }
            if (Check.isNull(details) || details.isEmpty()) {
                return;
            }

            List<AiKuaishouAccountAutoVideo> videoGetList = new ArrayList<>();
            Long accountId = token.getAccountId();
            List<String> photoIds = autoVideoMapper.selectBatchByPhotoIds(details, date, accountId);
            for (int i = 0; i < details.size(); i++) {
                JSONObject detailJson = details.getJSONObject(i);
                if (Check.isNull(detailJson)) {
                    continue;
                }
                String photoId = detailJson.getString("photo_id");
                if (!Check.isNull(photoIds) && photoIds.contains(photoId)) {
                    continue;
                }
                AiKuaishouAccountAutoVideo videoGet = new AiKuaishouAccountAutoVideo();
                videoGet.setAccountId(accountId);
                videoGet.setPhotoId(photoId);
                videoGet.setPhotoName(detailJson.getString("photo_name"));
                videoGet.setStatDate(DateUtils.formatDate(detailJson.getDate("create_time"), DateUtils.WEB_FORMAT));
                String signature = detailJson.getString("signature");
                videoGet.setSignature(signature);
                Integer source = detailJson.getInteger("source");
                if (source == 2) {
                    videoGet.setChannelType(1);
                } else {
                    videoGet.setChannelType(0);
                }
                Integer newStatus = detailJson.getInteger("new_status");
                if (newStatus == 1) {
                    //状态1是可用，其他状态不录存
                    videoGet.setCustomStatus(1);
                    videoGet.setProgramStatus(1);
                } else {
                    continue;
                }
                Integer width = detailJson.getInteger("width");
                Integer height = detailJson.getInteger("height");
                Map<String, Integer> typeBySize = MaterialEnum.getTypeBySize(width, height);
                if (!Check.isNullMap(typeBySize)) {
                    videoGet.setMaterialType(typeBySize.get("type"));

                }
                videoGetList.add(videoGet);
            }
            if (!Check.isNull(videoGetList)) {
                autoVideoMapper.insertBatch(videoGetList);
            }
            if (doGet) {
                getVideoListByPage(token, page + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    static ExecutorService autoVideoService = Executors.newFixedThreadPool(6);

    @Override
    public void insertAutoVideoByProjectId(Long projectId) {
        List<JSONObject> accounts = userAllocationService.getAccountInfoByProjectId(projectId);
        if (!Check.isNull(accounts)) {
            accounts.forEach(acc -> autoVideoService.submit(() -> {
                try {
                    getVideoListByProjectId(acc, 1);
                } catch (Exception e) {
                    log.error("通过项目ID获取视频素材失败", e);
                }
            }));


        }
    }

    private void getVideoListByProjectId(JSONObject acc, int page) {
        Long accountId = acc.getLong("accountId");
        Long projectId = acc.getLong("projectId");
        String accountName = acc.getString("accountName");
        String projectName = acc.getString("projectName");
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        try {
            int pageSize = 500;
            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", accountId);
            param.put("page_size", 500);
            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;
            }
            List<JSONObject> list = new ArrayList<>();
            for (int i = 0; i < videoList.size(); i++) {
                JSONObject video = videoList.getJSONObject(i);
                if (video != null && video.getInteger("new_status") == 1) {
                    video.put("accountId",accountId);
                    video.put("accountName",accountName);
                    video.put("projectId",projectId);
                    video.put("projectName",projectName);
                    list.add(video);
                }
            }
            if (!Check.isNull(list)) {
                autoVideoMapper.insertBatchAiKuaishouProjectAutoVideo(list);
            }
            if (doGet) {
                getVideoListByPage(token, page + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
