package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.oss.entity.UploadResult;
import com.ruoyi.oss.factory.OssFactory;
import com.ruoyi.oss.service.IOssStrategy;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.domain.bo.SysOssBo;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.mapper.SysOssMapper;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文件上传 服务层实现
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysOssServiceImpl implements ISysOssService {

    @Value("${spring.profiles.active}")
    private String active;

    @Value("${upload-path.filePath}")
    private String filePath;

    @Value("${server.port}")
    private String port;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${upload-path.path}")
    private String path;


    private final SysOssMapper baseMapper;

    @Override
    public TableDataInfo<SysOssVo> queryPageList(SysOssBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysOss> lqw = buildQueryWrapper(bo);
        Page<SysOssVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysOss> buildQueryWrapper(SysOssBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysOss> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getFileName()), SysOss::getFileName, bo.getFileName());
        lqw.like(StringUtils.isNotBlank(bo.getOriginalName()), SysOss::getOriginalName, bo.getOriginalName());
        lqw.eq(StringUtils.isNotBlank(bo.getFileSuffix()), SysOss::getFileSuffix, bo.getFileSuffix());
        lqw.eq(StringUtils.isNotBlank(bo.getUrl()), SysOss::getUrl, bo.getUrl());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            SysOss::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), SysOss::getCreateBy, bo.getCreateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getService()), SysOss::getService, bo.getService());
        return lqw;
    }

    @Override
    public SysOss getById(Long ossId) {
        return baseMapper.selectById(ossId);
    }

    @Override
    public SysOss upload(MultipartFile file) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
        IOssStrategy storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }
        // 保存文件信息
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName(uploadResult.getFilename());
        oss.setOriginalName(originalfileName);
        oss.setService(storage.getServiceType().getValue());
        baseMapper.insert(oss);
        return oss;
    }

    @Override
    public SysOss apiUpload(MultipartFile file) {
        return this.localUpload(file);
    }

    private SysOss uploadFile(MultipartFile file) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
        IOssStrategy storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }

        // 保存文件信息
        SysOss oss = new SysOss();
