package cn.ysk.cashier.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.ysk.cashier.domain.QiniuConfig;
import cn.ysk.cashier.exception.BadRequestException;
import com.aliyun.teaopenapi.models.Config;
import com.dianguang.cloud.ossservice.config.CloudStorageConfig;
import com.dianguang.cloud.ossservice.service.OSSFactory;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import lombok.RequiredArgsConstructor;
import cn.ysk.cashier.domain.QiniuContent;
import cn.ysk.cashier.repository.QiniuContentRepository;
import cn.ysk.cashier.service.dto.QiniuQueryCriteria;
import cn.ysk.cashier.utils.QiNiuUtil;
import cn.ysk.cashier.repository.QiNiuConfigRepository;
import cn.ysk.cashier.service.QiNiuService;
import cn.ysk.cashier.utils.FileUtil;
import cn.ysk.cashier.utils.PageUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.ValidationUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author Zheng Jie
 * @date 2018-12-31
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "qiNiu")
public class QiNiuServiceImpl implements QiNiuService {

    private final QiNiuConfigRepository qiNiuConfigRepository;
    private final QiniuContentRepository qiniuContentRepository;

    @Value("${qiniu.max-size}")
    private Long maxSize;

    @Override
    @Cacheable(key = "'config'")
    public QiniuConfig find() {
        Optional<QiniuConfig> qiniuConfig = qiNiuConfigRepository.findById(1L);
        QiniuConfig config= qiniuConfig.orElseGet(QiniuConfig::new);
        return config;


    }

    @Override
    public CloudStorageConfig findCloud() {
        Optional<QiniuConfig> qiniuConfig = qiNiuConfigRepository.findById(1L);
        QiniuConfig config= qiniuConfig.orElseGet(QiniuConfig::new);
        if(ObjectUtil.isNotEmpty(config)){
            CloudStorageConfig cloudStorageConfig=new CloudStorageConfig();
            cloudStorageConfig.setType(2);
            cloudStorageConfig.setUrl(config.getBucket().concat(".").concat(config.getHost()));
            cloudStorageConfig.setPrefix("upload");
            cloudStorageConfig.setAccessKey(config.getAccessKey());
            cloudStorageConfig.setSecretKey(config.getSecretKey());
            cloudStorageConfig.setBucketName(config.getBucket());
            cloudStorageConfig.setEndPoint(config.getHost());
            return cloudStorageConfig;
        }

        return null;
    }

    @Override
    public Config findTempCloud() {
        Optional<QiniuConfig> qiniuConfig = qiNiuConfigRepository.findById(1L);
        QiniuConfig config= qiniuConfig.orElseGet(QiniuConfig::new);
        if(ObjectUtil.isNotEmpty(config)){
            com.aliyun.teaopenapi.models.Config config1 = new com.aliyun.teaopenapi.models.Config()
                    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
//                .setAccessKeyId(System.getenv("LTAI5tPdEfYSZcqHbjCrtPRD"))
                    .setAccessKeyId(qiniuConfig.get().getAccessKey())
                    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                    .setAccessKeySecret(qiniuConfig.get().getSecretKey());
            // Endpoint 请参考 https://api.aliyun.com/product/Sts
            config1.endpoint = "sts.cn-hangzhou.aliyuncs.com";
            return config1;
        }

        return null;
    }

    @Override
    @CachePut(key = "'config'")
    @Transactional(rollbackFor = Exception.class)
    public QiniuConfig config(QiniuConfig qiniuConfig) {
        qiniuConfig.setId(1L);
        //String http = "http://", https = "https://";
        ////if (!(qiniuConfig.getHost().toLowerCase().startsWith(http)||qiniuConfig.getHost().toLowerCase().startsWith(https))) {
        //    throw new BadRequestException("外链域名必须以http://或者https://开头");
        //}
        return qiNiuConfigRepository.save(qiniuConfig);
    }

