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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.UserAllocation;
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.service.IKuaiShouCommentService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.enums.NoEn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 评论
 */
@Slf4j
@Service
public class IKuaiShouCommentServiceImpl implements IKuaiShouCommentService {

    @Autowired
    private ICtopOauthTokenService oauthTokenService;

    @Override
    public void shieldComment(Long accountId) {
        try {
            Long start = System.currentTimeMillis();
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            queryComments(oauthToken.getAccessToken(), accountId, 1, 500, 1);
            Long end = System.currentTimeMillis();
            log.info("总用时:{}毫秒",end-start);
        } catch (Exception e) {
            log.error("屏蔽评论异常", e);
        }
    }

    @Override
    public void deleteComment(UserAllocation allocation) {
        CtopOauthToken token = oauthTokenService.getTokenByAccountId(allocation.getAccountId());
        deleteCommentByPage(token,1);
        log.info("删除评论完成:accounId=>{}",allocation.getAccountId());
    }

    private void deleteCommentByPage(CtopOauthToken token, int pageNum) {
        //1:查询评论数据
        JSONArray comments = getComments(token,pageNum,500);
        if(null!=comments&&!comments.isEmpty()){
            //存在评论则执行删除查询下一页，循环
            shieldCommentApi(token.getAccessToken(), token.getAccountId(), comments);
            deleteCommentByPage(token,pageNum+1);
        }
    }

    private JSONArray getComments(CtopOauthToken token, int pageNum, int pageSize) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.COMMENT_LIST;
        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", token.getAccountId());
        //未隐藏数据
        params.put("shield_status", NoEn.NO1.valueInt());
        params.put("page", pageNum);
        params.put("page_size", pageSize);
        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 dataJson = resultJson.getJSONObject("data");
                JSONArray details = dataJson.getJSONArray("details");
                if (!Check.isNull(details)) {
                   return  details;
                }
            }
        }
        return new JSONArray();
    }

    /**
     * 查询评论
     *
     * @param
     * @return com.alibaba.fastjson.JSONArray
     * @throws
     * @author ZHAOXA
     */
    private JSONArray queryComments(String token, Long accountId, int page, int pageSize, int num) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.COMMENT_LIST;
        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("shield_status", NoEn.NO1.valueInt());
        params.put("page", page);
        params.put("page_size", pageSize);
        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 dataJson = resultJson.getJSONObject("data");
                JSONArray details = dataJson.getJSONArray("details");
                if (!Check.isNull(details)) {
                    log.info("账户（{}）删除第{}次，待删除条数：{}", accountId, num, details.size());
                    if (num <= 50) {
                        if (shieldCommentApi(token, accountId, details)) {
                            queryComments(token, accountId, page, pageSize, ++num);
                        }
                    }
                }
                return null;
            } else {
                log.error("查询评论列表数据接口返回信息错误：accountId：{}，返回信息：{}", accountId, resultJson);
            }
        }
        return null;
    }

    /**
     * 执行屏蔽接口
     *
     * @param
     * @return com.alibaba.fastjson.JSONArray
     * @throws
     * @author ZHAOXA
     */
    private boolean shieldCommentApi(String token, Long accountId, JSONArray comments) {
        if (Check.isNull(comments)) {
            return false;
        }
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.COMMENT_SHIELD;
        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("shield_list", comments);
        String result = HttpUtils.httpPostRequest(url, params, header);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                return true;
            } else {
                log.info("删除评论失败，accountId：{}，返回信息：{}", accountId, resultJson);
            }
        }
        return false;
    }
}
