package cn.com.ctop.manage.modules.material.service.impl;

import cn.com.ctop.common.module.entity.MaterialImageInfo;
import cn.com.ctop.common.module.enums.MaterialEnum;
import cn.com.ctop.common.module.service.IMaterialImageInfoService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.manage.modules.material.service.IMaterialUploadImageService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class MaterialUploadImageServiceImpl implements IMaterialUploadImageService {
    static ExecutorService executorService = Executors.newFixedThreadPool(4);
    @Value("${oss.replace.replace-value}")
    private String replaceValue;
    @Value("${oss.replace.replace-old-value}")
    private String replaceOldValue;
    @Value("${oss.replace.download}")
    private String downloadUrl;

    @Autowired
    private IMaterialImageInfoService materialImageInfoService;
    @Autowired
    private IKuaiShouImageGetService imageGetService;

    /**
     * 同步素材到账号下
     */
    @Override
    public void uploadImage(String videoId, Long accountId, String accessToken) {
        try {
            QueryWrapper<MaterialImageInfo> imageInfoQueryWrapper = new QueryWrapper<>();
            imageInfoQueryWrapper.eq("video_id", videoId);
            imageInfoQueryWrapper.eq("status", 0);
            List<MaterialImageInfo> imageList = materialImageInfoService.list(imageInfoQueryWrapper);
            if (!Check.isNull(imageList)) {
                for (MaterialImageInfo imageInfo : imageList) {
                    QueryWrapper<KuaiShouImageGet> imageQueryWrapper = new QueryWrapper<>();
                    imageQueryWrapper.eq("account_id", accountId);
                    imageQueryWrapper.eq("signature", imageInfo.getCode());
                    List<KuaiShouImageGet> imageGetList = imageGetService.list(imageQueryWrapper);
                    if (!Check.isNull(imageGetList)) {
                        log.info("此封面已上传");
                        continue;
                    }
                    String url = String.valueOf(imageInfo.getUrl());
                    String localUrl = LoadFileUtil.downLoadFromUrl(url, downloadUrl);
                    FileSystemResource resource = new FileSystemResource(new File(localUrl));
                    Map<String, String> headerMap = new HashMap<>();
                    JSONObject requestJson = new JSONObject();
                    requestJson.put("advertiser_id", accountId);
                    headerMap.put("Access-Token", accessToken);
                    headerMap.put("Content-Type", "multipart/form-data");

                    requestJson.put("file", resource);
                    requestJson.put("signature", imageInfo.getCode());
                    requestJson.put("type", "2");
                    requestJson.put("upload_type", "1");
                    String requestUrl = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_UPLOAD;
                    String result = exceptInfoForRestTemplate(requestUrl, requestJson, headerMap);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if (!Check.isNull(resultJson)) {
                        if (resultJson.getInteger("code") == 0) {
                            JSONObject dataJson = resultJson.getJSONObject("data");
                            if (!Check.isNull(dataJson)) {
                                String signature = dataJson.getString("signature");
                                String image_token = dataJson.getString("image_token");
                                KuaiShouImageGet imageGet = new KuaiShouImageGet();
                                imageGet.setId(accountId + image_token);
                                imageGet.setAccountId(accountId);
                                imageGet.setUrl(dataJson.getString("url"));
                                imageGet.setWidth(dataJson.getInteger("width"));
                                imageGet.setHeight(dataJson.getInteger("height"));
                                imageGet.setSize(dataJson.getInteger("size"));
                                imageGet.setFormat(dataJson.getString("format"));
                                Integer type = MaterialEnum.getTypeBySize(dataJson.getInteger("width"), dataJson.getInteger("height"));
                                if (!Check.isNull(type)) {
                                    imageGet.setMaterialType(type);
                                }
                                imageGet.setSignature(signature);
                                imageGet.setImageToken(image_token);
                                imageGetService.saveOrUpdate(imageGet);
                            }
                            log.info("快手封面素材素材同步完成，accountId：{}，code：{},返回信息：{}", accountId, imageInfo.getCode(), resultJson);
                        } else {
                            log.error("快手同步封面素材失败，返回信息：{}，请求参数：{}", resultJson, requestJson);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Autowired
    private RestTemplate rest;

    private String exceptInfoForRestTemplate(String url, Map<String, Object> paramMap, Map<String, String> headerMap) throws ParseException {
        try {
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            if (!Check.isNullMap(paramMap)) {
                for (String key : paramMap.keySet()) {
                    param.add(key, paramMap.get(key));
                }
                HttpHeaders headers = new HttpHeaders();
                if (!Check.isNullMap(headerMap)) {
                    for (String key : headerMap.keySet()) {
                        headers.add(key, headerMap.get(key));
                    }
                }
                HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param, headers);
                ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
                return responseEntity.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
