package ctop.bytedance.ad.common.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import ctop.bytedance.ad.advertise.dockapi.MarketingService;
import ctop.bytedance.ad.advertise.entity.BytedanceImageInfo;
import ctop.bytedance.ad.advertise.service.IBytedanceImageInfoService;
import ctop.bytedance.ad.common.entity.CtopOauthToken;
import ctop.bytedance.ad.common.entity.FileInfo;
import ctop.bytedance.ad.common.mapper.FileInfoMapper;
import ctop.bytedance.ad.common.service.ICtopOauthTokenService;
import ctop.bytedance.ad.common.service.IFileInfoService;
import ctop.bytedance.ad.common.utils.ResultMapUtils;
import ctop.bytedance.ad.common.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Author: jeecg-boot
 * @Date: 2019-07-09
 * @Version: V1.0
 */
@Slf4j
@Service
@Primary
public class FileInfoServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileInfoService {
    @Autowired
    private MarketingService marketingService;
    @Autowired
    private IBytedanceImageInfoService bytedanceImageInfoService;
    @Autowired
    private ICtopOauthTokenService ctopOauthTokenService;

    /**
     * 平台 上传图片
     * @param accountId
     * @param imageUrl
     * @return
     */
    @Override
    public Map<String, Object> uploadImageToBytedance(String accountId, String imageUrl) {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            CtopOauthToken token = ctopOauthTokenService.getOauthTokenByAccountId(accountId);
            JSONObject result = marketingService.imageUpload(token, imageUrl);
            if(null == result){
                ResultMapUtils.setResultMap(resultMap, StatusCode.BYTEDANCE_IMAGE_UPLOAD_ERROR);
                return resultMap;
            }
            Integer code = result.getInteger("code");
            String message = result.getString("message");
            if(code!=0){
                resultMap.put("message",message);
                resultMap.put("code",code);
                resultMap.put("success",false);
                return resultMap;
            }
            JSONObject data = result.getJSONObject("data");
            BytedanceImageInfo imageInfo = new BytedanceImageInfo(data,token);
            bytedanceImageInfoService.saveOrUpdate(imageInfo);
            resultMap.put("data",imageInfo);
            ResultMapUtils.setResultMap(resultMap,StatusCode.COMMON_SUCCESS);
            return resultMap;
        } catch (Exception e) {
            log.error("头条上传图片文件失败，accountId:{}", accountId);
            log.error(e.getMessage(), e);
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SERVER_ERROR);
            return resultMap;
        }
    }

    @Override
    public String getSuggestImageId(CtopOauthToken token, String vid) {
        String result = null;
        for(int i=0;i<3;i++){
            JSONObject resultObject = marketingService.getSuggestImageId(token, vid);
            log.info("获取推荐封面返回结果：{}",resultObject);
            if(null==resultObject||null==resultObject.getInteger("code")||0!=resultObject.getInteger("code")){
                continue;
            }
            JSONObject data = resultObject.getJSONObject("data");
            String status = data.getString("status");
            if("SUCCESS".equals(status)){
                JSONArray array  = data.getJSONArray("list");
                JSONObject imageInfo = array.getJSONObject(0);
                return imageInfo.getString("id");
            }
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
