package com.huatek.busi.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.huatek.busi.common.util.FileUtils;
import com.huatek.busi.entity.GlobalSettingItem;
import com.huatek.busi.entity.LabReportParamData;
import com.huatek.busi.service.IGlobalSettingItemService;
import com.huatek.busi.service.ILabReportBasisDataService;
import com.huatek.busi.service.IRModelService;
import com.huatek.busi.service.ISysFileService;
import com.huatek.busi.vo.DeviceSubclassOrTestItemListVo;
import com.huatek.busi.where.LabReportBasisDataSelectVo;
import com.huatek.busi.where.LabReportBasisDataStatisticsWhereVo;
import com.huatek.busi.where.LabReportParamDataSelectVo;
import com.huatek.busi.where.SysFileSelectVo;
import com.huatek.torch.frame.tools.ConstantUtil;
import com.huatek.torch.frame.tools.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Api(tags = {"离线实验报告基础数据管理接口"})
@RestController
@RequestMapping("/api/labReportBasisData")
public class LabReportBasisDataController {

    @Reference(check = false)
    ILabReportBasisDataService labReportBasisDataService;

    @Reference(check = false)
    IRModelService rModelService;

    @Reference(check = false)
    ISysFileService sysFileService;

    @Reference(check = false)
    IGlobalSettingItemService globalSettingItemService;


