package com.ruixuan.launch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.KuaishouAPIConstant;
import com.ruixuan.common.utils.http.HttpUtil;
import com.ruixuan.launch.entity.AccountToken;
import com.ruixuan.launch.entity.KuaishouLaunchCampaign;
import com.ruixuan.launch.entity.KuaishouLaunchCampaignRecord;
import com.ruixuan.launch.mapper.KuaishouLaunchCampaignMapper;
import com.ruixuan.launch.mapper.KuaishouLaunchCampaignRecordMapper;
import com.ruixuan.launch.service.IAccountTokenService;
import com.ruixuan.launch.service.IKuaishouLaunchCampaignService;
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 KuaishouLaunchCampaignServiceImpl implements IKuaishouLaunchCampaignService {
    @Autowired
    private KuaishouLaunchCampaignMapper kuaishouLaunchCampaignMapper;
    @Autowired
    private KuaishouLaunchCampaignRecordMapper kuaishouLaunchCampaignRecordMapper;

    @Autowired
    private IAccountTokenService tokenService;

    /**
     * 查询广告计划信息
     *
     * @param id 广告计划信息主键
     * @return 广告计划信息
     */
    @Override
    public KuaishouLaunchCampaign selectKuaishouLaunchCampaignById(String id) {
        return kuaishouLaunchCampaignMapper.selectKuaishouLaunchCampaignById(id);
    }

    /**
     * 查询广告计划信息列表
     *
     * @param kuaishouLaunchCampaign 广告计划信息
     * @return 广告计划信息
     */
    @Override
    public List<KuaishouLaunchCampaign> selectKuaishouLaunchCampaignList(KuaishouLaunchCampaign kuaishouLaunchCampaign) {
        return kuaishouLaunchCampaignMapper.selectKuaishouLaunchCampaignList(kuaishouLaunchCampaign);
    }

    /**
     * 新增广告计划信息
     */
    @Override
    public Long insertKuaishouLaunchCampaign(JSONObject requestJson, String token) {
        try {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("advertiser_id", requestJson.getLong("accountId"));
            param.put("name", requestJson.getString("campaignName"));
            param.put("type", requestJson.getInteger("campaignType"));
            param.put("promotion_type", requestJson.getInteger("promotionType"));
            if (Check.isNotNull(requestJson.getLong("dayBudget")) && requestJson.getLong("dayBudget") != -1) {
                param.put("day_budget", requestJson.getLong("dayBudget"));
            }
            if (Check.isNotNull(requestJson.getJSONArray("budgetSchedule"))) {
                param.put("budget_schedule", requestJson.getJSONArray("budgetSchedule"));
            }
            JSONObject resultJson = APIUtil.getApiResult(KuaishouAPIConstant.CREATE_CAMPAIGN, token, param);
            Long campaignId = -1L;
            KuaishouLaunchCampaignRecord record = JSONObject.parseObject(requestJson.toJSONString(), KuaishouLaunchCampaignRecord.class);

            if (resultJson.getInteger("code") == 0) {
                JSONObject entity = resultJson.getJSONObject("data").getJSONArray("detail").getJSONObject(0);
                KuaishouLaunchCampaign campaign = JSONObject.parseObject(requestJson.toJSONString(), KuaishouLaunchCampaign.class);
                campaignId = entity.getLong("id");
                campaign.setCampaignId(campaignId);
                if (Check.isNull(campaign.getDayBudget())) {
                    campaign.setDayBudget(0L);
                }
                campaign.setPutStatus(1);
                campaign.setId(UUID.randomUUID().toString().replace("-", ""));
                campaign.setStatDate(DateUtils.getDate());
                kuaishouLaunchCampaignMapper.insertKuaishouLaunchCampaign(campaign);
                record.setMessage("success");
                record.setCampaignId(campaignId);
            } else {
                record.setMessage(resultJson.getString("message"));
                log.error("创建计划失败，账户{}，{}", requestJson.getLong("accountId"), resultJson.toJSONString());
            }
            record.setStrategyId(requestJson.getLong("id"));
            record.setId(UUID.randomUUID().toString().replace("-", ""));
            record.setStatDate(DateUtils.getDate());
            kuaishouLaunchCampaignRecordMapper.insertKuaishouLaunchCampaignRecord(record);
            return campaignId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1L;
    }


    public ResultResponse getCampaignInfo(Long accountId, Long id, String level, String startTime, String endTime) {
        try {
            AccountToken accountToken = tokenService.getAccountToken(accountId);

            String url = "https://ad.e.kuaishou.com" + KuaishouAPIConstant.SEARCH_AD;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", accountToken.getAccessToken());
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("advertiser_id", accountId);
            JSONObject params = new JSONObject();
            params.put("start_time", DateUtils.timeToStamp(startTime));
            params.put("end_time", DateUtils.timeToStamp(endTime));
//            params.put("start_time", DateUtils.timeToStamp(DateUtils.getDate().concat(" 00:00:01")));
//            params.put("end_time", DateUtils.timeToStamp(DateUtils.getDate().concat(" 23:59:59")));
            params.put("search_level", level);//1-计划 2-组 3-创意
            if (Check.isNotNull(id)) {
                params.put("name", id);
            }
            param.put("param", params);
            JSONObject pageInfo = new JSONObject();
            pageInfo.put("page", 1);
            pageInfo.put("page_size", 20);
            param.put("page_info", pageInfo);
            System.out.println(params);
            String result = HttpUtil.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            System.out.println(resultJson);
            if (Check.isNotNull(resultJson) && resultJson.getInteger("code") == 0) {
//                JSONObject data = resultJson.getJSONObject("data").getJSONArray("data").getJSONObject(0);
//                campaign.setPutStatus(data.getInteger("put_status"));
//                campaign.setId(UUID.randomUUID().toString().replace("-", ""));
//                campaign.setCampaignId(id);
//                kuaishouLaunchCampaignMapper.insertKuaishouLaunchCampaign(campaign);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultResponse.success();

    }

    @Override
    public KuaishouLaunchCampaign getOne(JSONObject parameter) {
        return kuaishouLaunchCampaignMapper.getOne(parameter);
    }

    /**
     * 修改广告计划信息
     *
     * @param kuaishouLaunchCampaign 广告计划信息
     * @return 结果
     */
    @Override
    public int updateKuaishouLaunchCampaign(KuaishouLaunchCampaign kuaishouLaunchCampaign) {
        return kuaishouLaunchCampaignMapper.updateKuaishouLaunchCampaign(kuaishouLaunchCampaign);
    }

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

    /**
     * 删除广告计划信息信息
     *
     * @param id 广告计划信息主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouLaunchCampaignById(String id) {
        return kuaishouLaunchCampaignMapper.deleteKuaishouLaunchCampaignById(id);
    }
}