package com.rf.psychological.file;

import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.utils.OSUtil;
import com.rf.psychological.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author zzf
 * @description:download APK 下载安装包
 * @date 2021/5/11 10:57
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Api(tags = "文件下载")
public class FileController extends BaseController {

    @ApiOperation(value = "安装包/量表模板下载：flag=APK表示下载安装包，flag=model表示下载量表模板")
    @GetMapping("/download/{flag}")
    public String downloadFile(@PathVariable String flag, String file_name ,HttpServletResponse response) throws Exception {
        String fileName = "";
        if(flag.equals("model")){
            fileName = "量表导入模板.xlsx";
//            fileName = "scaleModel.xlsx";
        }else if(flag.equals("APK")){
            fileName = "psychological.apk";
        }else if("scale".equals(flag)){
           fileName=file_name;
        }else if("pluseApp".equals(flag)){
            fileName="pluse_app_2.1.apk";
        }else{
            return "下载标志错误";
        }
        if (fileName != null) {
//            fileName = fileName.replace('_','-')+""
            File file = null;
            //设置文件路径
            if(OSUtil.isLinux()){

                if("scale".equals(flag)){
                    file = new File("./scales/"+fileName);
                }else{
                    file = new File("./"+fileName);
                }
            }else{

                if("scale".equals(flag)){
                    file = new File("./psychological/scales/"+fileName);
                }else if ("pluseApp".equals(flag)){
                    String filepath = FileController.txt2String(new File("C:/DataPilot/file-group-apk.txt"));
                    file = new File(filepath+fileName);
                }else if("model".equals(flag)){
                    file = new File("./"+fileName);
                }else {
                    file = new File("./心理检测/安装包/"+fileName);
                }
            }
            if (file.exists()) {
               /* response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                response.setContentType("application/binary;charset=ISO8859-1");*/
                response.reset();
                response.setContentType("application/octet-stream");
                response.setCharacterEncoding("utf-8");
                response.setContentLength((int) file.length());
                response.setHeader("Content-Disposition", "attachment;filename="+ java.net.URLEncoder.encode(fileName, "UTF-8"));

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }

    /**
     * 自定义量表文件上传
     * @param file
     * @return
     */
    @PostMapping("/customUpload")
    public Result customUpload(MultipartFile file, HttpServletRequest request) throws Exception {
        //文件保存
        String fileName = "";
        String FILEDIR;
        String customDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        if (OSUtil.getOSname().equalsIgnoreCase("Windows")) {
            FILEDIR = "./psychological/scales/"+customDate+"/";
        } else {
            FILEDIR = "./scales/"+customDate+"/";
        }
        if (file == null) {
            throw new Exception("文件为空");
        } else {
            String suffix = file.getOriginalFilename();

            if (!file.isEmpty()) {
                fileName = suffix;
                try {
                    File temp = new File(FILEDIR);
                    if (!temp.exists()) {
                        temp.mkdirs();
                    }
                    System.out.println("FILEDIR---" + FILEDIR);
                    System.out.println("fileName--" + fileName);
                    File fileLocal = new File(FILEDIR, fileName);
                    FileUtils.copyInputStreamToFile(file.getInputStream(), fileLocal);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


        return success(FILEDIR+fileName);
    }

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result fileUpload(MultipartFile file, HttpServletRequest request) throws Exception {

        String fileName = "";
        String FILEDIR ;
        String filePath = "static/images/";
        if(OSUtil.getOSname().equalsIgnoreCase("Windows")){
            FILEDIR ="./psychological/images/";
        }else {
//            FILEDIR = request.getServletContext().getRealPath(filePath);
            FILEDIR = "./images/";
        }
        if(file == null){
            throw new Exception("文件为空");
        }else {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
            if(!file.isEmpty()){
                fileName = UUID.randomUUID()+"."+suffix;
                try{
                    File temp = new File(FILEDIR);
                    if(!temp.exists()){
                        temp.mkdirs();
                    }
                    System.out.println("FILEDIR---"+FILEDIR);
                    System.out.println("fileName--"+fileName);
                    File fileLocal = new File(FILEDIR,fileName);
//                    file.transferTo(fileLocal);
                    FileUtils.copyInputStreamToFile(file.getInputStream(),fileLocal);
                }catch (Exception e ){
                    e.printStackTrace();
                    return fail();
                }
            }
        }
        return success(filePath+fileName);
    }

    /**
     * 文件上传局域网版上传采集到的数据文件
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadData")
    public Result dataUpload(MultipartFile file, HttpServletRequest request) throws Exception {

        String fileName = file.getOriginalFilename();
        String FILEDIR;
        String filePath = "static/pulse/";
        if (OSUtil.getOSname().equalsIgnoreCase("Windows")) {
            //FILEDIR = "./pulse/data/";
            FILEDIR = "C:/pulse/data";
        } else {
//            FILEDIR = request.getServletContext().getRealPath(filePath);
            FILEDIR = "./data/";
        }
        if (file == null) {
            throw new Exception("文件为空");
        } else {
//            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (!file.isEmpty()) {
//                fileName = UUID.randomUUID() + "." + suffix;
                try {
                    File temp = new File(FILEDIR);
                    if (!temp.exists()) {
                        temp.mkdirs();
                    }
                    System.out.println("FILEDIR---" + FILEDIR);
                    System.out.println("fileName--" + fileName);
                    File fileLocal = new File(FILEDIR, fileName);
//                    file.transferTo(fileLocal);
                    FileUtils.copyInputStreamToFile(file.getInputStream(), fileLocal);
                } catch (Exception e) {
                    e.printStackTrace();
                    return fail();
                }
            }
        }
        return success(filePath + fileName);
    }

    /**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                //result.append(System.lineSeparator()+s);换行
                result.append(s);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }


}


