package com.fufan.mtsaas.modules.base;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.fufan.mtsaas.modules.common.bo.request.ResultPack;
import com.fufan.mtsaas.modules.common.bo.response.RequestPojo;
import com.fufan.mtsaas.modules.common.bo.response.ResStatus;
import com.fufan.mtsaas.modules.common.bo.response.Result;
import com.fufan.mtsaas.util.ParamUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
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.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @ClassName: FileUploadController
 * @description: 文件上传 控制器
 * @author: Lihua
 * @date: 2021-10-12 14:03
 * @version: V1.0
 **/
@Slf4j
@RestController
@RequestMapping("fileupload")
@Api(tags  = "公共-上传文件")
@RequiredArgsConstructor
public class FileUploadController {

    @Value("${upload.data.uploadFolder}")
    protected String uploadingdir;

    @Value("${upload.data.httpUrl}")
    protected String httpUrl;

    @RequestMapping("/imgUpload")
    @ApiOperation(value = "单上传文件",notes = "单上传文件",httpMethod = "POST")
    public @ResponseBody Result imgUpload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        Result result = new Result();
        RequestPojo requestPojo = ParamUtil.doChange();
        if (file.isEmpty()) {
            result.setResMsg(ResStatus.UPLOAD_FILE_FAILED);
            result.setResStatus(ResStatus.UPLOAD_FILE_FAILED_MSG+",没有上传文件");
            return new ResultPack().doResultPack(result,requestPojo.getIntfId(),requestPojo.getAppKey());
        }

        String fileName = file.getOriginalFilename();
        String extname = FilenameUtils.getExtension(fileName);
        //新文件名
        fileName = UUID.randomUUID() + "." + extname;
        //按年月日分的子目录
        Calendar now = Calendar.getInstance();
        String subdir = "upload/" + now.get(Calendar.YEAR) + "-"
                + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DAY_OF_MONTH);
        String filePath = uploadingdir + "/" + subdir + "/" + fileName;
        Path path = Paths.get(filePath);

//        if (!dest.getParentFile().exists()) {
//            dest.getParentFile().mkdirs();
//        }
//        if(!dest.exists()){
//            dest.mkdirs();
//        }
        //根目录
        String strRootUrl = this.getRootUrl(request);
        try {
            Files.createDirectories(path.getParent());
            File dest = new File(filePath);
            Files.createFile(path);
            file.transferTo(dest);
            //相对路径
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", fileName);
            jsonObject.put("src", "/" + subdir + "/" + fileName);
            //mapObject.put("relative_url", "/" + subdir + "/" + fileName);
            jsonObject.put("url", strRootUrl + subdir + "/" + fileName);
            //mapObject.put("url",  this.getRootUrl(request) + "/" + subdir + "/" + fileName);
            //return this.WriteResult(mapObject);
            result.setResMsg(ResStatus.STATUS_SUCCESS);
            result.setResStatus(ResStatus.UPLOAD_FILE_SUCCESS_MSG);
            Page page = new Page<>();
            List<JSONObject> list = new ArrayList<>();
            list.add(jsonObject);
            page.setRecords(list);
            result.setResData(page);

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            result.setResMsg(ResStatus.UPLOAD_FILE_FAILED);
            result.setResStatus(ResStatus.UPLOAD_FILE_FAILED_MSG + e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            result.setResMsg(ResStatus.UPLOAD_FILE_FAILED);
            result.setResStatus(ResStatus.UPLOAD_FILE_FAILED_MSG + e.getMessage());
        }
        return new ResultPack().doResultPack(result,requestPojo.getIntfId(),requestPojo.getAppKey());
    }
    /**
     * 多文件上传
     */
//    @ApiOperation(value = "多上传文件",notes = "多上传文件",httpMethod = "POST")
//    @RequestMapping(value = "/multifileupload", method = RequestMethod.POST)
//    public @ResponseBody Object multifileUpload(HttpServletRequest request){
//        Result result = new Result();
//        RequestPojo requestPojo = ParamUtil.doChange();
//        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("filename");
//        if (files.isEmpty()) {
//            result.setResMsg(ResStatus.UPLOAD_FILE_FAILED);
//            result.setResStatus(ResStatus.UPLOAD_FILE_FAILED_MSG+",没有上传文件");
//            return new ResultPack().doResultPack(result,requestPojo.getIntfId(),requestPojo.getAppKey());
//        }
//
//        //按年月日分的子目录
//        Calendar now = Calendar.getInstance();
//        String subdir = "upload/" + now.get(Calendar.YEAR) + "/"
//                + (now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DAY_OF_MONTH);
//        String path = uploadingdir + "/" + subdir;
//        File fileDir = new File(path);
//        if (!fileDir.exists()) {
//            fileDir.mkdirs();
//        }
//        //根目录
//        String strRootUrl = this.getRootUrl(request);
//        List<Map<String, Object>> lstFiles = new ArrayList<>();
//        for (MultipartFile file : files) {
//            String fileName = file.getOriginalFilename();
//            String extname = FilenameUtils.getExtension(fileName);
//            //新文件名
//            fileName = UUID.randomUUID() + "." + extname;
//            int size = (int) file.getSize();
//            if (file.isEmpty()) {
//                result.setResMsg(ResStatus.UPLOAD_FILE_FAILED);
//                result.setResStatus(ResStatus.UPLOAD_FILE_FAILED_MSG+",没有上传文件");
//                return new ResultPack().doResultPack(result,null,null);
//            } else {
//                File dest = new File(path + "/" + fileName);
//                try {
//                    file.transferTo(dest);
//                    //相对路径
//                    Map<String, Object> mapObject = new HashMap<>();
//                    mapObject.put("relative_url", "/" + subdir + "/" + fileName);
//                    mapObject.put("url", strRootUrl + "/" + subdir + "/" + fileName);
//                    lstFiles.add(mapObject);
//                    result.setResMsg(ResStatus.UPLOAD_FILE_SUCCESS);
//                    result.setResStatus(ResStatus.UPLOAD_FILE_SUCCESS_MSG);
//                } catch (Exception e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                    result.setResMsg(ResStatus.UPLOAD_FILE_FAILED);
//                    result.setResStatus(ResStatus.UPLOAD_FILE_FAILED_MSG + e.getMessage());
//                }
//            }
//        }
//
//        Page page = new Page<>();
//        page.setRecords(lstFiles);
//        return new ResultPack().doResultPack(result,requestPojo.getIntfId(),requestPojo.getAppKey());
//    }
    //通过相对路径获取绝对路径
    protected String getRootUrl(HttpServletRequest request) {
        //图片根目录
//        String filerootpath = "http://139.196.226.235:9062";
////        filerootpath = "http://" + request.getServerName() + ":" + request.getServerPort();
//        if (request.getServerName().toLowerCase().equals("localhost") || request.getServerName().toLowerCase().equals("127.0.0.1")) {
//            filerootpath = "http://" + request.getServerName() + ":" + request.getServerPort() + "/";
//        } else {
//            //SqlMapper sqlMapper = new SqlMapper(sqlSessions);
//            //filerootpath = sqlMapper.fetchScale("select f_img_src('', 3) as img_root");
//            //filerootpath = "http://121.42.231.1:8762";
//            filerootpath = httpUrl;
//        }
        return httpUrl;
    }
}
