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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
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.ai.service.IKuaishouLandpagePackageService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouProgramCreative;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouProgramCreativeMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouProgramCreativeService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
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 2020-09-22
 */
@Service
@Slf4j
public class KuaishouProgramCreativeServiceImpl extends ServiceImpl<KuaishouProgramCreativeMapper, KuaishouProgramCreative> implements IKuaishouProgramCreativeService {

    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;

    @Autowired
    private IMaterialCutFrameService materialCutFrameService;

    @Autowired
    private IKuaishouLandpagePackageService landpagePackageService;
    @Autowired
    private KuaishouProgramCreativeMapper programCreativeMapper;

    @Override
    public void getProgramCreative(Long accountId, Long unitId, String accessToken, String startDate, String endDate, Integer page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PROGRAM_LIST;
        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);
        }

        if (!Check.isNull(unitId)) {
            JSONArray array = new JSONArray();
            array.add(unitId);
            param.put("unit_ids", array);
        }


        param.put("advertiser_id", accountId);
        param.put("page_size", 500);
        param.put("page", page);

        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        System.err.println(resultJson);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广程序化创意异常:{},accountId:{}", message, accountId);
            return;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        if (Check.isNull(dataJson)) {
            log.error("获取快手广程序化创意返回data为空,accountId:{}", accountId);
            return;
        }
        JSONArray details = dataJson.getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }

        List<KuaishouProgramCreative> programCreativeList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            if (!Check.isNull(detailJson)) {
                detailJson.put("creative_create_time", detailJson.getDate("create_time"));
                detailJson.put("creative_update_time", detailJson.getDate("update_time"));
                var programCreative = JSONObject.toJavaObject(detailJson, KuaishouProgramCreative.class);
                programCreative.setAccountId(accountId);
                programCreative.setId(accountId + "_" + programCreative.getUnitId());
                programCreativeList.add(programCreative);

            }
        }

        programCreativeMapper.replaceBatch(programCreativeList);
        getProgramCreative(accountId, unitId, accessToken, startDate, endDate, page + 1);


    }

    /**
     * 创建程序化2.0
     *
     * @param oauthToken
     * @param requestJson
     * @return
     */

    @Override
    public JSONObject createProgramCreative(CtopOauthToken oauthToken, JSONObject requestJson) {

        JSONObject returnJson = new JSONObject();
        try {
            JSONObject pramsJson = new JSONObject();
            pramsJson.put("advertiser_id", oauthToken.getAccountId());
            pramsJson.put("unit_id", requestJson.getLong("unitId"));
            pramsJson.put("package_name", requestJson.getString("packageName"));
            pramsJson.put("horizontal_photo_ids", requestJson.getJSONArray("horizontalPhotoIds"));
            pramsJson.put("vertical_photo_ids", requestJson.getJSONArray("verticalPhotoIds"));
            pramsJson.put("cover_image_tokens", requestJson.getJSONArray("coverImageTokens"));
            if (!Check.isNull(requestJson.getLong("siteId"))) {
                pramsJson.put("site_id", requestJson.getLong("siteId"));
            }
            if (!Check.isNull(requestJson.getJSONArray("stickerStyles"))) {
                pramsJson.put("sticker_styles", requestJson.getJSONArray("stickerStyles"));
            }

            if (!Check.isNull(requestJson.getJSONArray("coverSlogans"))) {
                pramsJson.put("cover_slogans", requestJson.getJSONArray("coverSlogans"));
            }

            Integer creativeCategory = requestJson.getInteger("creativeCategory");
            JSONArray creativeTag = requestJson.getJSONArray("creativeTag");

            if (!Check.isNull(creativeCategory) && !Check.isNull(creativeTag)) {
                pramsJson.put("creative_category", creativeCategory);
                pramsJson.put("creative_tag", creativeTag);
            }
            pramsJson.put("action_bar", requestJson.getString("actionBarText"));
            pramsJson.put("captions", requestJson.getJSONArray("captions"));
            if (!Check.isNull(requestJson.getString("clickUrl"))) {
                pramsJson.put("click_url", requestJson.getString("clickUrl"));
            }
            if (!Check.isNull(requestJson.getString("actionbarClickUrl"))) {
                pramsJson.put("actionbar_click_url", requestJson.getString("actionbarClickUrl"));
            }
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", oauthToken.getAccessToken());
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PROGRAM_CREATE;
            JSONArray coverImageTokens = requestJson.getJSONArray("coverImageTokens");
            JSONArray cover_image_tokens = new JSONArray();
            requestJson.remove(coverImageTokens);
            if (!Check.isNull(coverImageTokens)) {
                for (int i = 0; i < coverImageTokens.size(); i++) {
                    String signature = coverImageTokens.getString(i);
                    if (Check.isNull(signature)) {
                        continue;
                    }
                    String imageToken = null;
                    if (!Check.isNull(signature)) {
                        QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("account_id", oauthToken.getAccountId());
                        queryWrapper.eq("signature", signature);
                        queryWrapper.last("limit 1");
                        KuaiShouImageGet imageGet = imageGetService.getOne(queryWrapper);
                        if (!Check.isNull(imageGet)) {
                            imageToken = imageGet.getImageToken();
                        } else {
                            String imageUrl = imageGetService.getUrlByCode(signature);
                            imageToken = uploadService.kuauiShouImageUpload(imageUrl, signature, oauthToken.getAccountId(), oauthToken.getAccessToken());
                        }
                        cover_image_tokens.add(imageToken);
                    }
                }
            }
            pramsJson.put("cover_image_tokens", cover_image_tokens);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, pramsJson.toJSONString(), headers);
            JSONObject jsonObject = JSONObject.parseObject(result);
            log.info("创建程序化创意返回结果:{}", jsonObject);
            if (!Check.isNull(jsonObject)) {
                Integer code = jsonObject.getInteger("code");
                if (code == 0) {
                    returnJson.put("isTrueOrFalse", true);
                    returnJson.put("message", "创建成功");
                    createLandPageAndUnit(pramsJson, jsonObject.getJSONObject("data"));
                } else {
                    log.error("创建失败:入参：{}", pramsJson);
                    returnJson.put("isTrueOrFalse", false);
                    returnJson.put("message", jsonObject.getString("message"));
                }


            }

        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("isTrueOrFalse", false);
            returnJson.put("message", "系统错误");

        }
        return returnJson;
    }

    //绑定落地页与广告组、创意的关系
    private void createLandPageAndUnit(JSONObject programJson, JSONObject data) {
        if (!Check.isNull(data) && !Check.isNull(programJson.getLong("site_id"))) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    landpagePackageService.createLandPageAndUnit(programJson.getLong("site_id"), data.getLong("creative_id"), programJson.getLong("unit_id"), programJson.getLong("advertiser_id"));
                }
            };
            thread.start();
        }
    }

    @Override
    public JSONArray getProgramCreativeCover(JSONArray md5Arr) {

        JSONArray returnArr = new JSONArray();
        for (int i = 0; i < md5Arr.size(); i++) {
            String signature = md5Arr.getString(i);
            if (Check.isNull(signature)) {
                continue;
            }
            List<JSONObject> coverArr = materialCutFrameService.getProgramCreativeCover(signature);
            if (!Check.isNull(coverArr)) {
                for (int j = 0; j < coverArr.size(); j++) {
                    JSONObject jsonObject = JSONObject.parseObject(coverArr.get(j).toJSONString());
                    if (!Check.isNull(jsonObject)) {
                        returnArr.add(jsonObject);
                    }
                }

            }

        }
        return returnArr;
    }


}
