package com.ruixuan.launch.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.KuaishouAPIConstant;
import com.ruixuan.launch.entity.KuaishouLaunchGroup;
import com.ruixuan.launch.entity.KuaishouLaunchGroupRecord;
import com.ruixuan.launch.entity.KuaishouLaunchGroupTarget;
import com.ruixuan.launch.mapper.KuaishouLaunchGroupMapper;
import com.ruixuan.launch.mapper.KuaishouLaunchGroupRecordMapper;
import com.ruixuan.launch.mapper.KuaishouLaunchGroupTargetMapper;
import com.ruixuan.launch.service.IKuaishouLaunchGroupService;
import com.ruixuan.launch.unitls.APIUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 广告组信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-06-23
 */
@Slf4j
@Service
public class KuaishouLaunchGroupServiceImpl implements IKuaishouLaunchGroupService {
    @Autowired
    private KuaishouLaunchGroupMapper kuaishouLaunchGroupMapper;

    @Autowired
    private KuaishouLaunchGroupTargetMapper kuaishouLaunchGroupTargetMapper;

    @Autowired
    private KuaishouLaunchGroupRecordMapper kuaishouLaunchGroupRecordMapper;

    /**
     * 查询广告组信息
     *
     * @param id 广告组信息主键
     * @return 广告组信息
     */
    @Override
    public KuaishouLaunchGroup selectKuaishouLaunchGroupById(String id) {
        return kuaishouLaunchGroupMapper.selectKuaishouLaunchGroupById(id);
    }

    /**
     * 查询广告组信息列表
     *
     * @param kuaishouLaunchGroup 广告组信息
     * @return 广告组信息
     */
    @Override
    public List<KuaishouLaunchGroup> selectKuaishouLaunchGroupList(KuaishouLaunchGroup kuaishouLaunchGroup) {
        return kuaishouLaunchGroupMapper.selectKuaishouLaunchGroupList(kuaishouLaunchGroup);
    }

    /**
     * 新增广告组信息
     *
     * @param kuaishouLaunchGroup 广告组信息
     * @return 结果
     */
    @Override
    public Long insertKuaishouLaunchGroup(JSONObject requestJson, String token) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("advertiser_id", requestJson.getLong("accountId"));
        param.put("campaign_id", requestJson.getLong("campaignId"));
        param.put("name", requestJson.getString("newUnitName"));
        param.put("bid_type", requestJson.getInteger("bidType"));
        if (Check.isNotNull(requestJson.getLong("cpaBid"))) {
            param.put("cpa_bid", requestJson.getLong("cpaBid"));
        }
        param.put("ocpx_action_type", requestJson.getInteger("ocpxActionType"));
        if (Check.isNotNull(requestJson.getDouble("roiRatio"))) {
            param.put("roi_ratio", requestJson.getDouble("roiRatio"));
        }
        param.put("scene_id", requestJson.getJSONArray("sceneId"));
        param.put("unit_type", requestJson.getInteger("unitType"));

        if (Check.isNotNull(requestJson.getString("beginTimeStr"))) {
            param.put("begin_time_str", requestJson.getString("beginTimeStr"));
        } else {
            param.put("begin_time_str", DateUtils.getDate());
        }
        if (Check.isNotNull(requestJson.getString("endTimeStr"))) {
            param.put("end_time_str", requestJson.getString("endTimeStr"));
        }
        if (Check.isNotNull(requestJson.getString("scheduleTime"))) {
            param.put("schedule_time", requestJson.getString("scheduleTime"));
        }
        if (Check.isNotNull(requestJson.getLong("groupDayBudget")) && requestJson.getLong("groupDayBudget") != -1) {
            param.put("day_budget", requestJson.getLong("groupDayBudget"));
        }
        param.put("support_type", requestJson.getInteger("supportType"));
        param.put("show_mode", requestJson.getInteger("showMode"));
        param.put("speed", requestJson.getInteger("speed"));
        if (Check.isNotNull(requestJson.getLong("itemId"))) {
            param.put("item_id", requestJson.getLong("itemId"));
        }
        param.put("merchant_item_put_type", requestJson.getInteger("merchantItemPutType"));
        if (Check.isNotNull(requestJson.getLong("shoppingCarProductId"))) {
            param.put("shopping_car_product_id", requestJson.getLong("shoppingCarProductId"));
        }

        JSONObject target = getTarget(requestJson);
        param.put("target", target);
        if (Check.isNotNull(requestJson.getInteger("liveUserId"))) {
            param.put("live_user_id", requestJson.getInteger("liveUserId"));
        }

