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

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.kuaishou.modules.dimension.entity.KuaiShouDimensionCreative;
import cn.com.ctop.kuaishou.modules.dimension.mapper.KuaiShouDimensionCreativeMapper;
import cn.com.ctop.kuaishou.modules.dimension.service.IKuaiShouDimensionCreativeService;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多维度测试关联创意
 *
 * @author jeecg-boot
 * 2021-07-22
 * @version V1.0
 */
@Slf4j
@Service
public class KuaiShouDimensionCreativeServiceImpl extends ServiceImpl<KuaiShouDimensionCreativeMapper, KuaiShouDimensionCreative> implements IKuaiShouDimensionCreativeService {
    @Autowired
    private KuaiShouDimensionCreativeMapper dimensionCreativeMapper;
    static ExecutorService createCreativeService = Executors.newFixedThreadPool(5);
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;

    @Override
    public void addBatch(List<KuaiShouDimensionCreative> addList) {
        dimensionCreativeMapper.addBatch(addList);
    }

    /**
     * 创意创建
     *
     * @param accountId
     * @param accessToken
     * @param id
     * @param unitId
     */
    @Override
    public void createCreative(Long accountId, String accessToken, String id, Long unitId) {
        createCreativeService.submit(new Runnable() {
            @Override
            public void run() {
                QueryWrapper<KuaiShouDimensionCreative> updateCreativeQueryWrapper = new QueryWrapper<>();
                updateCreativeQueryWrapper.eq("unit_table_id", id);
                KuaiShouDimensionCreative updateDimensionCreative = new KuaiShouDimensionCreative();
                updateDimensionCreative.setUnitId(unitId);
                int update = dimensionCreativeMapper.update(updateDimensionCreative, updateCreativeQueryWrapper);
                if (update > 0) {
                    log.info("修改创意关联unit成功，tableId:{},unitId:{}", id, unitId);
                }
                QueryWrapper<KuaiShouDimensionCreative> creativeQueryWrapper = new QueryWrapper<>();
                creativeQueryWrapper.eq("unit_table_id", id);
                creativeQueryWrapper.eq("create_status", 0);
                List<KuaiShouDimensionCreative> dimensionCreatives = dimensionCreativeMapper.selectList(creativeQueryWrapper);
                if (!Check.isNull(dimensionCreatives)) {
                    for (KuaiShouDimensionCreative creative : dimensionCreatives) {
                        KuaiShouDimensionCreative updateCreative = new KuaiShouDimensionCreative();
                        updateCreative.setId(creative.getId());
                        updateCreative.setCreateStatus(1);
                        updateCreative.setCreateDescribe("创建中");
                        dimensionCreativeMapper.updateById(updateCreative);
                        JSONObject creativeJson = new JSONObject();
                        creativeJson.put("advertiser_id", accountId);
                        creativeJson.put("unit_id", unitId);
                        Integer creativeMaterialType = creative.getCreativeMaterialType();
                        creativeJson.put("creative_material_type", creativeMaterialType);
                        String action_bar_text = creative.getActionBarText();
                        creativeJson.put("action_bar_text", action_bar_text);
                        String description = creative.getDescription();
                        creativeJson.put("description", description.trim());
                        String name = creative.getCreativeName();
                        creativeJson.put("creative_name", name);
                        Long photoId = creative.getPhotoId();
                        if (!Check.isNull(photoId)) {
                            creativeJson.put("photo_id", photoId);
                        }
                        if (!Check.isNull(creative.getCreativeCategory())) {
                            creativeJson.put("creative_category", creative.getCreativeCategory());
                        }
                        if (!Check.isNull(!Check.isNull(creative.getCreativeTag()))) {
                            creativeJson.put("creative_tag", JSONArray.parseArray(creative.getCreativeTag()));
                        }
                        String click_track_url = creative.getClickTrackUrl();
                        if (!Check.isNull(click_track_url)) {
                            creativeJson.put("click_track_url", click_track_url);
                        }
                        // 第三方点击按钮监测链接
                        if (!Check.isNull(creative.getActionbarClickUrl())) {
                            creativeJson.put("actionbar_click_url", creative.getActionbarClickUrl());
                        }
                        Map<String, Object> creativeMap = kuaishouInterfaceService.creativeCreate(accessToken, accountId, creativeJson, 1);
                        if (!Check.isNullMap(creativeMap)) {
                            Integer code = (Integer) creativeMap.get("code");
                            if (code == 0) {
                                Long creativeId = (Long) creativeMap.get("creativeId");
                                updateCreative.setCreativeId(creativeId);
                                updateCreative.setCreateStatus(2);
                                updateCreative.setCreateDescribe("创建成功");
                                dimensionCreativeMapper.updateById(updateCreative);

                            } else {
                                String message = (String) creativeMap.get("message");
                                if ("/rest/openapi/v2/creative/create调用已超日限，次日可恢复调用".equals(message)) {
                                    updateCreative.setCreateStatus(4);
                                    updateCreative.setCreateDescribe("当日创意额度超限");
                                    dimensionCreativeMapper.updateById(updateCreative);
                                    dimensionCreativeMapper.updateBy(id);
                                    return;
                                } else {
                                    updateCreative.setCreateStatus(3);
                                    updateCreative.setCreateDescribe(message);
                                    dimensionCreativeMapper.updateById(updateCreative);
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    /**
     * 重新提交创意
     *
     * @param accountId
     * @param accessToken
     */
    @Override
    public void againCreateCreative(Long accountId, String accessToken) {
        QueryWrapper<KuaiShouDimensionCreative> creativeQueryWrapper = new QueryWrapper<>();
        creativeQueryWrapper.eq("account_id", accountId);
        creativeQueryWrapper.eq("create_status", 4);
        List<KuaiShouDimensionCreative> dimensionCreatives = dimensionCreativeMapper.selectList(creativeQueryWrapper);
        if (!Check.isNull(dimensionCreatives)) {
            for (KuaiShouDimensionCreative creative : dimensionCreatives) {
                KuaiShouDimensionCreative updateCreative = new KuaiShouDimensionCreative();
                updateCreative.setId(creative.getId());
                updateCreative.setCreateStatus(1);
                updateCreative.setCreateDescribe("创建中");
                dimensionCreativeMapper.updateById(updateCreative);
                JSONObject creativeJson = new JSONObject();
                creativeJson.put("advertiser_id", accountId);
                creativeJson.put("unit_id", creative.getUnitId());
                Integer creativeMaterialType = creative.getCreativeMaterialType();
                creativeJson.put("creative_material_type", creativeMaterialType);
                String action_bar_text = creative.getActionBarText();
                creativeJson.put("action_bar_text", action_bar_text);
                String description = creative.getDescription();
                creativeJson.put("description", description.trim());
                String name = creative.getCreativeName();
                creativeJson.put("creative_name", name);
                Long photoId = creative.getPhotoId();
                if (!Check.isNull(photoId)) {
                    creativeJson.put("photo_id", photoId);
                }
                if (!Check.isNull(creative.getCreativeCategory())) {
                    creativeJson.put("creative_category", creative.getCreativeCategory());
                }
                if (!Check.isNull(!Check.isNull(creative.getCreativeTag()))) {
                    creativeJson.put("creative_tag", JSONArray.parseArray(creative.getCreativeTag()));
                }
                String click_track_url = creative.getClickTrackUrl();
                if (!Check.isNull(click_track_url)) {
                    creativeJson.put("click_track_url", click_track_url);
                }
                // 第三方点击按钮监测链接
                if (!Check.isNull(creative.getActionbarClickUrl())) {
                    creativeJson.put("actionbar_click_url", creative.getActionbarClickUrl());
                }
                Map<String, Object> creativeMap = kuaishouInterfaceService.creativeCreate(accessToken, accountId, creativeJson, 1);
                if (!Check.isNullMap(creativeMap)) {
                    Integer code = (Integer) creativeMap.get("code");
                    if (code == 0) {
                        Long creativeId = (Long) creativeMap.get("creativeId");
                        updateCreative.setCreativeId(creativeId);
                        updateCreative.setCreateStatus(2);
                        updateCreative.setCreateDescribe("创建成功");
                        dimensionCreativeMapper.updateById(updateCreative);

                    } else {
                        String message = (String) creativeMap.get("message");
                        if ("/rest/openapi/v2/creative/create调用已超日限，次日可恢复调用".equals(message)) {
                            updateCreative.setCreateStatus(4);
                            updateCreative.setCreateDescribe("当日创意额度超限");
                            dimensionCreativeMapper.updateById(updateCreative);
                            dimensionCreativeMapper.updateBy(creative.getUnitTableId());
                            return;
                        } else {
                            updateCreative.setCreateStatus(3);
                            updateCreative.setCreateDescribe(message);
                            dimensionCreativeMapper.updateById(updateCreative);
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<Long> getAccountList() {
        return dimensionCreativeMapper.getAccountList();
    }

    @Override
    public void removeByUnitTableIds(List<String> strings) {
        dimensionCreativeMapper.removeByUnitTableIds(strings);
    }

}
