package com.qmth.file.controller;

import com.qmth.file.config.SystemConfig;
import com.qmth.file.core.FileMD5Utils;
import com.qmth.file.enums.ExamStatus;
import com.qmth.file.exception.FileServerException;
import com.qmth.file.model.AttachmentPhoto;
import com.qmth.file.model.ExamPlan;
import com.qmth.file.service.ExamPlanService;
import com.qmth.file.service.JkAttachmentPhotoService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLDecoder;

/**
 * @author xf
 */
@RestController
@RequestMapping("/api/jkdevice")
public class FileUploadController implements Serializable {

    private static final long serialVersionUID = 227423597082641591L;

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);

    @Autowired
    private SystemConfig systemConfig;

    @Resource
    @Lazy
    private ExamPlanService examPlanService;

    @Resource
    JkAttachmentPhotoService jkAttachmentPhotoService;

    @RequestMapping("/test")
    public Object test(String test) {
        return "hello!" + test;
    }

    /**
     * 考生抓拍头像图片上传
     *
     * @param request
     * @param file
     * @throws IOException
     */
    @RequestMapping(value = "/upload_catch_photo", method = RequestMethod.POST)
    public Object upload(HttpServletRequest request,
                         @RequestParam(required = false, value = "file") MultipartFile file) throws IOException {
        request.setCharacterEncoding("UTF-8");
        String examCode = request.getHeader("examCode");
        String placeCode = request.getHeader("placeCode");
        String roomCode = request.getHeader("roomCode");
        String fileName = request.getHeader("fileName");
        String md5 = request.getHeader("md5");

        ExamPlan examPlan = examPlanService.findByExamCode(examCode);
        if (StringUtils.isEmpty(examCode) || examPlan == null) {
            throw FileServerException.EXAM_CODE_INVALID;
        }
        if (!ExamStatus.PUBLISHED.equals(examPlan.getExamStatus())) {
            throw FileServerException.EXAM_PLAN_UN_PUBLISHED;
        }

        if (file == null) {
            LOGGER.error("没有检测到文件实体");
            throw FileServerException.withMessage("没有检测到文件实体");
        } else {
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                // 创建随机文件夹
                File storeDir = new File(systemConfig.getRoot());
                storeDir = new File(storeDir, examCode);
                if (!storeDir.exists()) {
                    storeDir.mkdirs();
                    if (!storeDir.exists()) {
                        throw FileServerException.withMessage("@@create dir failed:" + storeDir.getAbsolutePath());
                    }
                }
                if (StringUtils.isNotEmpty(fileName)) {
                    fileName = URLDecoder.decode(fileName, "UTF-8");
                }
                if (StringUtils.isEmpty(fileName)) {
                    fileName = file.getOriginalFilename();
                }
                File saveFile = new File(storeDir, fileName);
                LOGGER.info("@@target file:" + saveFile.getAbsolutePath());
                if (!saveFile.exists()) {
                    saveFile.createNewFile();
                }
                inputStream = file.getInputStream();
                outputStream = new FileOutputStream(saveFile);
                IOUtils.copy(inputStream, outputStream);
                // 存储文件
                AttachmentPhoto attachment = new AttachmentPhoto();
                attachment.setExamCode(examCode);
                attachment.setPlaceCode(placeCode);
                attachment.setRoomCode(roomCode);
                attachment.setFileName(fileName);
                String mymd5 = FileMD5Utils.encrypt(saveFile);
                if (StringUtils.isNotEmpty(md5)) {
                    if (!mymd5.equals(md5)) {
                        throw FileServerException.withMessage("文件MD5校验失败");
                    }
                }
                attachment.setSize((double) saveFile.length());
                attachment.setMd5(mymd5);
                attachment.setPath(saveFile.getAbsolutePath());
                attachment.setCreateTime(System.currentTimeMillis());
//				attachmentPhotoDao.save(attachment);
                jkAttachmentPhotoService.saveOrUpdate(attachment);
                IOUtils.closeQuietly(outputStream);
                IOUtils.closeQuietly(inputStream);
                System.out.println("upload file successfully:" + saveFile.getAbsolutePath());
                return true;
            } finally {
                if (outputStream != null) {
                    IOUtils.closeQuietly(outputStream);
                }
                if (inputStream != null) {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    }

}
