package com.zt.plat.module.qms.resource.device.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zt.plat.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.enums.QmsCommonConstant;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import com.zt.plat.module.qms.resource.device.service.DeviceCalibrationPlanService;
import com.zt.plat.module.qms.resource.device.service.DeviceProductService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import com.zt.plat.framework.business.interceptor.BusinessControllerMarker;
import com.zt.plat.framework.business.annotation.FileUploadController;
import com.zt.plat.framework.business.controller.AbstractFileUploadController;

import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import com.zt.plat.framework.common.pojo.vo.BatchDeleteReqVO;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.datapermission.core.annotation.DeptDataPermissionIgnore;

import static com.zt.plat.framework.common.pojo.CommonResult.success;

import com.zt.plat.framework.excel.core.util.ExcelUtils;

import com.zt.plat.framework.apilog.core.annotation.ApiAccessLog;
import static com.zt.plat.framework.apilog.core.enums.OperateTypeEnum.*;

import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceCalibrationDO;
import com.zt.plat.module.qms.resource.device.service.DeviceCalibrationService;

@Tag(name = "管理后台 - 设备-检定校准")
@RestController
@RequestMapping("/qms/resource/device-calibration")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.devicecalibration")
public class DeviceCalibrationController extends AbstractFileUploadController implements BusinessControllerMarker{

    static {
        FileUploadController annotation = DeviceCalibrationController.class.getAnnotation(FileUploadController.class);
        if (annotation != null) {
        setFileUploadInfo(annotation);
        }
    }

    @Resource private DeviceCalibrationService deviceCalibrationService;
    @Resource private DeviceProductService deviceProductService;
    @Resource private BusinessFileService businessFileService;

    @PostMapping("/create")
    @Operation(summary = "创建设备-检定校准")
    public CommonResult<DeviceCalibrationRespVO> createDeviceCalibration(@Valid @RequestBody DeviceCalibrationSaveReqVO createReqVO) {
        return success(deviceCalibrationService.createDeviceCalibration(createReqVO));
    }

    @PostMapping("/createByDeviceId")
    @Operation(summary = "创建检定校准")
    public CommonResult<DeviceCalibrationRespVO> createByDeviceId(@RequestBody DeviceCalibrationSaveReqVO createReqVO) {
        return success(deviceCalibrationService.createByDeviceId(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备-检定校准")
    public CommonResult<DeviceCalibrationRespVO> updateDeviceCalibration(@Valid @RequestBody DeviceCalibrationSaveReqVO updateReqVO) {
        DeviceCalibrationDO entity = deviceCalibrationService.updateDeviceCalibration(updateReqVO);
        DeviceCalibrationRespVO vo = BeanUtils.toBean(entity, DeviceCalibrationRespVO.class);
        return success(vo);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备-检定校准")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteDeviceCalibration(@RequestParam("id") Long id) {
        deviceCalibrationService.deleteDeviceCalibration(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除设备-检定校准")
                @PreAuthorize("@ss.hasPermission('qms:device-calibration:delete')")
    public CommonResult<Boolean> deleteDeviceCalibrationList(@RequestBody BatchDeleteReqVO req) {
        deviceCalibrationService.deleteDeviceCalibrationListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备-检定校准")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DeviceCalibrationRespVO> getDeviceCalibration(@RequestParam("id") Long id) {
        DeviceCalibrationDO deviceCalibration = deviceCalibrationService.getDeviceCalibration(id);
        DeviceCalibrationRespVO vo = BeanUtils.toBean(deviceCalibration, DeviceCalibrationRespVO.class);
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return success(vo);
    }

    @GetMapping("/getVO")
    @Operation(summary = "获得设备-检定校准")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DeviceCalibrationVO> getVO(@RequestParam("id") Long id) {
        DeviceCalibrationVO vo = deviceCalibrationService.getDeviceCalibrationVO(id);
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return success(vo);
    }

    @GetMapping("/getLastData")
    @Operation(summary = "获得设备-检定校准")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DeviceCalibrationVO> getLastData(@Valid DeviceCalibrationPageReqVO vo) {
        Long deviceId = vo.getDeviceId();
        if(ObjectUtils.isEmpty(deviceId)){
            return CommonResult.error(0, "缺少参数");
        }
        JSONObject param = new JSONObject();
        param.put("deviceId", deviceId);
        param.put("flowStatus", QmsCommonConstant.COMPLETED);
        return CommonResult.success(deviceCalibrationService.getLastData( param));
    }

    @RequestMapping("/submitApply")
    @Operation(summary = "提交申请")
    public CommonResult<DeviceCalibrationRespVO> submitApply(@RequestBody DeviceCalibrationSaveReqVO param) {
        return deviceCalibrationService.submitApply(param);
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备-检定校准分页")
    public CommonResult<PageResult<DeviceCalibrationVO>> getDeviceCalibrationPage(@Valid DeviceCalibrationPageReqVO param) {

        Page<DeviceCalibrationPageReqVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        Long productId = param.getProductId();
        if(!ObjectUtils.isEmpty(productId)){
            List<Long> productIdList = deviceProductService.getIdListByIdPath(productId);
            param.setProductIdList(productIdList);
            param.setProductId(null);
        }
        String flowStatus = param.getFlowStatus();
        if (!ObjectUtils.isEmpty(flowStatus)) {
            param.setFlowStatusList(Arrays.asList(flowStatus.split(",")));
            param.setFlowStatus("");
        }
        IPage<DeviceCalibrationVO> pageList = deviceCalibrationService.queryPageList(page, param);
        PageResult pageResult = new PageResult<>(pageList.getRecords(), pageList.getTotal());
        return CommonResult.success(pageResult);

//        PageResult<DeviceCalibrationDO> pageResult = deviceCalibrationService.getDeviceCalibrationPage(pageReqVO);
//        return success(BeanUtils.toBean(pageResult, DeviceCalibrationRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备-检定校准 Excel")
    @PreAuthorize("@ss.hasPermission('qms:device-calibration:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceCalibrationExcel(@Valid DeviceCalibrationPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DeviceCalibrationDO> list = deviceCalibrationService.getDeviceCalibrationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备-检定校准.xls", "数据", DeviceCalibrationRespVO.class,
                        BeanUtils.toBean(list, DeviceCalibrationRespVO.class));
    }

}