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

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.kuaishou.modules.dimension.entity.KuaiShouDimensionUnit;
import cn.com.ctop.kuaishou.modules.dimension.mapper.KuaiShouDimensionUnitMapper;
import cn.com.ctop.kuaishou.modules.dimension.service.IKuaiShouDimensionCreativeService;
import cn.com.ctop.kuaishou.modules.dimension.service.IKuaiShouDimensionUnitService;
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.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 多维度测试组列表
 *
 * @author jeecg-boot
 * 2021-07-22
 * @version V1.0
 */
@Slf4j
@Service
public class KuaiShouDimensionUnitServiceImpl extends ServiceImpl<KuaiShouDimensionUnitMapper, KuaiShouDimensionUnit> implements IKuaiShouDimensionUnitService {
    @Autowired
    private KuaiShouDimensionUnitMapper dimensionUnitMapper;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;
    @Autowired
    private IKuaiShouDimensionCreativeService dimensionCreativeService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IKuaiShouDimensionUnitService dimensionUnitService;

    /**
     * 创建组
     *
     * @param strategyId
     * @param accountId
     */
    @Override
    public void createUnit(Long strategyId, Long accountId, String accessToken) {
        QueryWrapper<KuaiShouDimensionUnit> unitQueryWrapper = new QueryWrapper<>();
        unitQueryWrapper.eq("strategy_id", strategyId);
        unitQueryWrapper.eq("account_id", accountId);
        unitQueryWrapper.eq("submit_status", 1);
        unitQueryWrapper.orderByAsc("create_time");
        unitQueryWrapper.last("limit 10");
        List<KuaiShouDimensionUnit> kuaiShouDimensionUnits = dimensionUnitMapper.selectList(unitQueryWrapper);
        if (Check.isNull(kuaiShouDimensionUnits)) {
            return;
        }
        for (KuaiShouDimensionUnit unit : kuaiShouDimensionUnits) {
            Boolean trueOrFalse = dimensionUnitService.getCreateOverrun(accountId);
            if (trueOrFalse) {
                log.error("该账户今日创建已超限，策略id：{}，账户id：{}", strategyId, accountId);
                return;
            }

            KuaiShouDimensionUnit updateDimensionUnit = new KuaiShouDimensionUnit();
            updateDimensionUnit.setId(unit.getId());
            updateDimensionUnit.setSubmitStatus(2);
            updateDimensionUnit.setCreateDescribe("创建中");
            dimensionUnitMapper.updateById(updateDimensionUnit);

            JSONObject createUnitJson = new JSONObject();
            createUnitJson.put("scene_id", JSONArray.parseArray(unit.getSceneId())); //资源位置
            createUnitJson.put("campaign_id", unit.getCampaignId());
            createUnitJson.put("unit_name", unit.getUnitName());
            if (!Check.isNull(unit.getBidType())) {
                createUnitJson.put("bid_type", unit.getBidType()); // 优化目标类型
            }
            if (!Check.isNull(unit.getUseAppMarket())) {
                createUnitJson.put("use_app_market", unit.getUseAppMarket()); //优先从系统应用商店下载
            }
            if (!Check.isNull(unit.getAppStore())) {
                createUnitJson.put("app_store", JSONArray.parseArray(unit.getAppStore())); //应用商店列表
            }
            if (!Check.isNull(unit.getBid())) {
                createUnitJson.put("bid", unit.getBid()); //出价
            }
            if (!Check.isNull(unit.getCpaBid())) {
                createUnitJson.put("cpa_bid", unit.getCpaBid()); //出价
            }
            if (!Check.isNull(unit.getOcpxActionType())) {
                createUnitJson.put("ocpx_action_type", unit.getOcpxActionType()); //优化目标
            }
            if (!Check.isNull(unit.getDeepConversionType())) {
                createUnitJson.put("deep_conversion_type", unit.getDeepConversionType()); //深度转化目标
            }
            if (!Check.isNull(unit.getDeepConversionBid())) {
                createUnitJson.put("deep_conversion_bid", unit.getDeepConversionBid()); //深度转化目标出价
            }
            if (!Check.isNull(unit.getUnitType())) {
                createUnitJson.put("unit_type", unit.getUnitType()); //创意制作方式
            }
            createUnitJson.put("begin_time", DateUtils.getNowDate("yyyy-MM-dd")); //投放开始时间
            if (!Check.isNull(unit.getScheduleTime())) {
                createUnitJson.put("schedule_time", unit.getScheduleTime()); //投放时间段
            }
            if (!Check.isNull(unit.getUnitDayBudget())) {
                createUnitJson.put("day_budget", unit.getUnitDayBudget()); //单日预算金额
            }
            if (!Check.isNull(unit.getSchemaUri())) {
                createUnitJson.put("schema_uri", unit.getSchemaUri()); // 吊起链接
            }
            if (!Check.isNull(unit.getAppId())) {
                createUnitJson.put("app_id", unit.getAppId()); // 应用ID
            }
            if (!Check.isNull(unit.getShowMode())) {
                createUnitJson.put("show_mode", unit.getShowMode()); // 创意展现方式
            }
            if (!Check.isNull(unit.getSpeed())) {
                createUnitJson.put("speed", unit.getSpeed()); // 投放方式
            }
            if (!Check.isNull(unit.getIntentionTarget())) {
                if (unit.getIntentionTarget()) {
                    createUnitJson.put("intention_target", unit.getIntentionTarget()); // 行为意向-系统优选
                }
            }
            JSONObject targetJson = getTarget(unit);
            createUnitJson.put("target", targetJson);

            Map<String, Object> returnUnitMap = kuaishouInterfaceService.adUnitCreate(accessToken, accountId, createUnitJson, 1);
            Integer unitCode = (Integer) returnUnitMap.get("code");
            if (unitCode == 0) {
                updateDimensionUnit.setSubmitStatus(3);
                updateDimensionUnit.setCreateDescribe("创建成功");
                Long unitId = (Long) returnUnitMap.get("unitId");
                updateDimensionUnit.setUnitId(unitId);
                dimensionUnitMapper.updateById(updateDimensionUnit);
                dimensionCreativeService.createCreative(accountId, accessToken, unit.getId(), unitId);
            } else {
                String unitMessage = (String) returnUnitMap.get("message");
                if ("/rest/openapi/v2/ad_unit/create调用已超日限，次日可恢复调用".equals(unitMessage)) {
                    updateDimensionUnit.setSubmitStatus(1);
                    updateDimensionUnit.setCreateDescribe("当日组创建超限");
                    dimensionUnitMapper.updateById(updateDimensionUnit);
                    return;
                } else {
                    updateDimensionUnit.setSubmitStatus(4);
                    updateDimensionUnit.setCreateDescribe(unitMessage);
                    dimensionUnitMapper.updateById(updateDimensionUnit);
                }
            }
        }


    }


