package com.xunwang.file.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.util.UuidUtils;
import com.xunwang.servicebase.exception.XunwangException;
import com.xunwang.servicebase.utils.ResultCode;
import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class MinioUtil {

    @Value("education")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Resource
    private MinioClient minioClient;

    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;



    /**
     * TODO
     *
     * @Description  为解决教员修改认证时，审核中的，新的头像Url被使用的问题 copyTeacherHeadPhotoFileToNewName
     * @Author Paul  Email:8203193@qq.com
     * @Version 1.0
     * @Date 2023/6/21 17:00
     *
     * 拷贝文件
     *
     * @param srcObjectName 源 文件名称
     * @param desObjectName 目标 文件名称
     */
        public String copyTeacherHeadPhotoFileToNewName( String srcObjectName,String desObjectName) {
            String result = "";
            try {
                ObjectWriteResponse owr = minioClient.copyObject(
                        CopyObjectArgs.builder()
                                .source(CopySource.builder().bucket(bucketName).object(srcObjectName).build())
                                .bucket(bucketName)
                                .object(desObjectName)
                                .build());
            } catch (Exception e) {
                throw new XunwangException(ResultCode.ERROR, e.getMessage());
            }
            result =  endpoint + "/" + bucketName + "/" + desObjectName;
            return  result;
        }



    /**
     * 查看存储bucket是否存在
     * @param bucketName
     * @return
     */
    public Boolean bucketExists(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        Boolean found = minioClient.bucketExists(BucketExistsArgs.builder()
                .bucket(bucketName)
                .build());
        return found;
    }

    /**
     * 创建存储bucket
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除存储bucket
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        List<Bucket> buckets = minioClient.listBuckets();
        return buckets;
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            log.warn("上传文件名为空");
            return "";
        }
        String uuid = UuidUtils.generateUuid().replaceAll("-", "");
        String fileName = uuid + originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = System.currentTimeMillis() + fileName;
        try {
            minioClient.putObject(PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return endpoint + "/" + bucketName + "/" + objectName;
    }


    /**
     * TODO
     *
     * @Description 小程序二维码上传 minio
     * @Author Paul  Email:8203193@qq.com
     * @Version 1.0
     * @Date 2023/6/12 11:45
     *
     */

    public String upload(MultipartFile file, String subBucketName,String filename) {

        String objectName = subBucketName + "/" + filename;
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            throw new XunwangException(ResultCode.ERROR, e.getMessage());
         //   return "";
        }
        return endpoint + "/" + bucketName + "/" + objectName;
    }

    /**
     * TODO
     *
     * @Description 接收Http 响应数据
     * @Author Paul  Email:8203193@qq.com
     * @Version 1.0
     * @Date 2023/6/12 10:38
     *
     */
    public static ByteArrayInputStream sendPost(String URL, String json) {
        InputStream inputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            HttpResponse response = httpclient.execute(httppost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                inputStream = entity.getContent();
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                // 创建一个Buffer字符串
                byte[] buffer = new byte[1024];
                // 每次读取的字符串长度，如果为-1，代表全部读取完毕
                int len = 0;
                // 使用一个输入流从buffer里把数据读取出来
                while ((len = inputStream.read(buffer)) != -1) {
                    // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                    outStream.write(buffer, 0, len);
                }
                // 关闭输入流
                inputStream.close();
                // 把outStream里的数据写入内存
                byteArrayInputStream = new ByteArrayInputStream(outStream.toByteArray());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new XunwangException(ResultCode.ERROR, e.getMessage());
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArrayInputStream;
    }

    /**
     * TODO
     *
     * @Description  获取小程序菊花码 （携带的用户的 uid ）
     * @Author Paul  Email:8203193@qq.com
     * @Version 1.0
     * @Date 2023/6/12 10:42
     *
     */
    public String getWXCode(String uid){

        String urlStr = "";
            //获取access_token
        String access_token = (String) redisTemplate.opsForValue().get("access_token");

        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
            String scene = uid;  //携带参数放在scene 内

            Map<String, String> param = new HashMap<>();
            param.put("scene", scene);
            //这里的page如果没有的话可以不写，默认是跳主页，如果写了没有的页面的话，会返回错误信息
            param.put("page", "pages/home/home");
            String json = JSON.toJSONString(param);
            ByteArrayInputStream inputStream = sendPost(url, json);
            //这里判断的是返回的图片还是错误信息，一般错误信息不会大于300
            System.out.println(inputStream.available());
            if (inputStream.available() <= 300) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int i;
                byte[] buffer = new byte[300];
                while ((i = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, i);
                }
                String str = new String(byteArrayOutputStream.toByteArray());
                //错误信息的格式在官方文档里有
                JSONObject jsonObject = JSONObject.parseObject(str);

                byteArrayOutputStream.close();
                log.error("getwxacodeunlimit errcode: " + jsonObject.getString("errcode"));
                throw new XunwangException(ResultCode.ERROR, "getwxacodeunlimit errcode: " + jsonObject.getString("errcode"));
            }

            MultipartFile file = new MultipartFileDto("noneName","noneName", ContentType.IMAGE_PNG.toString(), inputStream);
            urlStr = upload(file, uid, "qrc.png");

            inputStream.close();
            log.info("二维码生成成功");
        } catch (Exception e) {
            log.error("获取二维码异常");
            throw new XunwangException(ResultCode.ERROR, e.getMessage());
//            throw new CustomizeException(e.getMessage());
        }
        return urlStr;
    }
}
