package com.njcn.gather.device.controller;

import cn.hutool.core.util.StrUtil;
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.common.utils.LogUtil;
import com.njcn.gather.device.pojo.dto.DataCheckResDTO;
import com.njcn.gather.device.pojo.param.PqDevParam;
import com.njcn.gather.device.pojo.vo.PqDevVO;
import com.njcn.gather.device.service.IPqDevService;
import com.njcn.gather.type.service.IDevTypeService;
import com.njcn.web.controller.BaseController;
import com.njcn.web.utils.FileUtil;
import com.njcn.web.utils.HttpResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * @author caozehui
 * @date 2024/11/06
 */
@Slf4j
@Api(tags = "被检设备")
@RestController
@RequestMapping("/pqDev")
@RequiredArgsConstructor
public class PqDevController extends BaseController {

    private final IPqDevService pqDevService;
    private final IDevTypeService devTypeService;

    @OperateInfo
    @PostMapping("/list")
    @ApiOperation("分页查询被检设备")
    @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true)
    public HttpResult<Page<PqDevVO>> list(@RequestBody @Validated PqDevParam.QueryParam queryParam) {
        String methodDescribe = getMethodDescribe("list");
        LogUtil.njcnDebug(log, "{}，查询数据为：{}", methodDescribe, queryParam);
        Page<PqDevVO> result = pqDevService.listPqDevs(queryParam);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo
    @GetMapping("/getById")
    @ApiOperation("根据id查询被检设备")
    @ApiImplicitParam(name = "id", value = "被检设备id", required = true)
    public HttpResult<PqDevVO> getById(@RequestParam("id") String id) {
        String methodDescribe = getMethodDescribe("getById");
        LogUtil.njcnDebug(log, "{}，查询ID为：{}", methodDescribe, id);
        PqDevVO result = pqDevService.getPqDevById(id);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo(operateType = OperateType.ADD)
    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("新增被检设备")
    @ApiImplicitParam(name = "pqDevParam", value = "被检设备", required = true)
    public HttpResult<Boolean> add(@ModelAttribute @Validated PqDevParam pqDevParam) {
        String methodDescribe = getMethodDescribe("add");
        LogUtil.njcnDebug(log, "{}，新增数据为：{}", methodDescribe, pqDevParam);
        boolean result = pqDevService.addPqDev(pqDevParam);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    @OperateInfo(operateType = OperateType.UPDATE)
    @PostMapping(value = "/update", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("修改被检设备")
    @ApiImplicitParam(name = "updateParam", value = "被检设备", required = true)
    public HttpResult<Boolean> update(@ModelAttribute @Validated PqDevParam.UpdateParam updateParam) {
        String methodDescribe = getMethodDescribe("update");
        LogUtil.njcnDebug(log, "{}，修改数据为：{}", methodDescribe, updateParam);
        boolean result = pqDevService.updatePqDev(updateParam);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DOWNLOAD)
    @GetMapping("/image/preview")
    @ApiOperation("下载设备图片")
    @ApiImplicitParam(name = "id", value = "被检设备id", required = true)
    public void previewImage(@RequestParam("id") String id,
                             @RequestParam("fileName") String fileName,
                             HttpServletResponse response) {
        pqDevService.previewImage(id, fileName, response);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DOWNLOAD)
    @GetMapping("/image/download")
    @ApiOperation("download device image")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true),
            @ApiImplicitParam(name = "fileName", value = "fileName", required = true)
    })
    public void downloadImage(@RequestParam("id") String id,
                              @RequestParam("fileName") String fileName,
                              HttpServletResponse response) {
        pqDevService.downloadImage(id, fileName, response);
    }

    @OperateInfo(operateType = OperateType.DELETE)
    @PostMapping("/delete")
    @ApiOperation("删除被检设备")
    @ApiImplicitParam(name = "param", value = "删除参数", required = true)
    public HttpResult<Boolean> delete(@RequestBody @Validated PqDevParam.DeleteParam param) {
        String methodDescribe = getMethodDescribe("delete");
        LogUtil.njcnDebug(log, "{}，删除ID数据为：{}", methodDescribe, String.join(StrUtil.COMMA, param.getIds()));
        boolean result = pqDevService.deletePqDev(param);
        if (result) {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, true, methodDescribe);
        } else {
            return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.FAIL, false, methodDescribe);
        }
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DOWNLOAD)
    @PostMapping("/export")
    @ApiOperation("批量导出被检设备")
    @ApiImplicitParam(name = "queryParam", value = "查询参数", required = true)
    public void exportDev(@RequestBody @Validated PqDevParam.QueryParam queryParam) {
        String methodDescribe = getMethodDescribe("exportDev");
        LogUtil.njcnDebug(log, "{}，查询数据为：{}", methodDescribe, queryParam);
        pqDevService.exportDev(queryParam);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.DOWNLOAD)
    @PostMapping("/downloadTemplate")
    @ApiOperation("下载被检设备导入文件模板")
    public void downloadTemplate(@RequestBody PqDevParam pqDevParam) {
        pqDevService.downloadTemplate(pqDevParam.getPattern());
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON, operateType = OperateType.UPLOAD)
    @PostMapping(value = "/import")
    @ApiOperation("批量导入被检设备")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "被检设备数据文件", required = true),
            @ApiImplicitParam(name = "patternId", value = "模式id", required = true)
    })
    public HttpResult importDev(@RequestParam("file") MultipartFile file, @RequestParam("patternId") String patternId, @RequestParam("planId") String planId, @RequestParam(value = "cover", defaultValue = "0") Integer cover, HttpServletResponse response) {
        String methodDescribe = getMethodDescribe("importDev");
        LogUtil.njcnDebug(log, "{}，上传文件为：{}", methodDescribe, file.getOriginalFilename());
        boolean fileType = FileUtil.judgeFileIsExcel(file.getOriginalFilename());
        if (!fileType) {
            throw new BusinessException(CommonResponseEnum.FILE_XLSX_ERROR);
        }
        if ("null".equals(planId)) {
            planId = null;
        }
        return pqDevService.importDev(file, patternId, planId, response, cover);
    }

    @OperateInfo(info = LogEnum.BUSINESS_COMMON)
    @GetMapping("/listUnbound")
    @ApiOperation("获取指定模式下所有未绑定的设备")
    @ApiImplicitParam(name = "pattern", value = "模式id", required = true)
    public HttpResult<List<Map<String, Object>>> listUnbound(@RequestParam("pattern") String pattern) {
        String methodDescribe = getMethodDescribe("listUnbound");
        LogUtil.njcnDebug(log, "{}，查询数据为：{}", methodDescribe, pattern);
        List<Map<String, Object>> result = pqDevService.listUnbound(pattern);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo
    @GetMapping("/getSelectOptions")
    @ApiOperation("从历史数据中查询下拉框选项")
    @ApiImplicitParam(name = "pattern", value = "模式id", required = true)
    public HttpResult<Map<String, List<String>>> getSelectOptions(@RequestParam("pattern") String pattern) {
        String methodDescribe = getMethodDescribe("getSelectOptions");
        Map<String, List<String>> result = pqDevService.listSelectOptions(pattern);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, result, methodDescribe);
    }

    @OperateInfo
    @GetMapping("/getDataCheckRes")
    @ApiOperation("获取接入测试-数据校验结果")
    @ApiImplicitParam(name = "monitorId", value = "监测点id", required = true)
    public HttpResult<DataCheckResDTO> getDataCheckRes(@RequestParam("monitorId") String monitorId) {
        String methodDescribe = getMethodDescribe("getDataCheckRes");
        DataCheckResDTO dataCheckRes = pqDevService.getDataCheckRes(monitorId);
        return HttpResultUtil.assembleCommonResponseResult(CommonResponseEnum.SUCCESS, dataCheckRes, methodDescribe);
    }

}
