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

import cn.com.ctop.common.module.enums.MaterialEnum;
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.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class KuaiShouMaterialUploadServiceImpl implements IKuaiShouMaterialUploadService {

    @Value("${oss.replace.download}")
    private String downloadUrl;

    @Autowired
    private IKuaiShouImageGetService iKuaiShouImageGetService;
    @Autowired
    private IKuaishouInterfaceService kuaishouInterfaceService;

    /**
     * 上传文件
     *
     * @param
     * @param type
     * @param accountId
     */
    @Override
    public JSONObject video(String url, Integer type, Long accountId, String accessToken, String signature) {
        JSONObject returnJson = new JSONObject();
        try {
            log.info("开始本地视频上传");
            String requestUrl = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_UPLOAD;
            String localUrl = LoadFileUtil.downLoadFromUrl(url, downloadUrl);
            File file = new File(localUrl);
            FileSystemResource resource = new FileSystemResource(file);
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Content-Type", "multipart/form-data");
            headerMap.put("Access-Token", accessToken);
            JSONObject requestJson = new JSONObject();
            requestJson.put("signature", signature);
            requestJson.put("file", resource);
            requestJson.put("type", type);
            requestJson.put("advertiser_id", accountId);
            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 photoId = dataJson.getString("photo_id");
                        returnJson.put("success", true);
                        returnJson.put("photoId", photoId);
                        returnJson.put("signature", signature);
                        returnJson.put("message", "上传成功");
                        try {
                            Thread.sleep(1 * 500L);
                            kuaishouInterfaceService.getVideoInfo(accessToken, accountId, photoId);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                    LoadFileUtil.delFile(localUrl);
                    log.info("快手素材上传完成，accountId：{}，code：{},返回信息：{}", accountId, signature, resultJson);
                } else {
                    log.error("快手上传素材失败，返回信息：{}，请求参数：{}", resultJson, requestJson);
                    returnJson.put("success", false);
                    returnJson.put("signature", signature);
                    returnJson.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("快手上传素材返回信息为空请求参数：{}", requestJson);
                returnJson.put("success", false);
                returnJson.put("signature", signature);
                returnJson.put("message", "调用快手后台返回结果为空");
            }

        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("success", false);
            returnJson.put("signature", signature);
            returnJson.put("message", "系统异常");

        }
        return returnJson;


    }


    @Override
    public String kuauiShouImageUpload(String url, String signature, Long accountId, String token) {
        try {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Content-Type", "multipart/form-data");
            JSONObject requestJson = new JSONObject();
            requestJson.put("signature", signature);
            requestJson.put("url", url);
            requestJson.put("type", 2);
            requestJson.put("advertiser_id", accountId);
            headerMap.put("Access-Token", token);
            String requestUrl = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_UPLOAD;
            requestJson.put("upload_type", "2");
            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 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"));
                        Map<String, Integer> typeBySize = MaterialEnum.getTypeBySize(dataJson.getInteger("width"), dataJson.getInteger("height"));

                        if (!Check.isNullMap(typeBySize)) {
                            imageGet.setMaterialType(typeBySize.get("type"));
                        }
                        imageGet.setSignature(signature);
                        imageGet.setImageToken(image_token);
                        iKuaiShouImageGetService.saveOrUpdate(imageGet);
                        return dataJson.getString("image_token");
                    }

                } else {
                    log.error("上传图片失败，accountId:{},code:{},data:{}", accountId, signature, resultJson);
                }


            } else {
                log.error("上传图片,返回结果为空，accountId:{},code:{},data:{}", accountId, signature, resultJson);
            }


        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return null;
    }

    @Override
    public JSONObject kuauiShouImageUploadOnly(String url, String signature, Long accountId, String token) {
        try {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Content-Type", "multipart/form-data");
            JSONObject requestJson = new JSONObject();
            requestJson.put("signature", signature);
            requestJson.put("url", url);
            requestJson.put("type", 1);
            requestJson.put("advertiser_id", accountId);
            headerMap.put("Access-Token", token);
            String requestUrl = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_UPLOAD;
            requestJson.put("upload_type", "2");
            String result = exceptInfoForRestTemplate(requestUrl, requestJson, headerMap);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                return resultJson;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String uploadFile(MultipartFile multipartFile, String dirPath) throws IOException {
        String fileName = multipartFile.getOriginalFilename();
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        String localFileName = System.currentTimeMillis() + fileSuffix;
        String filePath = dirPath + File.separator + localFileName;
        File localFile = new File(filePath);
        File imagePath = new File(dirPath);
        if (!imagePath.exists()) {
            imagePath.mkdirs();
        }
        multipartFile.transferTo(localFile);
        return filePath;
    }

    @Autowired
    private RestTemplate rest;

    @Override
    public String exceptInfoForRestTemplate(String url, Map<String, Object> paramMap, Map<String, String> headerMap) {
        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));
                    }
                }
                SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
                requestFactory.setConnectTimeout(1000 * 500);// 设置超时
                requestFactory.setReadTimeout(1000 * 500);
                RestTemplate rest = new RestTemplate(requestFactory);
                HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
                ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
                return responseEntity.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
