package cn.com.ctop.toutiao.service.impl;

import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.toutiao.entity.*;
import cn.com.ctop.toutiao.mapper.*;
import cn.com.ctop.toutiao.service.IByteDanceAdvertisePlanService;
import cn.com.ctop.toutiao.service.IByteDanceAdvertiserDataService;
import cn.com.ctop.toutiao.service.IBytedanceAdvertisePlanTemplateService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 广告计划模板信息
 * @Author: jeecg-boot
 * @Date: 2019-07-28
 * @Version: V1.0
 */
@Service
public class BytedanceAdvertisePlanTemplateServiceImpl extends ServiceImpl<BytedanceAdvertisePlanTemplateMapper, BytedanceAdvertisePlanTemplate> implements IBytedanceAdvertisePlanTemplateService {

    @Autowired
    private ByteDanceCampaignMapper campaignMapper;
    @Autowired
    private ByteDanceBudgetTemplateMapper budgetTemplateMapper;
    @Autowired
    private BytedanceDeliveryTargetTemplateMapper deliveryTargetTemplateMapper;
    @Autowired
    private ByteDanceUserOrientationTemplateMapper userOrientationTemplateMapper;
    @Autowired
    private IByteDanceAdvertisePlanService advertisePlanService;
    @Autowired
    private BytedanceAdvertisePlanTemplateMapper templateMapper;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;

    @Override
    public Map<String, Object> insertTemplate(BytedanceAdvertisePlanTemplate template, String accountId) {
        Map<String, Object> resultMap = new HashMap<>();
        template.setStatus(1);
        Date now = new Date();
        template.setCreateTime(now);
        template.setUpdateTime(now);
        templateMapper.insert(template);
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        return resultMap;
    }

    /**
     * @param campaignId
     * @param getAccountId
     * @param deliveryRange
     * @param userorentationId
     * @param budgetId
     * @param deliverytargetId
     * @return
     */
    @Override
    public Map<String, Object> planCreate(Long campaignId, String getAccountId, String deliveryRange, Long userorentationId, Long budgetId, Long deliverytargetId, String getName, String convertId) {
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(getAccountId);
        ByteDanceBudgetTemplate budgetTemplate = budgetTemplateMapper.selectById(budgetId);
        BytedanceDeliveryTargetTemplate deliveryTargetTemplate = deliveryTargetTemplateMapper.selectById(deliverytargetId);
        ByteDanceUserOrientationTemplate userOrientationTemplate = userOrientationTemplateMapper.selectById(userorentationId);
        ByteDanceCampaign campaign = campaignMapper.selectById(campaignId);
        JSONObject data = new JSONObject();
        if (null != userOrientationTemplate) {
            data = advertiserDataService.setUserOrentationData(data, userOrientationTemplate);
        }
        //广告组id
        data.put("campaign_id", campaignId);
        //投放范围
        data.put("delivery_range", deliveryRange);
        //(1):投放目标
        //投放目标 转化量，点击量，展示量相关 未找到
        //下载方式 下载链接/落地页链接
        data.put("download_type", deliveryTargetTemplate.getDownloadType());
        if (null != deliveryTargetTemplate.getDownloadType() && !"".equals(deliveryTargetTemplate.getDownloadType()) && "DOWNLOAD_URL".equals(deliveryTargetTemplate.getDownloadType())) {
            //下载链接
            data.put("download_url", deliveryTargetTemplate.getDownloadUrl());
            //应用包名
            data.put("package", deliveryTargetTemplate.getPackageName());
        }

        if (null != deliveryTargetTemplate.getDownloadType() && !"".equals(deliveryTargetTemplate.getDownloadType()) && "EXTERNAL_URL".equals(deliveryTargetTemplate.getDownloadType())) {
            //落地页链接
            data.put("external_url", deliveryTargetTemplate.getExternalUrl());
        }
        if (null != campaign.getLandingType() && "APP".equals(campaign.getLandingType()) && null != deliveryTargetTemplate.getDownloadType() && "DOWNLOAD_URL".equals(deliveryTargetTemplate.getDownloadType())) {
            data.put("app_type", "APP_ANDROID");
        }

        //(2)人群定向目前空置
        //（3）：预算与出价
        //广告预算类型 日预算、总预算
        data.put("budget_mode", budgetTemplate.getBudgetPriceMode());
        //广告预算 //需要大于bid
        data.put("budget", budgetTemplate.getBudgetPrice());
        //转化出价（ocpm请填写 cpa_bid）
        data.put("cpa_bid", budgetTemplate.getConvertPrice());
        data.put("convert_id", convertId);
        //广告投放时间类型
        data.put("schedule_type", budgetTemplate.getFlowDateType());
        //广告投放开始时间
        data.put("start_time", budgetTemplate.getStartDate());
        //广告投放结束时间
        data.put("end_time", budgetTemplate.getEndDate());
        /**
         * 广告投放时段，默认全时段投放，格式是48*7位字符串，且都是0或1。也就是以半个小时为最小粒度，周一至周日每天分为48个区段，0为不投放，1为投放，不传、全传0、全传1均代表全时段投放。
         */
        //付费方式
        data.put("pricing", budgetTemplate.getPriceType());
        //广告投放速度类型 (投放方式) 优先跑量，均衡投放，优先低成本
        data.put("flow_control_mode", budgetTemplate.getFlowControlMode());
        //过滤已转化用户类型 只有投放目标为转化量时，才需要该字段
        data.put("hide_if_converted", budgetTemplate.getFilterType());

        data.put("name", getName + "_计划_" + System.currentTimeMillis());
        return advertisePlanService.advertiserPlanCreate(token, campaignId, data.toJSONString());
    }
}
