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.common.DeviceConstant;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import com.zt.plat.module.qms.resource.device.service.DeviceProductService;
import com.zt.plat.module.qms.resource.material.service.MaterialProductService;
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.DevicePeriodCheckDO;
import com.zt.plat.module.qms.resource.device.service.DevicePeriodCheckService;

@Tag(name = "管理后台 - 设备-期间核查")
@RestController
@RequestMapping("/qms/resource/device-period-check")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.deviceperiodcheck")
public class DevicePeriodCheckController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource private DevicePeriodCheckService devicePeriodCheckService;
    @Resource private DeviceProductService deviceProductService;
    @Resource private MaterialProductService materialProductService;
    @Resource private BusinessFileService businessFileService;

    @PostMapping("/create")
    @Operation(summary = "创建设备-期间核查")
    public CommonResult<DevicePeriodCheckRespVO> createDevicePeriodCheck(@Valid @RequestBody DevicePeriodCheckSaveReqVO createReqVO) {
        return success(devicePeriodCheckService.createDevicePeriodCheck(createReqVO));
    }

    @PostMapping("/createByDeviceId")
    @Operation(summary = "创建期间核查-设备")
    public CommonResult<DevicePeriodCheckRespVO> createByDeviceId(@RequestBody DevicePeriodCheckSaveReqVO createReqVO) {
        return success(devicePeriodCheckService.createByDeviceId(createReqVO));
    }

    @PostMapping("/createByMaterialId")
    @Operation(summary = "创建期间核查-物料试剂")
    public CommonResult<DevicePeriodCheckRespVO> createByMaterialId(@RequestBody DevicePeriodCheckSaveReqVO createReqVO) {
        return success(devicePeriodCheckService.createByMaterialId(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备-期间核查")
    public CommonResult<DevicePeriodCheckRespVO> updateDevicePeriodCheck(@Valid @RequestBody DevicePeriodCheckSaveReqVO updateReqVO) {
        DevicePeriodCheckDO entity = devicePeriodCheckService.updateDevicePeriodCheck(updateReqVO);
        DevicePeriodCheckRespVO vo = BeanUtils.toBean(entity, DevicePeriodCheckRespVO.class);
        return success(vo);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备-期间核查")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteDevicePeriodCheck(@RequestParam("id") Long id) {
        devicePeriodCheckService.deleteDevicePeriodCheck(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除设备-期间核查")
    @PreAuthorize("@ss.hasPermission('qms:device-period-check:delete')")
    public CommonResult<Boolean> deleteDevicePeriodCheckList(@RequestBody BatchDeleteReqVO req) {
        devicePeriodCheckService.deleteDevicePeriodCheckListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备-期间核查")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DevicePeriodCheckRespVO> getDevicePeriodCheck(@RequestParam("id") Long id) {
        DevicePeriodCheckDO entity = devicePeriodCheckService.getDevicePeriodCheck(id);
        DevicePeriodCheckRespVO vo = BeanUtils.toBean(entity, DevicePeriodCheckRespVO.class);
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return success(vo);
    }

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

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

    @RequestMapping("/submitApply")
    @Operation(summary = "提交申请")
    public CommonResult<DevicePeriodCheckRespVO> submitApply(@RequestBody DevicePeriodCheckSaveReqVO param) {
        return devicePeriodCheckService.submitApply(param);
    }
    
    @GetMapping("/pageDevice")
    @Operation(summary = "获得设备-期间核查分页")
    public CommonResult<PageResult<DevicePeriodCheckVO>> pageDevice(@Valid DevicePeriodCheckPageReqVO param) {
        Page<DevicePeriodCheckPageReqVO> 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("");
        }
        param.setCheckTarget(DeviceConstant.PERIOD_CHECK_TAGET_DEVICE);
        IPage<DevicePeriodCheckVO> pageList = devicePeriodCheckService.queryPageListDevice(page, param);
        PageResult<DevicePeriodCheckVO> pageResult = new PageResult<>(pageList.getRecords(), pageList.getTotal());
        return CommonResult.success(pageResult);
    }

    @GetMapping("/pageMaterial")
    @Operation(summary = "获得设备-期间核查分页")
    public CommonResult<PageResult<DevicePeriodCheckVO>> pageMaterial(@Valid DevicePeriodCheckPageReqVO param) {
        Page<DevicePeriodCheckPageReqVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        Long productId = param.getProductId();
        if(!ObjectUtils.isEmpty(productId)){
            List<Long> productIdList = materialProductService.getIdListByIdPath(productId);
            param.setProductIdList(productIdList);
            param.setProductId(null);
        }
        String flowStatus = param.getFlowStatus();
        if (!ObjectUtils.isEmpty(flowStatus)) {
            param.setFlowStatusList(Arrays.asList(flowStatus.split(",")));
            param.setFlowStatus("");
        }
        param.setCheckTarget(DeviceConstant.PERIOD_CHECK_TAGET_MATERIAL);
        IPage<DevicePeriodCheckVO> pageList = devicePeriodCheckService.queryPageListMaterial(page, param);
        PageResult<DevicePeriodCheckVO> pageResult = new PageResult<>(pageList.getRecords(), pageList.getTotal());
        return CommonResult.success(pageResult);
    }

    @GetMapping("/getLastDataDevice")
    @Operation(summary = "获取指定设备最新期间核查数据")
    public CommonResult<DevicePeriodCheckVO> getLastDataDevice(@Valid DevicePeriodCheckPageReqVO 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);
        param.put("checkTarget", DeviceConstant.PERIOD_CHECK_TAGET_DEVICE);
        return CommonResult.success(devicePeriodCheckService.getLastDataDevice( param));
    }

    @GetMapping("/getLastDataMaterial")
    @Operation(summary = "获取指定物料最新期间核查数据")
    public CommonResult<DevicePeriodCheckVO> getLastDataMaterial(@Valid DevicePeriodCheckPageReqVO 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);
        param.put("checkTarget", DeviceConstant.PERIOD_CHECK_TAGET_MATERIAL);
        return CommonResult.success(devicePeriodCheckService.getLastDataMaterial( param));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备-期间核查 Excel")
    @PreAuthorize("@ss.hasPermission('qms:device-period-check:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDevicePeriodCheckExcel(@Valid DevicePeriodCheckPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DevicePeriodCheckDO> list = devicePeriodCheckService.getDevicePeriodCheckPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备-期间核查.xls", "数据", DevicePeriodCheckRespVO.class, BeanUtils.toBean(list, DevicePeriodCheckRespVO.class));
    }

}