package cn.com.ctop.kuaishou.modules.report.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.BigDecimalUtil;
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.common.module.utils.StatusCode;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouGroupSpeedExploreLog;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouGroupSpeedExploreLogService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouGroupExplore;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyExplore;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouGroupExploreMapper;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouGroupExploreService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyExploreService;
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 java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 广告组的加速探索报表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-02-02
 */
@Slf4j
@Service
public class KuaishouGroupExploreServiceImpl extends ServiceImpl<KuaishouGroupExploreMapper, KuaishouGroupExplore> implements IKuaishouGroupExploreService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouGroupSpeedExploreLogService groupSpeedExploreLogService;
    @Autowired
    private IKuaishouReportDailyExploreService dailyExploreService;

    @Autowired
    private IKuaiShouGroupService kuaiShouGroupService;

    /**
     * 查询加速探索状态、预算
     *
     * @param
     * @return
     * @throws
     * @author ZHAOXA
     */
    @Override
    public Result<Object> unitExploreInfoGet(Long accountId, Long unitId) {
        try {
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UNIT_EXPLORE_INFO_GET;
            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("unit_id", unitId);
            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
     * @throws
     * @author ZHAOXA
     */
    @Override
    public Result<Object> unitExploreBudgetUpdate(Long accountId, Long unitId, Long exploreBudget) {
        String msg = null;
        try {
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UNIT_EXPLORE_BUDGET_UPDATE;
            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("unit_id", unitId);
            params.put("explore_budget", exploreBudget);
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    Result<Object> result1 = this.unitExploreInfoGet(accountId, unitId);
                    if (result1.getCode() == 200) {
                        JSONObject resultData = (JSONObject) result1.getResult();
                        Integer exploreStatus = resultData.getInteger("explore_status");
                        Long maxExploreBudget = resultData.getLong("max_explore_budget");
                        KuaiShouGroup kuaiShouGroup = new KuaiShouGroup();

                        KuaishouReportDailyExplore kuaishouGroupExplore = new KuaishouReportDailyExplore();
                        kuaishouGroupExplore.setAccountId(accountId);
                        kuaishouGroupExplore.setUnitId(unitId);
                        kuaishouGroupExplore.setStatDate(new Date());
                        kuaishouGroupExplore.setMaxExploreBudget(maxExploreBudget);
                        kuaishouGroupExplore.setExploreStatus(exploreStatus);
                        dailyExploreService.save(kuaishouGroupExplore);
                    }
                    return Result.ok(resultJson.getJSONObject("data"));
                } else {
                    log.info("广告组的加速探索预算设置失败，accountId：{}，返回信息：{}", accountId, resultJson);
                    return Result.error("广告组的加速探索预算设置失败，" + resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            log.error("广告组({})启动加速探索失败", unitId, e);
        }
        return Result.error("广告组的加速探索预算设置失败");
    }

    /**
     * 暂停广告组的加速探索预算接口
     *
     * @param
     * @throws
     * @author ZHAOXA
     */
    @Override
    public Result<Object> unitExploreStatusPause(JSONObject data) {
        try {
            Long accountId = data.getLong("accountId");
            if (Check.isNull(accountId)) {
                return Result.error("请选择广告主");
            }
            Long unitId = data.getLong("unitId");
            if (Check.isNull(unitId)) {
                return Result.error("请选择广告组");
            }
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UNIT_EXPLORE_STATUS_PAUSE;
            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("unit_id", unitId);
            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
     * @throws
     * @author ZHAOXA
     */
    @Override
    public Result<Object> querySpeedExploreReport(Long accountId, Long unitId, Integer exploreStatus, Long maxExploreBudget) {
        try {
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.QUERY_SPEED_EXPLORE_REPORT;
            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("unit_id", unitId);
            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 exploreJson = resultJson.getJSONObject("data");
                    KuaishouReportDailyExplore kuaishouGroupExplore = JSONObject.toJavaObject(exploreJson, KuaishouReportDailyExplore.class);
                    if (Check.isNull(kuaishouGroupExplore)) {
                        return Result.error("查询失败，结果为空");
                    }
                    QueryWrapper<KuaishouReportDailyExplore> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("unit_id", unitId);
                    queryWrapper.eq("account_id", accountId);
                    KuaishouReportDailyExplore one = dailyExploreService.getOne(queryWrapper);
                    if (!Check.isNull(one)) {
                        kuaishouGroupExplore.setId(one.getId());
                    }
                    KuaiShouGroup kuaiShouGroup = kuaiShouGroupService.selectGroupByUnitId(accountId, unitId);
                    if (!Check.isNull(kuaiShouGroup)) {
                        kuaishouGroupExplore.setUnitName(kuaiShouGroup.getUnitName());
                        kuaishouGroupExplore.setCampaignId(kuaiShouGroup.getCampaignId());
                    }
                    kuaishouGroupExplore.setAccountId(accountId);
                    kuaishouGroupExplore.setExploreStatus(exploreStatus);
                    kuaishouGroupExplore.setMaxExploreBudget(maxExploreBudget);
                    kuaishouGroupExplore.setStatDate(new Date());
                    kuaishouGroupExplore.setExploreBudget(BigDecimalUtil.divideBigDecimal(kuaishouGroupExplore.getExploreBudget(), new BigDecimal(1000)));
                    kuaishouGroupExplore.setTotalCharge(BigDecimalUtil.divideBigDecimal(kuaishouGroupExplore.getTotalCharge(), new BigDecimal(1000)));
                    boolean b = dailyExploreService.saveOrUpdate(kuaishouGroupExplore);
                    if (b) {
                        return Result.ok("添加成功");
                    }
                } else {
                    log.info("查询广告组的加速探索报表失败，accountId：{}，返回信息：{}", accountId, resultJson);
                    return Result.error("查询广告组的加速探索报表失败，" + resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            log.error("查询广告组的加速探索报表失败", e);
        }
        return Result.error("查询广告组的加速探索报表失败");
    }

    @Override
    public void unitOpenSpeedExplore(Long accountId, Long unitId, BigDecimal groupAccount, Long accountExploreId) {
        KuaishouGroupSpeedExploreLog groupSpeedExploreLog = new KuaishouGroupSpeedExploreLog();
        groupSpeedExploreLog.setAccountExploreId(accountExploreId);
        groupSpeedExploreLog.setAccountId(accountId);
        try {
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UNIT_EXPLORE_BUDGET_UPDATE;
            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("unit_id", unitId);
            params.put("explore_budget", groupAccount.longValue());
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                String message = resultJson.getString("message");
                groupSpeedExploreLog.setStatus(code);
                groupSpeedExploreLog.setMessage(message);
            } else {
                groupSpeedExploreLog.setStatus(StatusCode.KUAISHOU_SPEED_EXPLORE_FAIL.getCode());
                groupSpeedExploreLog.setMessage(StatusCode.KUAISHOU_SPEED_EXPLORE_FAIL.getDesc());
            }
        } catch (Exception e) {
            log.error("广告组的加速探索预算设置失败", e);
            groupSpeedExploreLog.setStatus(StatusCode.COMMON_SERVER_ERROR.getCode());
            groupSpeedExploreLog.setMessage(StatusCode.COMMON_SERVER_ERROR.getDesc());
        }
        groupSpeedExploreLogService.save(groupSpeedExploreLog);
    }

    @Override
    public void getReportByAccount(CtopOauthToken token) {
        //1:查询此账户下设置了加速探索的组
    }

    @Override
    public Result<Object> adUnitExploreSupport(JSONObject data) {
        try {
            Long accountId = data.getLong("accountId");
            if (Check.isNull(accountId)) {
                return Result.error("请选择广告主");
            }
            JSONArray supportUnitIds = data.getJSONArray("supportUnitIds");
            if (Check.isNull(supportUnitIds)) {
                return Result.error("请填写辅助探索广告组集");
            }
            Long unitId = data.getLong("unitId");
            if (Check.isNull(unitId)) {
                return Result.error("请填写要设置辅助探索的广告组");
            }
            CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AD_UNIT_EXPLORE_SUPPORT;
            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("support_unit_ids", supportUnitIds);
            params.put("unit_id", unitId);
            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("辅助探索失败");
    }
}