    private JSONObject getTarget(KuaiShouDimensionUnit unit) {
        JSONObject target = new JSONObject();
        if (!Check.isNull(unit.getRegion())) {
            target.put("region", JSONArray.parseArray(unit.getRegion()));
        }

        if (!Check.isNull(unit.getAgesRange())) {
            target.put("ages_range", JSONArray.parseArray(unit.getAgesRange()));
        }

        if (!Check.isNull(unit.getGender())) {
            target.put("gender", unit.getGender());
        }

        if (!Check.isNull(unit.getNetwork())) {
            target.put("network", unit.getNetwork());
        }

        if (!Check.isNull(unit.getDeviceBrand())) {
            target.put("device_brand", JSONArray.parseArray(unit.getDeviceBrand()));
        }

        if (!Check.isNull(unit.getDevicePrice())) {
            target.put("device_price", JSONArray.parseArray(unit.getDevicePrice()));
        }

        if (!Check.isNull(unit.getAppIds())) {
            target.put("app_ids", JSONArray.parseArray(unit.getAppIds()));
        }

        if (!Check.isNull(unit.getPopulation())) {
            target.put("population", JSONArray.parseArray(unit.getPopulation()));
        }

        if (!Check.isNull(unit.getExcludePopulation())) {
            target.put("exclude_population", JSONArray.parseArray(unit.getExcludePopulation()));
        }

        if (!Check.isNull(unit.getPaidAudience())) {
            target.put("paid_audience", JSONArray.parseArray(unit.getPaidAudience()));
        }

        if (!Check.isNull(unit.getFilterConvertedLevel())) {
            target.put("filter_converted_level", unit.getFilterConvertedLevel());
        }

        if (!Check.isNull(unit.getIsOpen())) {
            if (unit.getIsOpen() == 1) {
                JSONObject intelli_extend = new JSONObject();
                intelli_extend.put("is_open", unit.getIsOpen());
                if (!Check.isNull(unit.getNoAgeBreak())) {
                    if (unit.getNoAgeBreak() == 1) {
                        intelli_extend.put("no_age_break", unit.getNoAgeBreak());
                    }
                }
                if (!Check.isNull(unit.getNoGenderBreak())) {
                    if (unit.getNoGenderBreak() == 1) {
                        intelli_extend.put("no_gender_break", unit.getNoGenderBreak());
                    }
                }
                if (!Check.isNull(unit.getNoAreaBreak())) {
                    if (unit.getNoAreaBreak() == 1) {
                        intelli_extend.put("no_area_break", unit.getNoAreaBreak());
                    }
                }
                target.put("intelli_extend", intelli_extend);
            }
        }
        return target;
    }

    @Override
    public Boolean getCreateOverrun(Long accountId) {
        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
        String creativeKey = accountId + "_" + nowDate + "creative_create_overrun";
        Object creative = redisUtil.get(creativeKey);

        String unitKey = accountId + "_" + nowDate + "unit_create_overrun";
        Object unit = redisUtil.get(unitKey);

        if (Check.isNull(creative) && Check.isNull(unit)) {
            return false;
        }
        if (!Check.isNull(creative)) {
            Integer creativeOverrun = (Integer) creative;
            if (creativeOverrun == 1) {
                return true;
            }
        }
        if (!Check.isNull(unit)) {
            Integer unitOverrun = (Integer) unit;
            if (unitOverrun == 1) {
                return true;
            }
        }
        return false;
    }

    @Override
    public List<JSONObject> getCampaignCount(Long accountId, Long strategyId) {
        return dimensionUnitMapper.getCampaignCount(accountId, strategyId);
    }

    @Override
    public Integer getUnitCount(Long accountId, Long strategyId) {
        return dimensionUnitMapper.getUnitCount(accountId, strategyId);
    }

    @Override
    public List<KuaiShouDimensionUnit> getUnitListBy(Long strategyId, Long accountId, Long campaignId) {

        QueryWrapper<KuaiShouDimensionUnit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("strategy_id", strategyId);
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("campaign_id", campaignId);
        queryWrapper.eq("submit_status", 0);
        queryWrapper.orderByDesc("unit_name");
        return dimensionUnitMapper.selectList(queryWrapper);
    }

    /**
     * 批量修改状态
     *
     * @param submitStatus
     * @param ids
     */
    @Override
    public void editBatch(Integer submitStatus, JSONArray ids) {
        dimensionUnitMapper.editBatch(submitStatus, ids);
    }

    @Override
    public Integer getUnitCountByStrategyId(Long strategyId) {
        return dimensionUnitMapper.getUnitCountByStrategyId(strategyId);
    }

}
