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.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCampaign;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.mapper.BatchMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouCampaignMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IBatchService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Slf4j
@Service
public class BatchServiceImpl implements IBatchService {
    @Autowired
    private BatchMapper batchMapper;
    @Autowired
    private KuaiShouCampaignMapper campaignMapper;
    @Autowired
    private UserAllocationMapper userAllocationMapper;


    /**
     * 获取总花费
     *
     * @param accountId
     * @return
     */
    @Override
    public BigDecimal getCost(Long accountId) {
        BigDecimal dailyCost = batchMapper.getDailyCost(accountId);
        BigDecimal hourlyCost = batchMapper.getHourCost(accountId, DateUtils.formatDate(new Date()));
        BigDecimal totalCost = dailyCost.add(hourlyCost);
        return totalCost;
    }

    /**
     * 获取总计划预算
     *
     * @param accountId
     * @return
     */
    @Override
    public BigDecimal getBudget(Long accountId) {
        return batchMapper.getBudget(accountId);
    }


    /**
     * 获取计划信息
     *
     * @param accountId
     * @param campaignId
     * @return
     */
    @Override
    public KuaiShouCampaign getCampaignInfo(Long accountId, Long campaignId) {
        QueryWrapper<KuaiShouCampaign> campaignQueryWrapper = new QueryWrapper<>();
        campaignQueryWrapper.eq("account_id", accountId);
        campaignQueryWrapper.eq("campaign_id", campaignId);
        campaignQueryWrapper.orderByDesc("create_time");
        campaignQueryWrapper.last("limit 1");
        KuaiShouCampaign campaign = campaignMapper.selectOne(campaignQueryWrapper);
        return campaign;
    }

    /**
     * 获取项目最高出价
     *
     * @param accountId
     * @return
     */

    @Override
    public BigDecimal getProjectMaxBid(Long accountId) {
        QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
        userAllocationQueryWrapper.eq("account_id", accountId);
        userAllocationQueryWrapper.eq("media_id", "2");
        userAllocationQueryWrapper.orderByDesc("create_time");
        userAllocationQueryWrapper.last("limit 1");
        UserAllocation userAllocation = userAllocationMapper.selectOne(userAllocationQueryWrapper);
        if (!Check.isNull(userAllocation)) {
            return batchMapper.getProjectMaxBidByProject(userAllocation.getProjectId());
        }
        return new BigDecimal(0);
    }


    /**
     * 校验广告组名称是否重复
     *
     * @param campaignId
     * @param unitName
     * @return
     */
    @Autowired
    private KuaiShouGroupMapper kuaiShouGroupMapper;

    @Override
    public Boolean checkUnitName(Long campaignId, String unitName) {
        QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("campaign_id", campaignId);
        groupQueryWrapper.eq("unit_name", unitName);
        groupQueryWrapper.orderByDesc("create_time");
        groupQueryWrapper.last("limit 1");
        KuaiShouGroup kuaiShouGroup = kuaiShouGroupMapper.selectOne(groupQueryWrapper);
        if (!Check.isNull(kuaiShouGroup)) {
            return false;
        }
        return true;
    }


    /**
     * 批量创建广告组
     *
     * @param requestJson
     * @return
     */
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;

