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

import cn.com.ctop.common.module.entity.CtopOauthToken;
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.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouCreativeMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouVideoGetMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCreativeService;
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 org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 快手-创意信息
 * @Author: jeecg-boot
 * @Date: 2019-07-23
 * @Version: V1.0
 */
@Slf4j
@Service
public class KuaiShouCreativeServiceImpl extends ServiceImpl<KuaiShouCreativeMapper, KuaiShouCreative> implements IKuaiShouCreativeService {
    @Resource
    private KuaiShouCreativeMapper kuaiShouCreativeMapper;
    @Resource
    private KuaiShouVideoGetMapper kuaiShouVideoGetMapper;

    @Override
    public void replaceBatch(List<KuaiShouCreative> creatives) {
        kuaiShouCreativeMapper.replaceBatch(creatives);
    }

    @Override
    public String getCodeByCreativeId(Long creativeId) {
        QueryWrapper<KuaiShouCreative> creativeQueryWrapper = new QueryWrapper<>();
        creativeQueryWrapper.eq("creative_id", creativeId);
        creativeQueryWrapper.orderByDesc("create_time");
        creativeQueryWrapper.last("limit 1");
        KuaiShouCreative kuaiShouCreative = kuaiShouCreativeMapper.selectOne(creativeQueryWrapper);
        if (!Check.isNull(kuaiShouCreative)) {
            String photoId = kuaiShouCreative.getPhotoId();
            if (!Check.isNull(photoId)) {
                QueryWrapper<KuaiShouVideoGet> videoGetQueryWrapper = new QueryWrapper<>();
                videoGetQueryWrapper.eq("photo_id", photoId);
                videoGetQueryWrapper.orderByDesc("create_time");
                videoGetQueryWrapper.last("limit 1");
                KuaiShouVideoGet kuaiShouVideoGet = kuaiShouVideoGetMapper.selectOne(videoGetQueryWrapper);
                if (!Check.isNull(kuaiShouVideoGet)) {
                    return kuaiShouVideoGet.getSignature();
                }
            }
        }
        return null;
    }

    /**
     * 创意条数
     *
     * @param accountId
     * @param unitId
     * @return
     */
    @Override
    public Integer checkCreativeCount(Long accountId, Long unitId) {
        return kuaiShouCreativeMapper.checkCreativeCount(accountId, unitId);
    }

