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

import cn.com.ctop.common.module.service.IMessageTemplate;
import cn.com.ctop.common.module.service.ISendMessageService;
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.clean.entity.TrackMonitorConfigure;
import cn.com.ctop.kuaishou.modules.clean.entity.TrackMonitorLogs;
import cn.com.ctop.kuaishou.modules.clean.mapper.TrackMonitorLogsMapper;
import cn.com.ctop.kuaishou.modules.clean.service.ITrackMonitorLogsService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 监测链接预警-日志
 *
 * @author jeecg-boot
 * 2021-09-23
 * @version V1.0
 */
@Slf4j
@Service
public class TrackMonitorLogsServiceImpl extends ServiceImpl<TrackMonitorLogsMapper, TrackMonitorLogs> implements ITrackMonitorLogsService {
    @Autowired
    private ISendMessageService sendMessageService;
    @Autowired
    private IMessageTemplate messageTemplate;
    @Autowired
    private TrackMonitorLogsMapper monitorLogsMapper;


    @Override
    public void monitorCreative(TrackMonitorConfigure configure, Long accountId, String accessToken, String userId, String startDate, String endDate, Integer page) {
        log.info("开始自定义创意监测链接预警，accountId：{}", accountId);
        String clickTrackUrl = "";
        if (!Check.isNull(configure.getClickTrackUrl())) {
            clickTrackUrl = configure.getClickTrackUrl().trim();
        }
        String actionbarClickUrl = "";
        if (!Check.isNull(configure.getActionbarClickUrl())) {
            actionbarClickUrl = configure.getActionbarClickUrl().trim();
        }
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", accessToken);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        Integer page_size = 500;
        param.put("page_size", page_size);
        param.put("page", page);
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告创意返回结果为空,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取广告创意返回结果异常,advertiserId:{},message:{}", accountId, message);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            return;
        }
        Boolean doGet = true;
        if (details.size() < page_size) {
            doGet = false;
        }
        Map<Long, JSONObject> unitMap = new HashMap<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject creativeJson = details.getJSONObject(i);
            Integer status = creativeJson.getInteger("status");
            if (status == 52 || status == 41 || status == 19) { // 只检查创意状态为投放中、审核中
                JSONObject unitJson = new JSONObject();
                Boolean trueOrFalse = false;
                String click_track_url = creativeJson.getString("click_track_url");
                if (!Check.isNull(click_track_url)) {
                    if (!Check.isNull(clickTrackUrl)) {
                        if (!click_track_url.equals(clickTrackUrl)) {
                            trueOrFalse = true;
                            unitJson.put("click_track_url", click_track_url);
                        }
                    }
                }
                String actionbar_click_url = creativeJson.getString("actionbar_click_url");
                if (!Check.isNull(actionbar_click_url)) {
                    if (!Check.isNull(actionbarClickUrl)) {
                        if (!actionbar_click_url.equals(actionbarClickUrl)) {
                            trueOrFalse = true;
                            unitJson.put("actionbar_click_url", actionbar_click_url);
                        }
                    }
                }
                if (trueOrFalse) {
                    Long unit_id = creativeJson.getLong("unit_id");
                    Integer count = monitorLogsMapper.getCount(accountId, unit_id);
                    if (count <= 0 || count == null) {
                        unitMap.put(unit_id, unitJson);
                    }
                }
            }
        }
        if (!Check.isNullMap(unitMap)) {
            doOperation(accountId, accessToken, unitMap, userId);
        }
        if (doGet) {
            monitorCreative(configure, accountId, accessToken, userId, startDate, endDate, page + 1);
        }
    }

    @Override
    public void monitorProgramCreative(TrackMonitorConfigure configure, Long accountId, String accessToken, String userId, String startDate, String endDate, Integer page) {
        log.info("开始程序化创意监测链接预警，accountId：{}", accountId);
        String clickTrackUrl = "";
        if (!Check.isNull(configure.getClickTrackUrl())) {
            clickTrackUrl = configure.getClickTrackUrl().trim();
        }
        String actionbarClickUrl = "";
        if (!Check.isNull(configure.getActionbarClickUrl())) {
            actionbarClickUrl = configure.getActionbarClickUrl().trim();
        }
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PROGRAM_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", accessToken);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        Integer page_size = 500;
        param.put("page_size", page_size);
        param.put("page", page);
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告创意返回结果为空,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取广告创意返回结果异常,advertiserId:{},message:{}", accountId, message);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            return;
        }
        Boolean doGet = true;
        if (details.size() < page_size) {
            doGet = false;
        }
        Map<Long, JSONObject> unitMap = new HashMap<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject creativeJson = details.getJSONObject(i);

            Integer status = creativeJson.getInteger("view_status");
            if (status == 52 || status == 41 || status == 19 || status == 62) { // 只检查创意状态为投放中、审核中、待送审
                JSONObject unitJson = new JSONObject();
                Boolean trueOrFalse = false;
                String click_track_url = creativeJson.getString("click_url");
                if (!Check.isNull(click_track_url)) {
                    if (!Check.isNull(clickTrackUrl)) {
                        if (!click_track_url.equals(clickTrackUrl)) {
                            trueOrFalse = true;
                            unitJson.put("click_track_url", click_track_url);
                        }
                    }
                }
                String actionbar_click_url = creativeJson.getString("actionbar_click_url");
                if (!Check.isNull(actionbar_click_url)) {
                    if (!Check.isNull(actionbarClickUrl)) {
                        if (!actionbar_click_url.equals(actionbarClickUrl)) {
                            trueOrFalse = true;
                            unitJson.put("actionbar_click_url", actionbar_click_url);
                        }
                    }
                }
                if (trueOrFalse) {
                    Long unit_id = creativeJson.getLong("unit_id");
                    Integer count = monitorLogsMapper.getCount(accountId, unit_id);
                    if (count <= 0 || count == null) {
                        unitMap.put(unit_id, unitJson);
                    }
                }
            }
        }
        if (!Check.isNullMap(unitMap)) {
            doOperation(accountId, accessToken, unitMap, userId);
        }
        if (doGet) {
            monitorCreative(configure, accountId, accessToken, userId, startDate, endDate, page + 1);
        }
    }

    private void doOperation(Long accountId, String accessToken, Map<Long, JSONObject> unitMap, String userId) {
        List<TrackMonitorLogs> trackMonitorLogs = new ArrayList<>();
        for (Map.Entry<Long, JSONObject> entry : unitMap.entrySet()) {
            Long unitId = entry.getKey();
            JSONObject info = entry.getValue();
            String trackMessage = messageTemplate.getTrackMessage(accountId, unitId);
            sendMessageService.sendMessage(userId, trackMessage);
            Map<String, Object> map = monitorUpdateUnitStatus(accessToken, accountId, unitId, 2, "e9ca23d68d884d4ebb19d07889727dae");
            if (Check.isNullMap(map)) {
                continue;
            }
            Integer code = (Integer) map.get("code");
            if (code == 0) {
                TrackMonitorLogs logs = new TrackMonitorLogs();
                logs.setAccountId(accountId);
                logs.setUnitId(unitId);
                String click_track_url = info.getString("click_track_url");
                if (!Check.isNull(click_track_url)) {
                    logs.setClickTrackUrl(click_track_url);
                }
                String actionbar_click_url = info.getString("actionbar_click_url");
                if (!Check.isNull(actionbar_click_url)) {
                    logs.setActionbarClickUrl(actionbar_click_url);
                }
                trackMonitorLogs.add(logs);
            }
        }
        monitorLogsMapper.replaceBatch(trackMonitorLogs);
    }


    private Map<String, Object> monitorUpdateUnitStatus(String token, Long advertiserId, Long unitId, int putStatus, String loginId) {
        Map<String, Object> returnMap = new HashMap<>();
        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", advertiserId);
            params.put("unit_id", unitId);
            params.put("put_status", putStatus);
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                    returnMap.put("message", "修改成功");
                    log.info("监测链接预警修改组状态成功，accountId：{}。unitId：{}", advertiserId, unitId);
                } else {
                    log.error("监测链接预警修改广告组状态失败，advertiserId：{}，unitId：{}，返回信息：{}", advertiserId, unitId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("监测链接预警修改广告组状态返回结果为空，advertiserId：{}，unitId：{}", advertiserId, unitId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }
        } catch (Exception e) {
            log.error("监测链接预警修改广告组状态异常，advertiserId：{}，unitId：{}", advertiserId, unitId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告组状态异常");
        }

        return returnMap;
    }

}
