package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.AdqAdvertiserInfo;
import cn.com.ctop.common.module.mapper.AdqAdvertiserInfoMapper;
import cn.com.ctop.common.module.service.IAdqAdvertiserInfoService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class AdqAdvertiserInfoServiceImpl extends ServiceImpl<AdqAdvertiserInfoMapper, AdqAdvertiserInfo> implements IAdqAdvertiserInfoService {

    private static final String API_URL = "https://api.e.qq.com/v3.0/advertiser/get";

    private static final String[] FIELDS = {
            "account_id", "daily_budget", "registration_type", "corporation_name",
            "corporation_licence", "certification_image_id", "certification_image",
            "individual_qualification", "area_code", "mdm_id", "mdm_name",
            "system_industry_id", "customized_industry", "introduction_url",
            "corporate_brand_name", "memo", "system_status", "reject_message",
            "is_adx", "business_alias", "contact_person", "contact_person_email",
            "contact_person_telephone", "contact_person_mobile", "websites",
            "agency_account_id", "operators"
    };

    @Resource
    private AdqAdvertiserInfoMapper adqAdvertiserInfoMapper;

    @Override
    public void syncAdvertiserInfo() {
        List<JSONObject> tokenList = adqAdvertiserInfoMapper.getAdqAccessTokenList();
        if (Check.isNull(tokenList)) {
            log.warn("未获取到ADQ授权token列表");
            return;
        }
        for (JSONObject tokenJson : tokenList) {
            Long adminAdvertiserId = tokenJson.getLong("adminAdvertiserId");
            String accessToken = tokenJson.getString("accessToken");
            if (Check.isNull(accessToken)) {
                continue;
            }
            try {
                getAdvertiserByPage(adminAdvertiserId, accessToken, 1);
            } catch (Exception e) {
                log.error("同步腾讯广告客户信息异常，adminAdvertiserId：{}", adminAdvertiserId, e);
            }
        }
    }

    private void getAdvertiserByPage(Long adminAdvertiserId, String accessToken, int page) {
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", accessToken);
        params.put("timestamp", System.currentTimeMillis() / 1000);
        params.put("nonce", UUID.randomUUID().toString().replace("-", "").substring(0, 32));
        params.put("fields", buildFieldsParam());
        params.put("pagination_mode", "PAGINATION_MODE_NORMAL");
        params.put("page", page);
        params.put("page_size", 100);

        String result = HttpUtils.httpGet(API_URL, params, new HashMap<>());
        if (Check.isNull(result)) {
            log.error("请求腾讯广告客户信息接口返回为空，adminAdvertiserId：{}", adminAdvertiserId);
            return;
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (code == null || code != 0) {
            log.error("请求腾讯广告客户信息接口失败，adminAdvertiserId：{}，message：{}", adminAdvertiserId, resultJson.getString("message"));
            return;
        }
        JSONObject data = resultJson.getJSONObject("data");
        if (Check.isNull(data)) {
            return;
        }
        JSONArray list = data.getJSONArray("list");
        if (Check.isNull(list) || list.isEmpty()) {
            return;
        }

        List<AdqAdvertiserInfo> infoList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject item = list.getJSONObject(i);
            AdqAdvertiserInfo info = parseAdvertiserInfo(item, adminAdvertiserId);
            infoList.add(info);
        }

        if (!infoList.isEmpty()) {
            adqAdvertiserInfoMapper.replaceBatch(infoList);
        }

        // 判断是否有下一页
        JSONObject pageInfo = data.getJSONObject("page_info");
        if (pageInfo != null) {
            int totalPage = pageInfo.getIntValue("total_page");
            if (page < totalPage) {
                getAdvertiserByPage(adminAdvertiserId, accessToken, page + 1);
            }
        }
    }

    private AdqAdvertiserInfo parseAdvertiserInfo(JSONObject item, Long adminAdvertiserId) {
        AdqAdvertiserInfo info = new AdqAdvertiserInfo();
        info.setAdminAdvertiserId(adminAdvertiserId);
        info.setAccountId(item.getLong("account_id"));
        info.setDailyBudget(item.getLong("daily_budget"));
        info.setRegistrationType(item.getString("registration_type"));
        info.setCorporationName(item.getString("corporation_name"));
        info.setCorporationLicence(item.getString("corporation_licence"));
        info.setCertificationImageId(item.getString("certification_image_id"));
        info.setCertificationImage(item.getString("certification_image"));

        // 解析身份证明
        JSONObject qualification = item.getJSONObject("individual_qualification");
        if (qualification != null) {
            info.setIndividualQualificationName(qualification.getString("name"));
            info.setIndividualQualificationIdNumber(qualification.getString("identification_number"));
        }

        info.setAreaCode(item.getInteger("area_code"));
        info.setMdmId(item.getLong("mdm_id"));
        info.setMdmName(item.getString("mdm_name"));
        info.setSystemIndustryId(item.getLong("system_industry_id"));
        info.setCustomizedIndustry(item.getString("customized_industry"));
        info.setIntroductionUrl(item.getString("introduction_url"));
        info.setCorporateBrandName(item.getString("corporate_brand_name"));
        info.setMemo(item.getString("memo"));
        info.setSystemStatus(item.getString("system_status"));
        info.setRejectMessage(item.getString("reject_message"));
        info.setIsAdx(item.getBoolean("is_adx"));
        info.setBusinessAlias(item.getString("business_alias"));
        info.setContactPerson(item.getString("contact_person"));
        info.setContactPersonEmail(item.getString("contact_person_email"));
        info.setContactPersonTelephone(item.getString("contact_person_telephone"));
        info.setContactPersonMobile(item.getString("contact_person_mobile"));
        info.setAgencyAccountId(item.getLong("agency_account_id"));
        return info;
    }

    private String buildFieldsParam() {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < FIELDS.length; i++) {
            sb.append("\"").append(FIELDS[i]).append("\"");
            if (i < FIELDS.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