    @ApiOperation(value = "离线试验报告基础数据列表", httpMethod = "POST", notes = "离线实验报告基础数据列表", produces = "application/json;charset=utf-8", response = Map.class)
    @PostMapping(value = "/list", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> list(@RequestBody LabReportBasisDataSelectVo labReportBasisDataSelectVo) {
        return labReportBasisDataService.list(labReportBasisDataSelectVo);
    }

    @ApiOperation(value = "根据离线报告搜索条件查询excel列表", httpMethod = "POST", notes = "根据离线报告搜索条件查询excel列表", produces = "application/json;charset=utf-8", response = Map.class)
    @PostMapping(value = "/findFileList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> findExcelList(@RequestBody LabReportBasisDataSelectVo labReportBasisDataSelectVo) {
        return labReportBasisDataService.findExcelList(labReportBasisDataSelectVo);
    }

    @ApiOperation(value = "查看离线试验报告基础数据列表", httpMethod = "POST", notes = "查看离线试验报告基础数据列表", produces = "application/json;charset=utf-8", response = Map.class)
    @PostMapping(value = "/findAll", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> findAll(@RequestBody LabReportParamDataSelectVo labReportParamDataSelectVo) {
        return labReportBasisDataService.findAll(labReportParamDataSelectVo);
    }

    @ApiOperation(value = "统计离线报告数据", httpMethod = "POST", notes = "统计离线报告数据", produces = "application/json;charset=utf-8", response = Map.class)
    @PostMapping(value = "/statistics", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> statistics(@RequestBody LabReportBasisDataStatisticsWhereVo labReportBasisDataStatisticsVo) {
        return labReportBasisDataService.statistics(labReportBasisDataStatisticsVo);
    }

    @ApiOperation("下载excel模板并写入数据")
    @GetMapping(value = "/downloadExcel")
    public Map<String, Object> downloadExcel(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        String pathName, path;
        String equType = params.get("equType").toString();
        switch (equType) {
            case "1":
                pathName = "transformer.xlsx";
                path = "/template/" + pathName;
                break;
            case "2":
                pathName = "gis.xlsx";
                path = "/template/" + pathName;
                break;
            default:
                throw new IllegalStateException("设备类型异常: " + equType);
        }
        File file = sysFileService.downloadExcel(path, equType, pathName);
        if (file != null) {
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", FileUtils.fileDownload(file, pathName, response));
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "", null);
    }

    @ApiOperation(value = "导入离线实验报告基础数据模板", httpMethod = "POST", notes = "导入离线实验报告基础数据模板", produces = "application/json;charset=utf-8", response = Map.class)
    @PostMapping("/import")
    public Map<String, Object> importFile(@RequestParam("file") MultipartFile file,
                                          @RequestParam("files") MultipartFile[] files,
                                          @RequestHeader("token") String token,
                                          @RequestParam("eqType") String eqType,
                                          @RequestParam("equipmentId") String equipmentId,
                                          @RequestParam("jgId") String jgId) throws IOException {
        GlobalSettingItem globalSettingItem = globalSettingItemService.findOne();
        if (globalSettingItem == null || (globalSettingItem.getFileUploadNumber() == null && globalSettingItem.getFileUploadNumber() <= 0)) {
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.UPLOAD.ANNEX.NUM", "");
        }
        // 上传附件数量
        Integer fileUploadNumber = globalSettingItem.getFileUploadNumber();
        List<Map<String, String>> fileList = new ArrayList<>();
        if (file != null && files.length >= fileUploadNumber.intValue()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < files.length; i++) {
                Map<String, String> fileMap = new HashMap<>();
                // 上传文件名称
                String getOriginalFilename = files[i].getOriginalFilename();
                // 文件字节数组
                byte[] bytes = files[i].getBytes();
                String encoded = Base64.getEncoder().encodeToString(bytes);
                stringBuilder.append(getOriginalFilename + "-" + encoded).append(",");

                fileMap.put("filename", getOriginalFilename);
                fileMap.put("byte", encoded);
                fileList.add(fileMap);
            }

            if (stringBuilder.length() > 0) {
                // 导入文件名称
                String fileName = file.getOriginalFilename();
                // 附件文件
                String enclosure = stringBuilder.substring(0, stringBuilder.length() - 1);
                // 上传根目录
                String rootPath = globalSettingItem.getRootPath();
                return labReportBasisDataService.importFile(file.getBytes(), token, eqType, fileName, enclosure, fileList, rootPath, equipmentId, jgId);
            } else {
                return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.IMPORT.FAIL", "");
            }
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.UPLOAD.ANNEX.NUM.NOTMATCH", "");
    }

    @ApiOperation(value = "导入离线报告模板", httpMethod = "POST", notes = "导入离线报告模板", produces = "application/json;charset=utf-8", response = Map.class)
    @PostMapping("/importModel")
    public Map<String, Object> importModel(@RequestParam("file") MultipartFile file,
                                           @RequestHeader("token") String token,
                                           @RequestParam("eqType") String eqType) throws IOException {
        GlobalSettingItem globalSettingItem = globalSettingItemService.findOne();
        if (globalSettingItem == null || (globalSettingItem.getFileUploadNumber() == null && globalSettingItem.getFileUploadNumber() <= 0)) {
            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.UPLOAD.ANNEX.NUM", "");
        }
        // 上传附件数量
        if (file != null) {
            // 导入文件名称
            String fileName = file.getOriginalFilename();
            // 上传根目录
            String rootPath = globalSettingItem.getRootPath();
            return labReportBasisDataService.importModel(file.getBytes(), token, eqType, fileName, rootPath);
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.UPLOAD.ANNEX.NUM.NOTMATCH", "");
    }

//    @ApiOperation(value = "故障仿真xml上传", produces = "application/json;charset=utf-8")
//    @PostMapping("/importSimulate")
//    public Map<String, Object> importSimulate(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, InvalidFormatException {
//
//        try {
//            FTPUtil.sshSftp(bytes,fileName);
//            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.UPLOAD.ANNEX.NUM.NOTMATCH", "");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "失败", "");
//        }
//
//    }

    @ApiOperation(value = "查询模板列表", httpMethod = "POST", notes = "查询文件列表", produces = "application/json;charset=utf-8", response = Map.class)
    @PostMapping(value = "/modelList", produces = {"application/json;charset=utf-8"})
    public Map<String, Object> modelList(@RequestBody SysFileSelectVo sysFileSelectVo) {
        return rModelService.modelList(sysFileSelectVo);
    }

    @ApiOperation("模板下载")
    @GetMapping("/downloadModels")
    public Map<String, Object> downloadModels(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        String id = params.get("id").toString();
        Map<String, Object> map = rModelService.downloadModels(id);
        if (CollUtil.isNotEmpty(map)) {
            if (map.get("filePath") == null && map.get("fileName") == null) {
                return map;
            }
            String filePath = map.get("filePath").toString();
            String fileName = map.get("fileName").toString();
            String path = FileUtils.fileDownload(new File(filePath), fileName, response);
            if (Objects.equals(path, "文件下载失败，未找到您要下载的文件") || Objects.equals(path, "文件下载失败,未知错误")) {
                return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.FILE.DOWNLOAD.FAIL", "");
            }
            return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "BUSINESS.FILE.DOWNLOAD.SUCCESS", path);
        }
        return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "BUSINESS.FILE.DOWNLOAD.FAIL", "");
    }

    @ApiOperation("删除模板记录")
    @PostMapping("/deleteModels")
    public Map<String, Object> deleteModels(@RequestParam("ids") List<String> ids, @RequestParam("equType") String equType) {
        return rModelService.deleteModels(ids, equType);
    }

    @ApiOperation("获取设备小类列表")
    @GetMapping("/deviceSubclassList/{equType}")
    public Map<String, Object> deviceSubclassList(@PathVariable String equType) {
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS,null,labReportBasisDataService.deviceSubclassList(equType));
    }

    @ApiOperation("获取试验项目列表")
    @GetMapping("/testItemList/{equType}")
    public Map<String, Object> testItemList(@PathVariable String equType) {
        return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS,null,labReportBasisDataService.testItemList(equType));
    }
}