//        oss.setUrl("prod".equals(active) ? filePath + File.separator + uploadResult.getFilename() : uploadResult.getUrl());
        oss.setUrl(uploadResult.getFilename());
        oss.setFileSuffix(suffix);
        oss.setFileName(uploadResult.getFilename());
        oss.setOriginalName(originalfileName);
        oss.setService(storage.getServiceType().getValue());
        return oss;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
        }
        List<SysOss> list = baseMapper.selectBatchIds(ids);
        for (SysOss sysOss : list) {
            IOssStrategy storage = OssFactory.instance(sysOss.getService());
            storage.delete(sysOss.getUrl());
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public SysOss localUpload(MultipartFile file) {
        try {
            // 获取项目路径
            String property = System.getProperty("user.dir");
            // 文件旧名称
            String oldName = file.getOriginalFilename();
            // 文件后缀（文件类型）
            String suffix = FileUtil.extName(oldName);
            // 获取文件新名称
            String newName = createNewFileName(oldName, suffix);
            // 获取文件存放路径
            String filePath = this.createFilePath(property) + newName;

            BufferedInputStream bufferedInputStream = (BufferedInputStream) file.getInputStream();
            this.copyFile(bufferedInputStream, filePath);

            // 本地路径替换成url
            String replace = this.urlByFilePath(property, filePath);

            // 保存文件信息
            SysOss oss = new SysOss();
            oss.setUrl(replace);
            oss.setFileSuffix(suffix);
            oss.setFileName(newName);
            oss.setOriginalName(oldName);
            oss.setService("本地上传");
            baseMapper.insert(oss);
            return oss;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败！");
        }
    }

    @Override
    public SysOss upload(byte[] bytes, String fileName, String contentType) {
        String suffix = StringUtils.substring(fileName, fileName.lastIndexOf("."), fileName.length());
        IOssStrategy storage = OssFactory.instance();
        UploadResult uploadResult = storage.uploadSuffix(bytes, suffix, contentType);
        // 保存文件信息
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName(uploadResult.getFilename());
        oss.setOriginalName(fileName);
        oss.setService(storage.getServiceType().getValue());
        baseMapper.insert(oss);
        return oss;
    }

    @Override
    public SysOss localUpload(byte[] bytes, String fileName) {
        try {
            String suffix = StringUtils.substring(fileName, fileName.lastIndexOf("."), fileName.length());

            // 获取项目路径
            String property = System.getProperty("user.dir");

            // 获取文件存放路径
            String filePath = this.createFilePath(property) + fileName;

            BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(bytes));
            this.copyFile(bufferedInputStream, filePath);

            // 本地路径替换成url
            String replace = this.urlByFilePath(property, filePath);

            // 保存文件信息
            SysOss oss = new SysOss();
            oss.setUrl(replace);
            oss.setFileSuffix(suffix);
            oss.setFileName(fileName);
            oss.setOriginalName(fileName);
            oss.setService("本地上传");
            baseMapper.insert(oss);
            return oss;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败！");
        }
    }

    /**
     * 获取文件新名字（UUID模式）
     * @param suffix
     * @return
     */
    private String createNewFileName(String suffix) {
        return IdUtil.fastSimpleUUID() + "." + suffix;
    }

    /**
     * 获取文件新名字（文件名称后面接时间戳）
     * @param oldName
     * @return
     */
    private String createNewFileName(String oldName, String suffix) {
        String[] split = oldName.split("\\.");
        if(split.length == 2){
            return split[0] + DateUtil.format(new Date(), "HHmmssSS") +"."+ split[1];
        } else {
            return split[0] + DateUtil.format(new Date(), "HHmmssSS") +"."+ suffix;
        }
    }

    /**
     * 创建文件路径
     *
     * @param propertyPath
     * @return
     */
    private String createFilePath(String propertyPath) {
        String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
        String path = propertyPath + filePath + File.separator + dateStr + File.separator;
        File file = new File(path);
        //如果路径不存在，新建
        if (!file.exists()) {
            file.mkdirs();
        }
        return path.replaceAll("\\\\", "/");
    }

    /**
     * 拷贝
     *
     * @param file
     * @param path
     * @throws Exception
     */
    private void copyFile(BufferedInputStream file, String path) throws Exception {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(path);
            bos = new BufferedOutputStream(fos);

            int size = 0;
            byte[] buffer = new byte[10240];
            while ((size = file.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败！");
        } finally {
            file.close();
            bos.close();
        }
    }

    /**
     * 文件路径替换成url
     *
     * @param property
     * @param filePathAll
     * @return
     */
    private String urlByFilePath(String property, String filePathAll) {
        String old = property + filePath;
        old = old.replaceAll("\\\\", "/");

        //TODO 此方法生成相对路径，需要前后端在同一台服务器 生产环境 本地上传放开这个
        return filePathAll.replace(old, path);

        //TODO 此方法会生成访问全路径
//        return filePathAll.replace(old, getUrl());
    }

    public String getUrl() {
        StringBuilder url = new StringBuilder();
        if (active.contains("prod")) {
            //线上
            StringBuffer requestUrl = ServletUtils.getRequest().getRequestURL();
            StringBuffer strBuf = requestUrl.delete(requestUrl.length() - ServletUtils.getRequest().getRequestURI().length(), requestUrl.length());
            url.append(strBuf);
        } else {
            //本地
            String ip = "";
            try {
                InetAddress address = InetAddress.getLocalHost();
                ip = address.getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }

            if (StringUtils.isBlank(ip) || "1.1.1.1".equals(ip)) {
                ip = "localhost";
            }
            url.append("http://").append(ip).append(":").append(this.port);

            String contextPath = ServletUtils.getRequest().getServletContext().getContextPath();
            if (StringUtils.isNotBlank(contextPath) && !"/".equals(contextPath)) {
                url.append(contextPath);
            }
        }
        if (StringUtils.isNotBlank(path) && !"/".equals(path)) {
            url.append(path);
        }
        return url.toString();
    }

}
