package cn.com.ctop.toutiao.modules.material.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IMessageTemplate;
import cn.com.ctop.common.module.service.ISendMessageService;
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.PropertiesUtils;
import cn.com.ctop.toutiao.modules.material.entity.ByteDanceVideoInfo;
import cn.com.ctop.toutiao.modules.material.mapper.ByteDanceVideoInfoMapper;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceVideoInfoService;
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 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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 今日头条视频素材信息
 * @Author: jeecg-boot
 * @Date: 2019-07-29
 * @Version: V1.0
 */
@Service
public class ByteDanceVideoInfoServiceImpl extends ServiceImpl<ByteDanceVideoInfoMapper, ByteDanceVideoInfo> implements IByteDanceVideoInfoService {
    @Resource
    private ByteDanceVideoInfoMapper videoInfoMapper;
    @Autowired
    IUserAllocationService userAllocationService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private ISendMessageService sendMessageService;
    @Autowired
    private IMessageTemplate messageTemplate;

    @Override
    public void replaceBatch(List<ByteDanceVideoInfo> videoInfoList) {
        videoInfoMapper.replaceBatch(videoInfoList);
    }

    @Override
    public ByteDanceVideoInfo getOneByParams(Long materialId) {
        QueryWrapper<ByteDanceVideoInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("material_id", materialId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public void getIllegalVideosPushInfo(Long agentId, List<Long> list, Long promotionId) {
        String adid = PropertiesUtils.getValue("bytedance_config", "admin_account_id");
        CtopOauthToken token = oauthTokenService.getTokenByAccountId(Long.valueOf(adid));

        //广告违规素材推送
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_rapi_url") +
                PropertiesUtils.getValue("bytedance_config", "bytedance_v2_risk_promotion_list");
        Map<String, Object> param = new HashMap<>();
        param.put("agent_id", agentId);
        param.put("business_type", "AD");
        String today = DateUtils.date2Str();
        String yesterday = DateUtils.getLastDay(today, 1);
        param.put("start_date", yesterday);
        param.put("end_date", today);

        JSONObject filtering = new JSONObject();
        filtering.put("illegal_material_ids", list);
        param.put("filtering", filtering);

        Map<String, String> header = new HashMap<>();
        header.put("Access-Token", token.getAccessToken());

        JSONObject result = JSONObject.parseObject(HttpUtils.httpGet(url, param, header));
        if (!Check.isNull(result)) {
            String code = result.getString("code");
            if ("0".equals(code)) {
                //违规信息入库
                storageIllegalInfo(result.getJSONObject("data").getJSONArray("data"), promotionId);
            } else {
                log.error("查询违规广告列表失败，原因：" + result.getString("message"));
            }
        }
    }

    private static Map<String, String> sendMap = new HashMap<>();

    //违规信息入库
    private void storageIllegalInfo(JSONArray array, Long promotionId) {
        try {
            List<JSONObject> list = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject data = array.getJSONObject(i);
                Long advertiserId = data.getLong("advertiser_id");
                //获取项目消息
                JSONObject project = userAllocationService.getAccountInfoByAccountId(advertiserId);
                if (!Check.isNull(project)) {
                    data.put("projectId", project.getLong("projectId"));
                    data.put("projectName", project.getString("projectName"));
                    data.put("userId", project.getString("user_id"));
                }
                //计划ID
                Long promotion_id = data.getLong("promotion_id");
                //违规素材列表，包含广告下投前+投中拒审的素材信息
                JSONArray materialList = data.getJSONArray("material_list");
                for (int j = 0; j < materialList.size(); j++) {
                    JSONObject materialObj = materialList.getJSONObject(j);
                    JSONObject info = getmaterialData(data, materialObj);
                    list.add(info);
                    if (promotionId.equals(promotion_id)) {
                        //发送企业微信提醒
                        //素材ID+计划
                        String key = info.getString("materialId") + promotion_id;
                        String val = sendMap.get(key);
                        if (Check.isNull(val)) {
                            sendMsg(info);
                            sendMap.put(key, "send");
                        }
                    }
                }
            }

            if (!Check.isNull(list)) {
                videoInfoMapper.replaceBatchIllegalBytedanceMaterialInfo(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //违规素材列表 数据整理
    private JSONObject getmaterialData(JSONObject data, JSONObject material) {
        JSONObject info = new JSONObject();
        info.put("agentId", data.getLong("agent_id"));
        info.put("projectId", data.getLong("projectId"));
        info.put("projectName", data.getString("projectName"));
        info.put("accountId", data.getLong("advertiser_id"));
        info.put("accountName", data.getString("advertiser_name"));
        info.put("promotionId", data.getLong("promotion_id"));
        info.put("materialId", material.getLong("id"));
        info.put("riskContent", material.getString("risk_content"));
        info.put("userId", data.getString("userId"));
        info.put("userName", data.getString("optimizer_name"));
        return info;
    }

    private void sendMsg(JSONObject info) {
        String text = messageTemplate.getIllegalADInfo(info);
        info.put("sendContent", text);
        sendMessageService.illegalSendMessage(info);
        videoInfoMapper.insertIllegalBytedanceSendRecord(info);
    }
}