    @Override
    public Object queryAll(QiniuQueryCriteria criteria, Pageable pageable){
        return PageUtil.toPage(qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
    }

    @Override
    public List<QiniuContent> queryAll(QiniuQueryCriteria criteria) {
        return qiniuContentRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String uploadVersionFile(MultipartFile file, CloudStorageConfig qiniuConfig,String fileName) {
        if(qiniuConfig== null){
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        // 构造一个带指定Zone对象的配置类
        try {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());

            return OSSFactory.build(qiniuConfig).uploadFileName(file.getBytes(), extension,fileName);
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QiniuContent upload(MultipartFile file, CloudStorageConfig qiniuConfig) {
        FileUtil.checkSize(maxSize, file.getSize());
        if(qiniuConfig== null){
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        // 构造一个带指定Zone对象的配置类
        try {

            String extension = FilenameUtils.getExtension(file.getOriginalFilename());
            String url = OSSFactory.build(qiniuConfig).uploadSuffix(file.getBytes(), extension);
            if(url != null){
                //存入数据库
                String[] str=url.split("/");

                String fileName=str[str.length-1];

                QiniuContent qiniuContent = new QiniuContent();
                qiniuContent.setKey(fileName);
                qiniuContent.setSuffix(fileName.split("\\.")[1]);
                qiniuContent.setBucket(qiniuConfig.getBucketName());
                qiniuContent.setSize(file.getSize()+"");
                qiniuContent.setType("公开");
                qiniuContent.setUrl(url);
                return qiniuContentRepository.save(qiniuContent);
            }
            return new QiniuContent();
        } catch (Exception e) {
           throw new BadRequestException(e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QiniuContent uploadByte(byte[] bytes, CloudStorageConfig qiniuConfig) {
        if(qiniuConfig== null){
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        // 构造一个带指定Zone对象的配置类
        try {
            String url = OSSFactory.build(qiniuConfig).uploadSuffix(bytes, "png");
            if(url != null){
                //存入数据库
                String[] str=url.split("/");

                String fileName=str[str.length-1];

                QiniuContent qiniuContent = new QiniuContent();
                qiniuContent.setKey(fileName);
                qiniuContent.setSuffix(fileName.split("\\.")[1]);
                qiniuContent.setBucket(qiniuConfig.getBucketName());
                qiniuContent.setSize(bytes.length+"");
                qiniuContent.setType("公开");
                qiniuContent.setUrl(url);
                return qiniuContentRepository.save(qiniuContent);
            }
            return new QiniuContent();
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }

    @Override
    public QiniuContent findByContentId(Long id) {
        QiniuContent qiniuContent = qiniuContentRepository.findById(id).orElseGet(QiniuContent::new);
        ValidationUtil.isNull(qiniuContent.getId(),"QiniuContent", "id",id);
        return qiniuContent;
    }

    @Override
    public String download(QiniuContent content,QiniuConfig config){
        String finalUrl;
        String type = "公开";
        if(type.equals(content.getType())){
            finalUrl  = content.getUrl();
        } else {
            Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
            // 1小时，可以自定义链接过期时间
            long expireInSeconds = 3600;
            finalUrl = auth.privateDownloadUrl(content.getUrl(), expireInSeconds);
        }
        return finalUrl;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(QiniuContent content, QiniuConfig config) {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(content.getBucket(), content.getKey() + "." + content.getSuffix());
            qiniuContentRepository.delete(content);
        } catch (QiniuException ex) {
            qiniuContentRepository.delete(content);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void synchronize(QiniuConfig config) {
        if(config.getId() == null){
            throw new BadRequestException("请先添加相应配置，再操作");
        }
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(QiNiuUtil.getRegion(config.getZone()));
        Auth auth = Auth.create(config.getAccessKey(), config.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(config.getBucket(), prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            QiniuContent qiniuContent;
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                if(qiniuContentRepository.findByKey(FileUtil.getFileNameNoEx(item.key)) == null){
                    qiniuContent = new QiniuContent();
                    qiniuContent.setSize(FileUtil.getSize(Integer.parseInt(item.fsize+"")));
                    qiniuContent.setSuffix(FileUtil.getExtensionName(item.key));
                    qiniuContent.setKey(FileUtil.getFileNameNoEx(item.key));
                    qiniuContent.setType(config.getType());
                    qiniuContent.setBucket(config.getBucket());
                    qiniuContent.setUrl(config.getHost()+"/"+item.key);
                    qiniuContentRepository.save(qiniuContent);
                }
            }
        }
    }

    @Override
    public void deleteAll(Long[] ids, QiniuConfig config) {
        for (Long id : ids) {
            delete(findByContentId(id), config);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(String type) {
        qiNiuConfigRepository.update(type);
    }

    @Override
    public void downloadList(List<QiniuContent> queryAll, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (QiniuContent content : queryAll) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("文件名", content.getKey());
            map.put("文件类型", content.getSuffix());
            map.put("空间名称", content.getBucket());
            map.put("文件大小", content.getSize());
            map.put("空间类型", content.getType());
            map.put("创建日期", content.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
