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

import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.PropertiesUtils;
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.ByteDanceCampaign;
import cn.com.ctop.toutiao.entity.ByteDanceCampaignTemplate;
import cn.com.ctop.toutiao.mapper.ByteDanceCampaignMapper;
import cn.com.ctop.toutiao.mapper.ByteDanceCampaignTemplateMapper;
import cn.com.ctop.toutiao.service.IByteDanceCampaignTemplateService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 今日头条广告组模板信息
 * @Author: jeecg-boot
 * @Date: 2019-07-22
 * @Version: V1.0
 */
@Slf4j
@Service
public class ByteDanceCampaignTemplateServiceImpl extends ServiceImpl<ByteDanceCampaignTemplateMapper, ByteDanceCampaignTemplate> implements IByteDanceCampaignTemplateService {
    @Autowired
    private ByteDanceCampaignTemplateMapper campaignTemplateMapper;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private ByteDanceCampaignMapper campaignMapper;

    @Override
    public Map<String, Object> insertTemplate(ByteDanceCampaignTemplate template) {
        Map<String, Object> resultMap = new HashMap<>();
        String name = template.getCampaignName();
        Long id = template.getId();
        if (null == name || "".equals(name)) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.TEMPLATE_NAME_IS_NULL.getCode());
            return resultMap;
        }
        QueryWrapper<ByteDanceCampaignTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("campaign_name", template.getCampaignName());
        if (null != template.getId() && template.getId() != 0) {
            queryWrapper.ne("id", template.getId());
        }
        ByteDanceCampaignTemplate templateExist = getOne(queryWrapper);
        if (null != templateExist) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.TEMPLATE_NAME_HAS_EXIST.getCode());
            return resultMap;
        }
        template.setStatus(1);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        template.setAdvertiserId(user.getId());
        Date now = new Date();
        template.setCreateTime(now);
        template.setUpdateTime(now);
        this.saveOrUpdate(template);
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        return resultMap;
    }

    @Override
    public Result<IPage<ByteDanceCampaignTemplate>> getList(ByteDanceCampaignTemplate template, Integer pageNo, Integer pageSize, HttpServletRequest req) {
        Result<IPage<ByteDanceCampaignTemplate>> result = new Result<>();
        QueryWrapper<ByteDanceCampaignTemplate> queryWrapper = QueryGenerator.initQueryWrapper(template, req.getParameterMap());
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String advertiserId = user.getId();
        queryWrapper.eq("advertiser_id", advertiserId).orderByDesc("create_time");
        Page<ByteDanceCampaignTemplate> page = new Page<>(pageNo, pageSize);
        IPage<ByteDanceCampaignTemplate> pageList = this.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @Override
    public Map<String, Object> campaignCreate(String accountId, String campaignName, String budgetMode, Integer budget, String landingType) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("campaign_name", campaignName);
        params.put("budget_mode", budgetMode);
        params.put("budget", budget);
        params.put("landing_type", landingType);
        JSONObject result = createCampaign(params, token.getAccessToken());
        Integer code = result.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("创建广告组接口异常==》accountId:{},message:{}", accountId, result.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "创建广告组接口异常");
            return resultMap;
        }
        JSONObject data = result.getJSONObject("data");
        if (null == data) {
            log.info("广告组创建异常==》accountId:{},message:{}", accountId, result.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组创建异常");
            return resultMap;
        }
        Long id = data.getLong("campaign_id");
        ByteDanceCampaign campaign = new ByteDanceCampaign(id, token, campaignName, budgetMode, budget, landingType);
        campaignMapper.insert(campaign);
        resultMap.put("code", 0);
        resultMap.put("message", "广告组创建成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> getSuggestCover(String accountId, String videoId) {
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        return suggestVideo(token, videoId);
    }

    public JSONObject suggestVideo(CtopOauthToken token, String videoId) {
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/tools/video_cover/suggest/";
        // 请求参数
        JSONObject data = new JSONObject();
        data.put("advertiser_id", token.getAccountId());
        data.put("video_id", videoId);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, data);
    }

    @Override
    public Map<String, Object> campaignCreate(CtopOauthToken token, ByteDanceCampaignTemplate template) {
        Map<String, Object> resultMap = new HashMap<>();
        //2: 根据token以及用户id获取用户信息数据
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("campaign_name", template.getCampaignName());
        params.put("budget_mode", template.getCampaignBudget());
        params.put("budget", template.getBudgetDaily());
        params.put("landing_type", template.getPromotionPurpose());
        JSONObject result = createCampaign(params, token.getAccessToken());
        Integer code = result.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("创建广告组接口异常==》accountId:{},message:{}", token.getAccountId(), result.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", result.getString("message"));
            return resultMap;
        }
        JSONObject data = result.getJSONObject("data");
        if (null == data) {
            log.info("广告组创建异常==》accountId:{},message:{}", token.getAccountId(), result.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组创建异常");
            return resultMap;
        }
        Long id = data.getLong("campaign_id");
        ByteDanceCampaign campaign = new ByteDanceCampaign(id, token, template);
        //清除清数据，插入新数据
        campaignMapper.insert(campaign);
        resultMap.put("code", 0);
        resultMap.put("message", "广告组创建成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> campaignCreate(String getAccountId, Long campaignId, String name) {
        ByteDanceCampaignTemplate template = campaignTemplateMapper.selectById(campaignId);
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(getAccountId);
        Map<String, Object> resultMap = new HashMap<>();
        //2: 根据token以及用户id获取用户信息数据
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_hh_mm_ss");
        params.put("campaign_name", name + "_广告组_" + sdf.format(new Date()) + "汇创思拓_" + System.currentTimeMillis());
        params.put("budget_mode", template.getCampaignBudget());
        params.put("budget", template.getBudgetDaily());
        params.put("landing_type", template.getPromotionPurpose());
        JSONObject result = createCampaign(params, token.getAccessToken());
        Integer code = result.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("创建广告组接口异常==》accountId:{},message:{}", token.getAccountId(), result.getString("message"));
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", result.getString("message"));
            return resultMap;
        }
        JSONObject data = result.getJSONObject("data");
        if (null == data) {
            log.info("广告组创建异常==》accountId:{},message:{}", token.getAccountId(), result.getString("message"));
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", "广告组创建异常");
            return resultMap;
        }
        Long id = data.getLong("campaign_id");
        ByteDanceCampaign campaign = new ByteDanceCampaign(id, token, template);
        //清除清数据，插入新数据
        campaignMapper.insert(campaign);
        resultMap.put("campaignId", id);
        resultMap.put("success", true);
        resultMap.put("code", 0);
        resultMap.put("message", "广告组创建成功");
        return resultMap;
    }

    public JSONObject createCampaign(JSONObject data, String token) {
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_create");
        return HttpUtils.bytedancePostRequest(token, url, data);
    }
}
