package com.artfess.xqxt.meeting.manager.impl;

import com.artfess.base.context.BaseContext;
import com.artfess.xqxt.meeting.model.BizMeetingAccessory;
import com.artfess.xqxt.meeting.dao.BizMeetingAccessoryDao;
import com.artfess.xqxt.meeting.manager.BizMeetingAccessoryManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;



import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;


/**
 * 通用附件表 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author 管理员
 * @since 2022-10-28
 */
@Service
public class BizMeetingAccessoryManagerImpl extends BaseManagerImpl<BizMeetingAccessoryDao, BizMeetingAccessory> implements BizMeetingAccessoryManager {

    @Value("${file.tempFilePath}")
    private String tempFilePath;

    @Resource
    private BaseContext baseContext;

    @Override
    public String upload(MultipartFile file,String id) throws IOException {
        System.out.println(file);
        if (file == null || file.isEmpty()) {
            return "";
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件的前缀名
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        //获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);
        //获取文件大小
        int fileSize = (int) file.getSize();
        //获取编号
        Long code = getCode();
        //生成当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateNow = sdf.format(date);
        //文件路径
        File directory = new File(".");
        String filePath = directory.getCanonicalPath();
        String name = prefixName  + "."+suffixName;
        String tempFilePathSuffer = tempFilePath.substring(tempFilePath.lastIndexOf(".") + 1);
        String path = filePath + tempFilePathSuffer + dateNow + "/" + name;
        //文件存储路径:保存到数据库
        File dest = new File(path);
        // 判断路径是否存在，如果不存在则创建
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        BizMeetingAccessory aiFile = new BizMeetingAccessory();
        try {
            //保存文件
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(path));
            outputStream.write(file.getBytes());
            outputStream.flush();
            outputStream.close();
            //保存相关信息到数据库
            aiFile.setName(name);
            aiFile.setSuffix(suffixName);
            aiFile.setFileSize(fileSize);
            aiFile.setUrl(path);
            aiFile.setCreateBy(baseContext.getCurrentUserId());
            aiFile.setCreateName(baseContext.getCurrentUserName());
            if (StringUtils.isNotEmpty(id)){
                aiFile.setSourceId(id);
            }
            aiFile.setCreateTime(LocalDateTime.now());
            this.baseMapper.insert(aiFile);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return aiFile.getId();
    }

    @Override
    public void download(Long id, HttpServletRequest req, HttpServletResponse res) {
        if (id != null) {
            BizMeetingAccessory entity = this.getById(id);
            String path = entity.getUrl();
            setDownloadContent(entity.getName(), req, res);
            // 重要，需要设置此值，否则下载后打开文件会提示文件需要修复
            res.setContentLength(entity.getFileSize());
            File file = new File(path);
            if (file.exists()) {
                byte[] buffer = new byte[1024];
                //输出流
                OutputStream os;
                try (FileInputStream fis = new FileInputStream(file);
                     BufferedInputStream bis = new BufferedInputStream(fis);) {
                    os = res.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Override
    public void preview(Long id, HttpServletRequest req, HttpServletResponse res) {
        if (id != null) {
            BizMeetingAccessory entity = this.getById(id);
            String path = entity.getUrl();
            res.setContentLength(entity.getFileSize());
            File file = new File(path);
            byte[] buffer = FileUtil.readBytes(path);
            if (file.exists()) {
                try {
                    //设置contentType
                    res.setContentType(MediaType.ALL_VALUE);
                    res.setCharacterEncoding("UTF-8");
                    //获取outputStream
                    ServletOutputStream outputStream = res.getOutputStream();
                    //输出
                    IoUtil.write(outputStream, true, buffer);
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * 客户端下载文件上response header的设置。
     *
     * @param fileName 文件名
     * @param request  请求
     * @param response 响应
     */
    private void setDownloadContent(String fileName, HttpServletRequest request, HttpServletResponse response) {
        String agent = request.getHeader("User-Agent");
        try {
            if (null != agent && agent.toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
        } catch (UnsupportedEncodingException e1) {
        }
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    }


    /**
     * 生成编号
     *
     * @return code
     */
    private static Long getCode() {
        //生成当前时间戳的ID
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        //生成5位随机数
        int randomNum = (int) ((Math.random() * 9 + 1) * 10000);
        String result = String.valueOf(randomNum);
        String s = newDate + result;
        Long code = Long.parseLong(s);
        return code;
    }



}
