package com.njcn.gather.aireport.testdevice.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.common.pojo.annotation.OperateInfo;
import com.njcn.common.pojo.constant.OperateType;
import com.njcn.common.pojo.enums.common.LogEnum;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;
import com.njcn.gather.aireport.common.storage.AiReportMinioStorageService;
import com.njcn.gather.aireport.testdevice.component.TestDeviceReportStorageService;
import com.njcn.gather.aireport.testdevice.pojo.param.TestDeviceParam;
import com.njcn.gather.aireport.testdevice.pojo.po.TestDevicePO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceImportResultVO;
import com.njcn.gather.aireport.testdevice.pojo.vo.TestDeviceVO;
import com.njcn.gather.aireport.testdevice.service.TestDeviceService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.List;

@Api(tags = "检测设备管理")
@RestController
@RequestMapping("/api/test-device")
@RequiredArgsConstructor
public class TestDeviceController extends BaseController {

    private final TestDeviceService testDeviceService;
    private final TestDeviceReportStorageService reportStorageService;

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("查询检测设备列表")
    @PostMapping("/list")
    public HttpResult<Page<TestDeviceVO>> list(@RequestBody(required = false) TestDeviceParam.QueryParam param) {
        String methodDescribe = getMethodDescribe("list");
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,
                testDeviceService.listTestDevices(param), methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
    @ApiOperation("新增检测设备")
    @PostMapping(value = "/add", consumes = {"multipart/form-data"})
    public HttpResult<Boolean> add(@RequestPart("request") @Validated TestDeviceParam.AddParam param,
                                   @RequestPart("reportFile") MultipartFile reportFile) {
        String methodDescribe = getMethodDescribe("add");
        boolean result = testDeviceService.addTestDevice(param, reportFile);
        return HttpResultUtil.assembleCommonResponseResult(result ? CommonResponseEnum.SUCCESS : CommonResponseEnum.FAIL,
                result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPDATE)
    @ApiOperation("编辑检测设备")
    @PostMapping(value = "/update", consumes = {"multipart/form-data"})
    public HttpResult<Boolean> update(@RequestPart("request") @Validated TestDeviceParam.UpdateParam param,
                                      @RequestPart(value = "reportFile", required = false) MultipartFile reportFile) {
        String methodDescribe = getMethodDescribe("update");
        boolean result = testDeviceService.updateTestDevice(param, reportFile);
        return HttpResultUtil.assembleCommonResponseResult(result ? CommonResponseEnum.SUCCESS : CommonResponseEnum.FAIL,
                result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DELETE)
    @ApiOperation("删除检测设备")
    @PostMapping("/delete")
    public HttpResult<Boolean> delete(@RequestBody List<String> ids) {
        String methodDescribe = getMethodDescribe("delete");
        boolean result = testDeviceService.deleteTestDevices(ids);
        return HttpResultUtil.assembleCommonResponseResult(result ? CommonResponseEnum.SUCCESS : CommonResponseEnum.FAIL,
                result, methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("查询检测设备详情")
    @ApiImplicitParam(name = "id", value = "检测设备ID", required = true)
    @GetMapping("/{id}")
    public HttpResult<TestDeviceVO> detail(@PathVariable("id") String id) {
        String methodDescribe = getMethodDescribe("detail");
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,
                testDeviceService.getTestDevice(id), methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("下载检测设备导入模板")
    @GetMapping("/template")
    public void template() {
        testDeviceService.downloadTemplate();
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.ADD)
    @ApiOperation("导入检测设备")
    @PostMapping(value = "/import", consumes = {"multipart/form-data"})
    public HttpResult<TestDeviceImportResultVO> importExcel(@RequestPart("file") MultipartFile file,
                                                            @RequestPart("reportZip") MultipartFile reportZip) {
        String methodDescribe = getMethodDescribe("importExcel");
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS,
                testDeviceService.importTestDevices(file, reportZip), methodDescribe);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("导出检测设备")
    @GetMapping("/export")
    public void export(@ModelAttribute TestDeviceParam.QueryParam param) {
        testDeviceService.exportTestDevices(param);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("下载检测设备校准报告")
    @ApiImplicitParam(name = "id", value = "检测设备ID", required = true)
    @GetMapping("/{id}/report")
    public ResponseEntity<InputStreamResource> report(@PathVariable("id") String id) {
        return buildReportResponse(id, false);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @ApiOperation("预览检测设备校准报告")
    @ApiImplicitParam(name = "id", value = "检测设备ID", required = true)
    @GetMapping("/{id}/report/preview")
    public ResponseEntity<InputStreamResource> previewReport(@PathVariable("id") String id) {
        return buildReportResponse(id, true);
    }

    private ResponseEntity<InputStreamResource> buildReportResponse(String id, boolean preview) {
        TestDevicePO device = testDeviceService.requireNormal(id);
        if (device == null || device.getValidityReport() == null || device.getValidityReport().trim().isEmpty()) {
            throw new BusinessException(CommonResponseEnum.FAIL, "校准报告文件不存在");
        }
        try {
            String fileName = reportStorageService.resolveDownloadFileName(device.getValidityReport());
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
            AiReportMinioStorageService.StoredObject storedObject = reportStorageService.getObject(device.getValidityReport());
            return ResponseEntity.ok()
                    .contentType(preview ? MediaType.APPLICATION_PDF : MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            (preview ? "inline" : "attachment") + "; filename*=UTF-8''" + encodedFileName)
                    .body(new InputStreamResource(storedObject.getInputStream()));
        } catch (Exception exception) {
            throw new BusinessException(CommonResponseEnum.FAIL, "读取校准报告失败");
        }
    }
}
