package com.usky.iot.controller.web;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.FileUtils;
import com.usky.common.core.util.GlobalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

/**
 * 文件系统
 * @author yq
 * @date 2022/1/25 13:42
 */
@RestController
@RequestMapping("file")
@Slf4j
public class FileController {


    /**
     * 上传文件
     * @param multipartFile
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public ApiResult<Void> upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request){
        Optional.ofNullable(multipartFile).orElseThrow(() ->  new BusinessException("文件为空"));
        System.out.println(multipartFile.getSize());
        cutFile(multipartFile,1024);
        return ApiResult.success();
    }


    private static void cutFile(MultipartFile multipartFile, int num) {

        InputStream inputStream = null;
        try {
            byte [] byteArr=multipartFile.getBytes();
            inputStream = new ByteArrayInputStream(byteArr);
            //创建规定大小的byte数组
            byte[] b = new byte[num];
            int len = 0;
            //name为以后的小文件命名做准备
            int name = 1;
            //遍历将大文件读入byte数组中，当byte数组读满后写入对应的小文件中
            while ((len = inputStream.read(b)) != -1) {
                int chk = 0x0000;
                for(int i=0;i<len;i++){
                    chk += b[i]&0x00ff;
                }
                System.out.println(String.format("%04x", chk& 0x0000ffff));
                name++;
            }
            String s = MD5Utils.md5Hex(byteArr);
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除文件
     * @param fileName
     * @return
     */
    @RequestMapping("/delete")
    public ApiResult<Boolean> delete(@RequestParam String fileName){
        File file = FileUtils.getFile(GlobalUtils.getTempBaseDir(), fileName);
        return ApiResult.success(file.delete());
    }
}