    @Override
    public void syncCreative(Long accountId, String accessToken, Long campaignId, Integer page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", accessToken);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        if (!Check.isNull(campaignId)) {
            param.put("campaign_id", campaignId);
        }
        param.put("page_size", 500);
        param.put("page", page);

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告创意返回结果为空,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取广告创意返回结果异常,advertiserId:{},message:{}", accountId, message);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            return;
        }
        List<KuaiShouCreative> creatives = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = JSONObject.parseObject(details.get(i).toString());
            if (!Check.isNull(detailJson)) {
                KuaiShouCreative creative = new KuaiShouCreative();
                creative.setId("" + accountId + detailJson.getLong("creative_id"));
                creative.setAccountId(accountId);
                creative.setCampaignId(detailJson.getLong("campaign_id"));
                creative.setUnitId(detailJson.getLong("unit_id"));
                creative.setCreativeId(detailJson.getLong("creative_id"));
                creative.setCreativeName(detailJson.getString("creative_name"));
                creative.setCreativeMaterialType(detailJson.getInteger("creative_material_type"));
                if (!Check.isNull(detailJson.getJSONArray("material_url"))) {
                    creative.setMaterialUrl(detailJson.getJSONArray("material_url").toJSONString());
                }

                if (!Check.isNull(detailJson.getJSONArray("image_tokens"))) {
                    creative.setImageTokens(detailJson.getJSONArray("image_tokens").toJSONString());
                }
                creative.setStatus(detailJson.getInteger("status"));
                creative.setPutStatus(detailJson.getInteger("put_status"));
                creative.setCreateChannel(detailJson.getInteger("create_channel"));
                creative.setReviewDetail(detailJson.getString("review_detail"));
                creative.setCoverUrl(detailJson.getString("cover_url"));
                creative.setImageToken(detailJson.getString("image_token"));
                creative.setCoverWidth(detailJson.getString("cover_width"));
                creative.setCoverHeight(detailJson.getString("cover_height"));
                creative.setOverlayBgUrl(detailJson.getString("overlay_bg_url"));
                creative.setOverlayBgImageToken(detailJson.getString("overlay_bg_image_token"));
                creative.setStickerTitle(detailJson.getString("sticker_title"));
                creative.setOverlayType(detailJson.getString("overlay_type"));
                creative.setClickTrackUrl(detailJson.getString("click_track_url"));
                creative.setImpressionUrl(detailJson.getString("impression_url"));
                creative.setAdPhotoPlayedT3sUrl(detailJson.getString("ad_photo_played_t3s_url"));
                creative.setCreativeCreateTime(detailJson.getDate("create_time"));
                creative.setCreativeUpdateTime(detailJson.getDate("update_time"));
                creative.setFirstFrameType(detailJson.getInteger("first_frame_type"));
                creative.setShortSlogan(detailJson.getString("short_slogan"));
                creative.setActionbarClickUrl(detailJson.getString("actionbar_click_url"));
                JSONObject displayInfoJson = detailJson.getJSONObject("display_info");
                if (!Check.isNull(displayInfoJson)) {
                    creative.setDescription(displayInfoJson.getString("description"));
                    creative.setActionBarText(displayInfoJson.getString("action_bar_text"));
                }
                creative.setCreativeCategory(detailJson.getInteger("creative_category"));
                if (!Check.isNull(detailJson.getJSONArray("creative_tag"))) {
                    creative.setCreativeTag(detailJson.getJSONArray("creative_tag").toJSONString());
                }
                creative.setCreateTime(new java.util.Date());
                creative.setUpdateTime(new java.util.Date());
                creative.setSiteId(detailJson.getLong("site_id"));
                creative.setPhotoId(detailJson.getString("photo_id"));
                if (detailJson.getLong("photo_id") == 0) {
                    JSONArray photoIds = new JSONArray();
                    JSONObject programmed_creative_material = detailJson.getJSONObject("programmed_creative_material");
                    if (!Check.isNull(programmed_creative_material)) {
                        creative.setProgrammedCreativeMaterial(programmed_creative_material.toJSONString());
                        JSONArray materials = programmed_creative_material.getJSONArray("materials");
                        if (!Check.isNull(materials)) {
                            for (int j = 0; j < materials.size(); j++) {
                                JSONObject materialJson = materials.getJSONObject(j);
                                if (!Check.isNull(materialJson)) {
                                    Long photo_id = materialJson.getLong("photo_id");
                                    photoIds.add(String.valueOf(photo_id));
                                }
                            }
                            creative.setPhotoIds(photoIds.toJSONString());
                        }
                    }
                }
                creatives.add(creative);
            }
        }
        this.replaceBatch(creatives);
        this.syncCreative(accountId, accessToken, campaignId, page + 1);
    }

    @Override
    public Integer getCreateCount(Long accountId, String startTime) {
        return kuaiShouCreativeMapper.getCreateCount(accountId, startTime);
    }

    @Override
    public void delAllCreativesByCampaignId(Long accountId, Long campaignId) {
        kuaiShouCreativeMapper.delAllCreativesByCampaignId(accountId, campaignId);
    }

    @Override
    public List<KuaiShouCreative> queryCreativeInfoByCampaignId(Long accountId, Long campaignId) {
        return kuaiShouCreativeMapper.queryCreativeInfoByCampaignId(accountId, campaignId);
    }

    @Override
    public KuaiShouCreative getCreativeByCreativeId(Long creativeId) {
        QueryWrapper<KuaiShouCreative> creativeQueryWrapper = new QueryWrapper<>();
        creativeQueryWrapper.eq("creative_id", creativeId);
        creativeQueryWrapper.last("limit 1");
        KuaiShouCreative creative = kuaiShouCreativeMapper.selectOne(creativeQueryWrapper);
        return creative;
    }

    @Override
    public JSONArray getCreativeIds(Long accountId) {
        List<Long> creativeIds = kuaiShouCreativeMapper.getCreativeIds(accountId);
        return JSONArray.parseArray(creativeIds.toString());
    }

    @Override
    public synchronized String convertMoString(String sMo) {
        if (Check.isNull(sMo)) {
            return null;
        }
        String newString = null;
        try {
            if (sMo.contains("，")) {
                return sMo.replace('，', ',');
            } else if (sMo.contains("～")) {
                newString = sMo.replace('～', '~');
            } else if (sMo.contains("。")) {
                newString = sMo.replace('。', '.');
            } else if (sMo.contains("；")) {
                newString = sMo.replace('；', ';');
            } else if (sMo.contains("！")) {
                newString = sMo.replace("！", "!");
            } else if (sMo.contains("？")) {
                newString = sMo.replace('？', '?');
            } else if (sMo.contains("：")) {
                newString = sMo.replace('：', ':');
            } else if (sMo.contains("“")) {
                newString = sMo.replace('“', '＂');
            } else if (sMo.contains("”")) {
                newString = sMo.replace('”', '＂');
            } else if (sMo.contains("<")) {
                newString = sMo.replace('>', '》').replace('<', '《');
            } else if (sMo.contains(",")) {
                newString = sMo.replace(',', '，');
            } else if (sMo.contains(".")) {
                newString = sMo.replace('.', '。');
            } else if (sMo.contains(";")) {
                newString = sMo.replace(';', '；');
            } else if (sMo.contains("!")) {
                newString = sMo.replace("!", "！");
            } else if (sMo.contains("?")) {
                newString = sMo.replace('?', '？');
            } else if (sMo.contains(":")) {
                newString = sMo.replace(':', '：');
            } else if (sMo.contains("＂")) {
                newString = sMo.replace('＂', '“');
            } else if (sMo.contains("＂")) {
                newString = sMo.replace('＂', '”');
            } else if (sMo.contains("《")) {
                newString = sMo.replace('》', '>').replace('《', '<');
            } else if (sMo.contains("~")) {
                newString = sMo.replace('~', '～');
            } else {
                newString = sMo;
            }

        } catch (Exception ex) {
            return sMo;
        }
        return newString;
    }

    @Override
    public List<KuaiShouCreative> getByParams(Long accountId, String photoId, Integer putStatus) {
        QueryWrapper<KuaiShouCreative> queryWrapper = new QueryWrapper<>();
        if (null != accountId && accountId != 0) {
            queryWrapper.eq("account_id", accountId);
        }
        if (null != photoId && !"".equals(photoId.trim())) {
            queryWrapper.eq("photo_id", photoId);
        }
        if (null != putStatus && putStatus != 0) {
            queryWrapper.eq("put_status", putStatus);
        }
        return this.list(queryWrapper);
    }

    @Override
    public Integer getNewDataByAccountIdAndDate(Long accountId, String statDate) {
        return kuaiShouCreativeMapper.getNewDataByAccountIdAndDate(accountId, statDate);
    }

    @Override
    public String getClickTrackUrl(Long accountId, Long unitId) {
        return kuaiShouCreativeMapper.getClickTrackUrl(accountId, unitId);
    }

    @Override
    public List<KuaiShouCreative> getCreativeListByAccountIdAndUnitId(Long accountId, Long unitId) {
        QueryWrapper<KuaiShouCreative> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("unit_id", unitId);
        return this.list(queryWrapper);
    }


    @Override
    public void getProgramCreative(CtopOauthToken token, int page) {

        log.info("获取视频数据，accountId：{}", token.getAccountId());
        String url1 = "https://ad.e.kuaishou.com/rest/openapi/v2/creative/advanced/program/list";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<>();
        param.put("advertiser_id", token.getAccountId());
        param.put("page_size", 500);
        param.put("page", page);

        String result = HttpUtils.httpPostRequest(url1, 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, token.getAccountId());
            return;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        if (Check.isNull(dataJson)) {
            return;
        }
        JSONArray details = dataJson.getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }

        for (int i = 0; i < details.size(); i++) {
            JSONObject jsonObject = details.getJSONObject(i);
            if (Check.isNull(jsonObject)) {
                continue;
            }

            String updateUrl = "https://ad.e.kuaishou.com/rest/openapi/v2/creative/advanced/program/update";

            Map<String, String> headers1 = new HashMap<>();
            headers1.put("Content-Type", "application/json");
            headers1.put("Access-Token", token.getAccessToken());
            Map<String, Object> param1 = new HashMap<>();
            param1.put("advertiser_id", token.getAccountId());
            param1.put("unit_id", jsonObject.getLong("unit_id"));

          /*  String clickTrackUrl = jsonObject.getString("click_url").replace("&idfa_md5=__IDFA__", "").replace("&idfa_md5=__IDFA2__", "");
            if (Check.isNull(clickTrackUrl)) {
                continue;
            }

            if (clickTrackUrl.contains("&ad_name=__DNAME__")) {
                continue;
            }*/

            String replaceUrll = "https://click-wailaxin.1sapp.com/vendor/feedback/reportClick?platform=kuaishou&feedback_type=android&account_id=19&plan_id=__DID__&adgroup_id=__AID__&creative_id=__CID__&imei=__IMEI2__&mac=__MAC__&androidid=__ANDROIDID2__&ts=__TS__&ip=__IP__&ua=__UA__&callback=__CALLBACK__&oaid=__OAID__&app=dxqlb";

            param1.put("click_url", replaceUrll);
            String result1 = HttpUtils.httpPostRequest(updateUrl, param1, headers1);
            JSONObject resultJson1 = JSONObject.parseObject(result1);
            Integer code1 = resultJson1.getInteger("code");
            if (code1 == 0) {
                log.info("修改成功,accountId:{},unitId:{}", token.getAccountId(), jsonObject.getLong("unit_id"));

            } else {
                log.info("修改失败,accountId:{},unitId:{}，原因：{}", token.getAccountId(), jsonObject.getLong("unit_id"), resultJson1.getString("message"));
            }


        }

        getProgramCreative(token, page + 1);

    }

    @Override
    public String querMaxCreateTime(Long unitId) {
        return kuaiShouCreativeMapper.querMaxCreateTime(unitId);
    }


}
