package cn.com.ctop.kuaishou.modules.report.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.report.entity.EtlKuaiShouGroupDailyReport;
import cn.com.ctop.kuaishou.modules.report.mapper.EtlKuaiShouGroupDailyReportMapper;
import cn.com.ctop.kuaishou.modules.report.service.IEtlKuaiShouGroupDailyReportService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 快手组日报数据清洗
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-03-09
 */
@Service
@Slf4j
public class EtlKuaiShouGroupDailyReportServiceImpl extends ServiceImpl<EtlKuaiShouGroupDailyReportMapper, EtlKuaiShouGroupDailyReport> implements IEtlKuaiShouGroupDailyReportService {
    @Autowired
    private EtlKuaiShouGroupDailyReportMapper groupDailyReportMapper;
    @Autowired
    private IKuaiShouGroupService groupService;


    @Override
    public void getGroupReport(Long accountId, String accessToken, String startDate, String endDate, Integer page) {
        // log.info("获取广告组日报，accountId:{},开始时间:{},结束时间：{}", token.getAccountId(), DateUtils.formatDate(startDate), DateUtils.formatDate(endDate));
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GTOUP_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<>();
        if (!Check.isNull(startDate)) {
            param.put("start_date", startDate);
        }
        if (!Check.isNull(endDate)) {
            param.put("end_date", endDate);
        }
        param.put("advertiser_id", accountId);
        param.put("temporal_granularity", "DAILY");
        param.put("page_size", 2000);
        param.put("page", page);
        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告组报表异常:{},accountId:{}", message, accountId);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.info("快手广告组报表信息为空=》accountId:{}", accountId);
            return;
        }
        cleanGroupData(accountId, details);
        getGroupReport(accountId, accessToken, startDate, endDate, page + 1);
    }

    @Override
    public Result<Object> queryPageList(JSONObject request) {
        Integer pageNo = request.getInteger("pageNo");
        Integer pageSize = request.getInteger("pageSize");
        if (Check.isNull(pageNo)) {
            pageNo = 1;
        }
        if (Check.isNull(pageSize)) {
            pageSize = 10;
        }
        Long accountId = request.getLong("accountId");
        String sortCode = request.getString("sortCode");
        String sortType = request.getString("sortType");
        if (Check.isNull(sortCode)) {
            sortCode = "charge";
        }
        if (Check.isNull(sortType)) {
            sortType = "DESC";
        }
        Long total = groupDailyReportMapper.getTotal(accountId);
        PageHelper.startPage(pageNo, pageSize, false);
        PageInfo pageInfo = new PageInfo(groupDailyReportMapper.queryPageList(accountId, sortCode, sortType));
        pageInfo.setTotal(total);
        return Result.ok(pageInfo);
    }

    @Override
    public void updateStatus(Long accountId, Long unitId, Integer putStatus) {
        groupDailyReportMapper.updateStatus(accountId, unitId, putStatus);
    }

    /**
     * 数据清洗
     *
     * @param details
     */
    @Override
    public void cleanGroupData(Long accountId, JSONArray details) {
        if (Check.isNull(details)) {
            return;
        }
        List<EtlKuaiShouGroupDailyReport> addList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject groupJson = details.getJSONObject(i);
            EtlKuaiShouGroupDailyReport groupDailyReport = new EtlKuaiShouGroupDailyReport();
            groupDailyReport.setAccountId(accountId);
            groupDailyReport.setCampaignId(groupJson.getLong("campaign_id"));
            groupDailyReport.setCampaignName(groupJson.getString("campaign_name"));
            groupDailyReport.setUnitId(groupJson.getLong("unit_id"));
            groupDailyReport.setUnitName(groupJson.getString("unit_name"));
            groupDailyReport.setCharge(groupJson.getBigDecimal("charge"));
            groupDailyReport.setPhotoShow(groupJson.getLong("show"));
            groupDailyReport.setAclick(groupJson.getLong("aclick"));
            groupDailyReport.setBclick(groupJson.getLong("bclick"));
            groupDailyReport.setDownloadStarted(groupJson.getLong("download_started"));
            groupDailyReport.setDownloadCompleted(groupJson.getLong("download_completed"));
            groupDailyReport.setActivation(groupJson.getLong("activation"));
            groupDailyReport.setEventPayFirstDay(groupJson.getLong("event_pay_first_day"));
            groupDailyReport.setEventPay(groupJson.getLong("event_pay"));
            groupDailyReport.setEventRegister(groupJson.getLong("event_register"));
            groupDailyReport.setEventJinJianApp(groupJson.getLong("event_jin_jian_app"));
            groupDailyReport.setEventOrderPaid(groupJson.getLong("event_order_paid"));
            groupDailyReport.setEventNextDayStay(groupJson.getLong("event_next_day_stay"));
            groupDailyReport.setStatDate(groupJson.getString("stat_date"));
            Double play_3s_ratio = groupJson.getDouble("play_3s_ratio");
            Long aclick = groupJson.getLong("aclick");
            Double v = aclick * play_3s_ratio;
            groupDailyReport.setPlay3sCount(v.longValue());
            Long eventAppInvoked = groupJson.getLong("event_app_invoked");
            groupDailyReport.setEventAppInvoked(eventAppInvoked);
            addList.add(groupDailyReport);
        }
        if (!Check.isNull(addList)) {
            addList = getBid(accountId, addList);
            groupDailyReportMapper.replaceBatch(addList);
        }
    }

    private List<EtlKuaiShouGroupDailyReport> getBid(Long accountId, List<EtlKuaiShouGroupDailyReport> addList) {
        if (Check.isNull(addList)) {
            return addList;
        }
        Map<Long, Long> unitIdMap = new HashMap<>();
        for (EtlKuaiShouGroupDailyReport groupDailyReport : addList) {
            unitIdMap.put(groupDailyReport.getUnitId(), groupDailyReport.getUnitId());
        }
        Map<Long, JSONObject> unitMap = groupService.getBidMapByMap(accountId, unitIdMap);
        if (Check.isNullMap(unitMap)) {
            return addList;
        }
        for (EtlKuaiShouGroupDailyReport groupDailyReport : addList) {
            JSONObject unitJson = unitMap.get(groupDailyReport.getUnitId());
            if (Check.isNull(unitJson)) {
                continue;
            }
            groupDailyReport.setUnitStatus(unitJson.getInteger("unitStatus"));
            groupDailyReport.setBidType(unitJson.getInteger("bidType"));
            groupDailyReport.setBid(unitJson.getLong("bid"));
        }

        return addList;

    }


}
