package com.chy.borrow.controller;

import com.chy.borrow.util.CSVUtil;
import com.chy.borrow.util.FileUploadUtil;
import com.shanghaigeography.entity.ResultMsg;
import com.shanghaigeography.eum.ResultState;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@CrossOrigin
@RequestMapping("/file")
public class FileUploadController extends BaseController {

    @RequestMapping("/upload")
    @ResponseBody
    public String list(@RequestParam("file") MultipartFile multipartFile) {
        try {
            String fileName = FileUploadUtil.uploadToBasePath(multipartFile, "D:\\file\\").replaceAll("\\\\", "/");
            String url = "http://47.101.207.123:8080/file/"+fileName;

            List result = new ArrayList();
            Map map = new HashMap();
            map.put("fileUrl",url);
            result.add(map);
            return new ResultMsg<>().setCode(ResultState.SUCCESS).setMsg("文件上传成功").setData(result).toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("文件上传失败").toJSON();
        }
//        return FileUploadUtil.uploadToBasePath(multipartFile,"/data_nfs/nfs/sass/updateFile/").replaceAll("\\\\", "/");
    }
    @RequestMapping("/readFile")
    @ResponseBody
    public String readFile(@RequestParam("file") MultipartFile multipartFile) {
        try {

            Map map1 = new HashMap();
            map1.put("项目编号","projectCode");
            map1.put("数据范围","dataRange");
            map1.put("申请理由","applyReason");
            map1.put("期限说明材料","deadlineMaterials");
            map1.put("借阅期限","borrowDeadline");
            map1.put("借阅数据","borrowData");
            String fileName = FileUploadUtil.uploadToBasePath(multipartFile, "D:\\file\\").replaceAll("\\\\", "/");
            List<Map> result_read = CSVUtil.readFileToMap("D:\\file\\"+fileName,CSVUtil.initCsvConfig());
            List<Map> result = new ArrayList<>();
            for (int i = 0; i < result_read.size(); i++) {
                Map map_read = result_read.get(i);
                Map map = new HashMap();
                for (Object obj : map_read.keySet()){
                    map.put(map1.get(obj.toString()),map_read.get(obj));
                }
                result.add(map);
            }
            return new ResultMsg<>().setCode(ResultState.SUCCESS).setMsg("文件读取成功").setData(result).toJSON();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMsg<String>().setCode(ResultState.ERROR).setMsg("文件读取失败").toJSON();
        }
//        return FileUploadUtil.uploadToBasePath(multipartFile,"/data_nfs/nfs/sass/updateFile/").replaceAll("\\\\", "/");
    }

}
