package cn.hnthyy.thmz.controller.mz;


import cn.hnthyy.thmz.Utils.ImageUtil;
import cn.hnthyy.thmz.Utils.JsonUtil;
import cn.hnthyy.thmz.Utils.TokenUtil;
import cn.hnthyy.thmz.comment.UserLoginToken;
import cn.hnthyy.thmz.entity.thmz.FileUpload;
import cn.hnthyy.thmz.entity.thmz.User;
import cn.hnthyy.thmz.enums.FileTypeEnum;
import cn.hnthyy.thmz.service.thmz.FileUploadService;
import cn.hnthyy.thmz.service.thmz.UserService;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

@Slf4j
@RestController
public class FileController {

    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private UserService userService;



    /**
     * 根据名称下载文件
     *
     * @param name
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/downloadByName", method = RequestMethod.GET)
    public ResponseEntity<?> downloadByName(@RequestParam("name") String name) {
        FileUpload fileUpload = fileUploadService.queryByName(name);
        if (fileUpload == null) {
            return new ResponseEntity<>("{文件没有找到}", HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-disposition", "attachment; filename=" + fileUpload.getFileName());
        String primaryType, subType;
        try {
            primaryType = fileUpload.getMimeType().split("/")[0];
            subType = fileUpload.getMimeType().split("/")[1];
        } catch (IndexOutOfBoundsException | NullPointerException ex) {
            return new ResponseEntity<>("{}", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        headers.setContentType(new MediaType(primaryType, subType));
        return new ResponseEntity<>(fileUpload.getFile(), headers, HttpStatus.OK);
    }



    /**
     * 根据主键下载文件
     *
     * @param id
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public ResponseEntity<?> downloadFile(@RequestParam("id") Long id) {
        FileUpload fileUpload = fileUploadService.queryByid(id);
        if (fileUpload == null) {
            return new ResponseEntity<>("{文件没有找到}", HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-disposition", "attachment; filename=" + fileUpload.getFileName());
        String primaryType, subType;
        try {
            primaryType = fileUpload.getMimeType().split("/")[0];
            subType = fileUpload.getMimeType().split("/")[1];
        } catch (IndexOutOfBoundsException | NullPointerException ex) {
            return new ResponseEntity<>("{}", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        headers.setContentType(new MediaType(primaryType, subType));
        return new ResponseEntity<>(fileUpload.getFile(), headers, HttpStatus.OK);
    }


    /**
     * 下载用户头像
     *
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/download-profile", method = RequestMethod.GET)
    public ResponseEntity<?> downloadProfile(HttpServletRequest request) {
        String token = TokenUtil.getToken(request);
        DecodedJWT decodedJWT = TokenUtil.parseJWT(token);
        User tokenUser = (User) JsonUtil.jsontoObject(decodedJWT.getSubject(), User.class);
        User user = userService.queryUserById(tokenUser.getId());
        FileUpload fileUpload = fileUploadService.queryByid(user.getProfileImage());
        if (fileUpload == null) {
            return new ResponseEntity<>("{\"code\":-1,\"message\":\"文件没有找到\"}", HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("content-disposition", "attachment; filename=" + fileUpload.getFileName());
        String primaryType, subType;
        try {
            primaryType = fileUpload.getMimeType().split("/")[0];
            subType = fileUpload.getMimeType().split("/")[1];
        } catch (IndexOutOfBoundsException | NullPointerException ex) {
            return new ResponseEntity<>("{\"code\":-1}", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        headers.setContentType(new MediaType(primaryType, subType));
        return new ResponseEntity<>(fileUpload.getSquareFile()!=null?fileUpload.getSquareFile():fileUpload.getFile(), headers, HttpStatus.OK);
    }


    /**
     * 文件上传
     *
     * @param request
     * @return
     */
    @UserLoginToken
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResponseEntity uploadFile(MultipartHttpServletRequest request) {
        try {
            Iterator<String> itr = request.getFileNames();
            while (itr.hasNext()) {
                String uploadedFile = itr.next();
                MultipartFile file = request.getFile(uploadedFile);
                String mimeType = file.getContentType();
                String filename = file.getOriginalFilename();
                byte[] bytes = file.getBytes();
                FileUpload newFile = new FileUpload(filename, bytes, mimeType);
                String token = TokenUtil.getToken(request);
                DecodedJWT decodedJWT = TokenUtil.parseJWT(token);
                User tokenUser = (User) JsonUtil.jsontoObject(decodedJWT.getSubject(), User.class);
                newFile.setCreateUser(tokenUser.getId());
                String fileType = request.getHeader("fileType");
                if (StringUtils.isNotBlank(fileType)) {
                    newFile.setFileType(Integer.valueOf(fileType));
                    if (FileTypeEnum.PROFILE_IMAGE.code.equals(newFile.getFileType())) {
                        newFile.setSquareFile(ImageUtil.formatToSquare(bytes, filename.substring(filename.indexOf(".") + 1), null));
                    }else if(FileTypeEnum.PRINT_DRIVE.code.equals(newFile.getFileType())){
                        newFile.setSquareFile(bytes);
                    }
                }
                fileUploadService.saveUploadFile(newFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件上传失败，错误原因：{}", e.getMessage());
            return new ResponseEntity<>("{\"code\":-1}", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>("{\"code\":0}", HttpStatus.OK);
    }




//    /**
//     * 上传身份证头像到指定文件目录
//     * @param file 图片file
//     */
//    @RequestMapping("/uploadIdImage")
//    @ResponseBody
//    public ResponseEntity uploadIdImage(@RequestParam("file")MultipartFile file) {
//        try {
//           FileUtils.upload(file);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("文件上传失败，错误原因：{}", e.getMessage());
//            return new ResponseEntity<>("{\"code\":-1}", HttpStatus.INTERNAL_SERVER_ERROR);
//        }
//        return new ResponseEntity<>("{\"code\":0}", HttpStatus.OK);
//    }


}