    @Override
    public JSONObject createUnit(JSONObject requestJson) throws Exception {
        System.err.println(requestJson);
        Long accountId = requestJson.getLong("accountId");
        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        if (Check.isNull(oauthToken)) {
            throw new Exception("未获取到账户信息");
        }

        Long campaignId = requestJson.getLong("campaignId");
        if (Check.isNull(campaignId)) {
            throw new Exception("请选择广告计划");
        }

        JSONObject unitJson = new JSONObject();
        unitJson.put("campaign_id", campaignId);

        // 资源位置
        JSONArray scene_id = requestJson.getJSONArray("scene_id");
        if (!Check.isNull(scene_id)) {
            unitJson.put("scene_id", scene_id);
        }

        // 资源创作方式
        if (!Check.isNull(requestJson.getInteger("unit_type"))) {
            unitJson.put("unit_type", requestJson.getInteger("unit_type"));
        }

        //投放开始时间
        if (!Check.isNull(requestJson.getString("begin_time"))) {
            unitJson.put("begin_time", requestJson.getString("begin_time"));
        }
        // 投放结束时间
        if (!Check.isNull(requestJson.getString("end_time"))) {
            unitJson.put("end_time", requestJson.getString("end_time"));
        }
        // 投放时间段
        if (!Check.isNull(requestJson.getString("schedule_time"))) {
            unitJson.put("schedule_time", requestJson.getString("schedule_time"));
        }
        // 广告组单日预算
        if (!Check.isNull(requestJson.getLong("day_budget"))) {
            unitJson.put("day_budget", requestJson.getLong("day_budget"));
        }
        // url类型
        if (!Check.isNull(requestJson.getInteger("url_type"))) {
            unitJson.put("url_type", requestJson.getInteger("url_type"));
        }
        // url
        if (!Check.isNull(requestJson.getString("url"))) {
            unitJson.put("url", requestJson.getString("url"));
        }
        // appId
        if (!Check.isNull(requestJson.getLong("appId"))) {
            unitJson.put("app_id", requestJson.getLong("appId"));
        }
        // 创意展现方式
        if (!Check.isNull(requestJson.getInteger("show_mode"))) {
            unitJson.put("show_mode", requestJson.getInteger("show_mode"));
        }
        if (!Check.isNull(requestJson.getInteger("speed"))) {
            unitJson.put("speed", requestJson.getInteger("speed"));
        }


        // -----------------用户定向-----------
        JSONObject targetJson = new JSONObject();

        // 地域
        if (!Check.isNull(requestJson.getJSONArray("region"))) {
            targetJson.put("region", requestJson.getJSONArray("region"));
        }

        // 自定义年龄段
        JSONArray ageArr = requestJson.getJSONArray("age");
        if (!Check.isNull(ageArr)) {
            JSONObject ageJson = new JSONObject();
            ageJson.put("min", ageArr.get(0));
            ageJson.put("max", ageArr.get(1));
            targetJson.put("age", ageJson);
        }
        // 固定年龄段
        if (!Check.isNull(requestJson.getJSONArray("ages_range"))) {
            targetJson.put("ages_range", requestJson.getJSONArray("ages_range"));
        }
        // 性别
        if (!Check.isNull(requestJson.getInteger("gender"))) {
            targetJson.put("gender", requestJson.getInteger("gender"));
        }
        //操作系统
        if (!Check.isNull(requestJson.getInteger("platform_os"))) {
            targetJson.put("platform_os", requestJson.getInteger("platform_os"));
        }
        //Android版本
        if (!Check.isNull(requestJson.getInteger("android_osv"))) {
            targetJson.put("android_osv", requestJson.getInteger("android_osv"));
        }
        // iOS版本
        if (!Check.isNull(requestJson.getInteger("ios_osv"))) {
            targetJson.put("ios_osv", requestJson.getInteger("ios_osv"));
        }
        //网络环境
        if (!Check.isNull(requestJson.getInteger("network"))) {
            targetJson.put("network", requestJson.getInteger("network"));
        }
        //设备品牌
        if (!Check.isNull(requestJson.getJSONArray("device_brand"))) {
            targetJson.put("device_brand", requestJson.getJSONArray("device_brand"));
        }
        //设备价格
        if (!Check.isNull(requestJson.getJSONArray("device_price"))) {
            targetJson.put("device_price", requestJson.getJSONArray("device_price"));
        }
        //商业兴趣类型
        if (!Check.isNull(requestJson.getInteger("business_interest_type"))) {
            targetJson.put("business_interest_type", requestJson.getInteger("business_interest_type"));
        }
        // 商业兴趣
        if (!Check.isNull(requestJson.getJSONArray("business_interest"))) {
            targetJson.put("business_interest", requestJson.getJSONArray("business_interest"));
        }
        //网红粉丝
        if (!Check.isNull(requestJson.getJSONArray("fans_star"))) {
            targetJson.put("fans_star", requestJson.getJSONArray("fans_star"));
        }
        //兴趣视频用户
        if (!Check.isNull(requestJson.getJSONArray("interest_video"))) {
            targetJson.put("interest_video", requestJson.getJSONArray("interest_video"));
        }
        // APP行为-按分类
        if (!Check.isNull(requestJson.getJSONArray("app_interest"))) {
            targetJson.put("app_interest", requestJson.getJSONArray("app_interest"));
        }
        // APP行为-按APP名称
        if (!Check.isNull(requestJson.getJSONArray("app_ids"))) {
            targetJson.put("app_ids", requestJson.getJSONArray("app_ids"));
        }
        // 人群包定向
        if (!Check.isNull(requestJson.getJSONArray("population"))) {
            targetJson.put("population", requestJson.getJSONArray("population"));
        }
        // 人群包排除
        if (!Check.isNull(requestJson.getJSONArray("exclude_population"))) {
            targetJson.put("exclude_population", requestJson.getJSONArray("exclude_population"));
        }

        JSONObject intelliExtendJson = new JSONObject();

        // 开启智能扩量
        if (!Check.isNull(requestJson.getInteger("is_open"))) {
            intelliExtendJson.put("is_open", requestJson.getInteger("is_open"));
        }
        //不可突破年龄
        if (!Check.isNull(requestJson.getInteger("no_age_break"))) {
            intelliExtendJson.put("no_age_break", requestJson.getInteger("no_age_break"));
        }
        //不可突破性别
        if (!Check.isNull(requestJson.getInteger("no_gender_break"))) {
            intelliExtendJson.put("no_gender_break", requestJson.getInteger("no_gender_break"));
        }
        // 不可突破地域
        if (!Check.isNull(requestJson.getInteger("no_area_break"))) {
            intelliExtendJson.put("no_area_break", requestJson.getInteger("no_area_break"));
        }
        if (!Check.isNull(intelliExtendJson)) {
            targetJson.put("intelli_extend", intelliExtendJson);
        }

        unitJson.put("target", targetJson);


        JSONArray groupArr = requestJson.getJSONArray("groupArr");
        if (Check.isNull(groupArr)) {
            throw new Exception("请输入需要创建的广告组");
        }


        JSONObject returnJson = new JSONObject();
        // 创建条数
        returnJson.put("total", groupArr.size());
        JSONArray successArr = new JSONArray();
        JSONArray failArr = new JSONArray();

        for (int i = 0; i < groupArr.size(); i++) {
            JSONObject groupJson = groupArr.getJSONObject(i);
            if (!Check.isNull(groupJson)) {
                // 出价
                if (!Check.isNull(groupJson.getLong("bid"))) {
                    unitJson.put("bid", groupJson.getLong("bid"));
                }
                // 出价类型
                if (!Check.isNull(groupJson.getInteger("bid_type"))) {
                    unitJson.put("bid_type", groupJson.getInteger("bid_type"));
                }
                // 深度转化出价
                if (!Check.isNull(groupJson.getLong("cpa_bid"))) {
                    unitJson.put("cpa_bid", groupJson.getLong("cpa_bid"));
                }
                // 深度转化目标出价
                if (!Check.isNull(groupJson.getLong("deep_conversion_bid"))) {
                    unitJson.put("deep_conversion_bid", groupJson.getLong("deep_conversion_bid"));
                }
                // 深度转化目标
                if (!Check.isNull(groupJson.getInteger("deep_conversion_type"))) {
                    unitJson.put("deep_conversion_type", groupJson.getInteger("deep_conversion_type"));
                }
                // 优化目标
                if (!Check.isNull(groupJson.getInteger("ocpx_action_type"))) {
                    unitJson.put("ocpx_action_type", groupJson.getInteger("ocpx_action_type"));
                }
                String unitName = groupJson.getString("unitName");
                if (!Check.isNull(unitName)) {
                    unitJson.put("unit_name", unitName);
                }

                Map<String, Object> returnUnitMap = kuaishouInterfaceService.adUnitCreate(oauthToken.getAccessToken(), accountId, unitJson);
                if (!Check.isNullMap(returnUnitMap)) {
                    Integer code = (Integer) returnUnitMap.get("code");
                    if (code == 0) {
                        JSONObject successJson = new JSONObject();
                        successJson.put("unit_id", returnUnitMap.get("unitId"));
                        successJson.put("unit_name", unitName);
                        successJson.put("scene_id", scene_id);
                        successArr.add(successJson);
                    } else {
                        JSONObject failJson = new JSONObject();
                        failJson.put("unit_name", unitName);
                        failJson.put("failMessage", returnUnitMap.get("message"));
                        failArr.add(failJson);
                    }

                }

            }

        }

        returnJson.put("success", successArr);
        returnJson.put("fail", failArr);
        return returnJson;
    }

    /**
     * 获取广告组信息
     *
     * @param accountId
     * @param unitId
     * @return
     */
    @Autowired
    private KuaiShouGroupMapper groupMapper;

    @Override
    public KuaiShouGroup getUnitInfo(Long accountId, Long unitId) {
        QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("account_id", accountId);
        groupQueryWrapper.eq("unit_id", unitId);
        groupQueryWrapper.orderByDesc("create_time");
        groupQueryWrapper.last("limit 1");
        KuaiShouGroup group = groupMapper.selectOne(groupQueryWrapper);
        return group;
    }


}


