package com.weaver.seconddev.chapanda.feishu.util;

import com.alibaba.fastjson.JSONObject;
import com.weaver.eteams.file.client.file.FileData;
import com.weaver.file.ud.api.FileDownloadService;
import com.weaver.seconddev.chapanda.feishu.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;


@Component
public class Esb2FeishuUploadImageUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2FeishuUploadImageUtil.class);

    @Autowired
    private FileDownloadService fileDownloadService;

    @Autowired
    Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    public String uploadImage(Long pvalue) {
        log.error("esb2feishuuploadimageutil start");
        String imageKey = "";
        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){
            InputStream fileInputStream = null;
            try {
                FileData fileData = fileDownloadService.downloadFile(pvalue);
                String fileName = fileData.getFileObj().getName();
                fileInputStream = fileData.getInputStream();
                if(fileInputStream.available() > 0) {
                    byte[] fileByte = convertInputStreamToBytes(fileInputStream);
                    if(fileByte.length >0){
                        String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
                        String message = uploadImageByte(fileByte,encodedFileName,token);
                        if(StringUtils.isNotBlank(message)){
                            JSONObject returnData = JSONObject.parseObject(message);
                            if(returnData.containsKey("code")){
                                String code = returnData.getString("code");
                                if("0".equals(code)){
                                    JSONObject dataJson = returnData.getJSONObject("data");
                                    imageKey = dataJson.getString("image_key");
                                }
                            }
                        }

                    }
                }
                fileInputStream.close();
            }catch (Exception e){
                log.error("e:{}",e);
            }finally {
                try {
                    if(fileInputStream != null){
                        fileInputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imageKey;
    }


//    public String getToken2() {
//        String token = "";
//        JSONObject returnData = getAccessToken();
//        if(returnData.containsKey("tenantAccessToken")){
//            token = returnData.getString("tenantAccessToken");
//        }
//        System.out.println("token:"+token);
//        return token;
//    }

    /**
     *
     * @return
     */
//    public JSONObject getAccessToken() {
//
//        JSONObject returnData = new JSONObject();
//        JSONObject dataJson = new JSONObject();
//        dataJson.put("app_id", Constants.app_id);
//        dataJson.put("app_secret", Constants.app_secret);
//
//        log.error("dataJson:{}",dataJson.toJSONString());
////        dataJson.put("app_id", "cli_a8d0ee6b667dd00e");
////        dataJson.put("app_secret", "UjShC4eY7vCgHsQvFWZZleVdCqSEWGD0");
//
//        try {
//            OkHttpClient client = new OkHttpClient().newBuilder()
//                    .build();
//            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
//            RequestBody body = RequestBody.create(mediaType, dataJson.toJSONString());
//            Request request = new Request.Builder()
//                    .url(Constants.feishuHost+Constants.tokenUrl)
//                    .method("POST", body)
//                    .addHeader("Content-Type", "application/json; charset=utf-8")
//                    .build();
//            Response response = client.newCall(request).execute();
//            int code = response.code();
//            String msg = response.body().string();
//
//            log.error("code:{}",code);
//            log.error("msg:{}",msg);
//
//            if(code == 200){
//                if(StringUtils.isNotBlank(msg)){
//                    JSONObject returnJson = JSONObject.parseObject(msg);
//                    if(returnJson.containsKey("code")){
//                        String dataCode = returnJson.getString("code");
//                        if("0".equals(dataCode)){
//                            String tenantAccessToken = returnJson.getString("tenant_access_token");
//                            int expire = returnJson.getInteger("expire");
//
//                            log.error("tenantAccessToken:{}",tenantAccessToken);
//                            log.error("expire:{}",expire);
//
//                            returnData.put("tenantAccessToken",tenantAccessToken);
//                        }
//                    }
//                }
//            }else{
//                log.error("msg:{}",msg);
//            }
//        } catch (Exception e) {
//            log.error("msg:{}",e.getMessage());
//            e.printStackTrace();
//        }
//        return returnData;
//    }


    /**
     *

     * @param token
     * @return
     */
    public String uploadImageByte(byte[] imageData,String imageName,String token){
        String msg = "";

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        try {
// "toux.jpg"
            RequestBody body = new MultipartBody.Builder().setType(MediaType.get("multipart/form-data;charset=utf-8"))
                    .addFormDataPart("image_type","avatar")
                    .addFormDataPart("image",imageName,
                            RequestBody.create(MediaType.parse("application/octet-stream"),
                                    imageData))
                    .build();
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.imageUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}",code);
            msg = response.body().string();
            log.error("msg:"+msg);
        } catch (IOException e) {
            log.error("e:"+e);
            throw new RuntimeException(e);
        }
        return msg;
    }

    public byte[] convertInputStreamToBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        log.error("inputStream2:{}",inputStream.available());
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteStream.write(buffer, 0, bytesRead);
        }
        log.error("byteStream:{}",byteStream.toByteArray().length);

        return byteStream.toByteArray();
    }

}
