package com.template.services.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.template.common.utils.TimeExchange;
import com.template.config.CosConfig;
import com.template.mapper.SmartUserMapper;
import com.template.model.pojo.SmartUser;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.AffiliateUserVo;
import com.template.services.SmartUploadService;
import com.template.services.SmartUserService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ceshi
 * @since 2023-12-04
 */
@Service
public class SmartUploadServiceImpl implements SmartUploadService {

    @Resource
    private COSClient cosClient;

    @Resource
    private CosConfig cosConfig;

    @Override
    public String upload(MultipartFile[] files) {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(cosConfig.getSecretId(), cosConfig.getSecretKey());
        // 2 设置 bucket 的区域
        Region region = new Region(cosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClientU = new COSClient(cred, clientConfig);

        String response = null;
        String res = "";
        try {
            for (MultipartFile file : files) {
                System.out.println("运行时间1："+ TimeExchange.DateToString(new Date()));
                String originalFileName = file.getOriginalFilename();
                System.out.println("运行时间2："+ TimeExchange.DateToString(new Date()));
                // 获得文件流
                InputStream inputStream = null;
                System.out.println("运行时间3："+ TimeExchange.DateToString(new Date()));
                inputStream = file.getInputStream();
                System.out.println("运行时间4："+ TimeExchange.DateToString(new Date()));
                // 设置文件路径
                String filePath = getFilePath(originalFileName, "excelModel");
                System.out.println("运行时间5："+ TimeExchange.DateToString(new Date()));
                // 上传文件
                String bucketName = cosConfig.getBucketName();
                System.out.println("运行时间6："+ TimeExchange.DateToString(new Date()));
                ObjectMetadata objectMetadata = new ObjectMetadata();
                System.out.println("运行时间7："+ TimeExchange.DateToString(new Date()));
                objectMetadata.setContentLength(file.getSize());
                System.out.println("运行时间8："+ TimeExchange.DateToString(new Date()));
                objectMetadata.setContentType(file.getContentType());
                System.out.println("运行时间9："+ TimeExchange.DateToString(new Date()));
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath, inputStream, objectMetadata);
                System.out.println("运行时间10："+ TimeExchange.DateToString(new Date()));
                cosClientU.putObject(putObjectRequest);
                System.out.println("运行时间11："+ TimeExchange.DateToString(new Date()));
                cosClientU.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                System.out.println("运行时间12："+ TimeExchange.DateToString(new Date()));
                String url = cosConfig.getPath() + "/" + filePath;
                System.out.println("运行时间11："+ TimeExchange.DateToString(new Date()));
                res += url + ",";
            }
            String paths = res.substring(0, res.length() - 1);
            response = paths;
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            cosClientU.shutdown();
        }
        return response;
    }

    @Override
    public void deleteByFileName(String fileName) {
        cosConfig.cosClient();
        // 文件桶内路径
        String filePath = getDelFilePath(fileName, "excelModel/");
        cosClient.deleteObject(cosConfig.getBucketName(), filePath);
    }


    /**
     * 生成文件路径
     * @param originalFileName 原始文件名称
     * @param folder 存储路径
     * @return
     */
    private String getFilePath(String originalFileName, String folder) {
        // 获取后缀名
        String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 以文件后缀来存储在存储桶中生成文件夹方便管理
        String filePath = folder + "/";
        // 去除文件后缀 替换所有特殊字符
        String fileStr = StrUtil.removeSuffix(originalFileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
        //filePath += new DateTime().toString("yyyyMMddHHmmss") + "_" + fileStr + fileType; 去除时间
        filePath += originalFileName;
        return filePath;
    }
    /**
     * 生成文件路径
     * @param originalFileName 原始文件名称
     * @param folder 存储路径
     * @return
     */
    private String getDelFilePath(String originalFileName, String folder) {
        // 获取后缀名
        String fileType = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 以文件后缀来存储在存储桶中生成文件夹方便管理
        String filePath = folder + "/";
        // 去除文件后缀 替换所有特殊字符
        String fileStr = StrUtil.removeSuffix(originalFileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
        filePath += fileStr + fileType;
        return filePath;
    }
}