        Long unitId = -1L;
        KuaishouLaunchGroupRecord record = JSONObject.parseObject(requestJson.toJSONString(), KuaishouLaunchGroupRecord.class);
        JSONObject result = APIUtil.getApiResult(KuaishouAPIConstant.CREATE_UNIT, token, param);
        if (result.getInteger("code") == 0) {
            result = result.getJSONObject("data");
            JSONObject detail = result.getJSONArray("detail").getJSONObject(0);
            KuaishouLaunchGroup group = JSONObject.parseObject(requestJson.toJSONString(), KuaishouLaunchGroup.class);
            unitId = detail.getLong("id");
            group.setUnitId(unitId);
            group.setId(UUID.randomUUID().toString().replace("-", ""));
            group.setStatDate(DateUtils.getDate());
            kuaishouLaunchGroupMapper.insertKuaishouLaunchGroup(group);
            record.setMessage("success");
            record.setUnitId(unitId);
            KuaishouLaunchGroupTarget targetEnt = JSONObject.parseObject(target.toJSONString(), KuaishouLaunchGroupTarget.class);
            targetEnt.setAccountId(requestJson.getLong("accountId"));
            targetEnt.setUnitId(detail.getLong("id"));
            kuaishouLaunchGroupTargetMapper.insertKuaishouLaunchGroupTarget(targetEnt);
        } else {
            record.setMessage(result.getString("message"));
            log.error("广告组创建失败，账户{}，{}", record.getAccountId(), result.toJSONString());
        }
        record.setStrategyId(requestJson.getLong("id"));
        record.setId(UUID.randomUUID().toString().replace("-", ""));
        record.setStatDate(DateUtils.getDate());
        kuaishouLaunchGroupRecordMapper.insertKuaishouLaunchGroupRecord(record);
        return unitId;
    }


    /*定向数据*/
    private JSONObject getTarget(JSONObject requestJson) {
        JSONObject targetJson = new JSONObject();

        // 地域
        if (Check.isNotNull(requestJson.getJSONArray("region"))) {
            targetJson.put("region", requestJson.getJSONArray("region"));
        } else {
            targetJson.put("region", new JSONArray());
        }
        // 地域类型
        if (Check.isNotNull(requestJson.getInteger("regionType"))) {
            targetJson.put("region_type", requestJson.getInteger("regionType"));
        } else {
            targetJson.put("region_type", 0);
        }
        // 自定义年龄段
        JSONArray ageArr = requestJson.getJSONArray("age");
        if (Check.isNotNull(ageArr)) {
            targetJson.put("age", ageArr);
        }
        // 性别
        if (!Check.isNull(requestJson.getInteger("genderType"))) {
            targetJson.put("gender_type", requestJson.getInteger("genderType"));
        }
        // 人群包定向
        if (!Check.isNull(requestJson.getJSONArray("population"))) {
            targetJson.put("population", requestJson.getJSONArray("population"));
        }
        // 人群包排除
        if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
            targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
        }
        // 付费人群包 id
        if (!Check.isNull(requestJson.getJSONArray("paidAudience"))) {
            targetJson.put("paid_audience", requestJson.getJSONArray("paidAudience"));
        }

        //快手网红信息
        if (Check.isNotNull(requestJson.getInteger("behaviorList"))) {
            JSONObject celebrityInfo = new JSONObject();
            celebrityInfo.put("behavior_list", requestJson.getJSONArray("behaviorList"));
            if (Check.isNotNull(requestJson.getJSONArray("fansStarList"))) {
                celebrityInfo.put("fans_star_list", requestJson.getJSONArray("fansStarList"));
            }
            targetJson.put("celebrity_info", celebrityInfo);
        }

        //购物意图
        if (Check.isNotNull(requestJson.getJSONObject("purchaseIntention"))) {
            targetJson.put("purchase_intention", requestJson.getJSONObject("purchaseIntention"));
        }
        return targetJson;
    }

    /**
     * 修改广告组信息
     *
     * @param kuaishouLaunchGroup 广告组信息
     * @return 结果
     */
    @Override
    public int updateKuaishouLaunchGroup(KuaishouLaunchGroup kuaishouLaunchGroup) {
        return kuaishouLaunchGroupMapper.updateKuaishouLaunchGroup(kuaishouLaunchGroup);
    }

    /**
     * 批量删除广告组信息
     *
     * @param ids 需要删除的广告组信息主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouLaunchGroupByIds(String[] ids) {
        return kuaishouLaunchGroupMapper.deleteKuaishouLaunchGroupByIds(ids);
    }

    @Override
    public List<KuaishouLaunchGroupRecord> queryGroupRecord(Long accountId, Long strategyId) {
        return kuaishouLaunchGroupRecordMapper.queryGroupRecord(accountId, strategyId, DateUtils.getDate());
    }

    /**
     * 删除广告组信息信息
     *
     * @param id 广告组信息主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouLaunchGroupById(String id) {
        return kuaishouLaunchGroupMapper.deleteKuaishouLaunchGroupById(id);
    }
}