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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.plat.framework.security.core.LoginUser;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import com.zt.plat.module.qms.resource.device.dal.mapper.DeviceUseRecordMapper;
import com.zt.plat.module.qms.resource.device.service.DeviceInfomationService;
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 static com.zt.plat.module.qms.enums.ErrorCodeConstants.DEVICE_USE_RECORD_NOT_EXISTS;

import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceUseRecordDO;
import com.zt.plat.module.qms.resource.device.service.DeviceUseRecordService;

@Tag(name = "管理后台 - 设备-使用记录")
@RestController
@RequestMapping("/qms/resource/device-use-record")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.deviceuserecord")
public class DeviceUseRecordController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource private DeviceUseRecordService deviceUseRecordService;
    @Resource private DeviceInfomationService deviceInfomationService;
    @Resource private DeviceUseRecordMapper deviceUseRecordMapper;

    @GetMapping("/queryPageListWithCount")
    @Operation(summary = "使用记录分页列表查询（以设备为主数据）")
    public CommonResult<PageResult<DeviceInfomationUseRecordVO>> queryPageListWithCount(@Valid DeviceUseRecordPageReqVO pageReqVO) {
        PageResult<DeviceInfomationUseRecordVO> pageResult = deviceUseRecordService.queryPageListWithCount(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/queryLastUsingData")
    @Operation(summary = "查询设备最近一次使用中的记录")
    @Parameter(name = "deviceId", description = "设备ID", required = true, example = "1024")
    public CommonResult<DeviceUseRecordRespVO> queryLastUsingData(@RequestParam("deviceId") Long deviceId) {
        if(deviceId == null)
            return CommonResult.error(DEVICE_USE_RECORD_NOT_EXISTS.getCode(), "设备ID不能为空");
        LambdaQueryWrapper<DeviceUseRecordDO> query = new LambdaQueryWrapper<>();
        query.eq(DeviceUseRecordDO::getDeviceId, deviceId);
        query.isNull(DeviceUseRecordDO::getUseTimeEnd);
        query.orderByDesc(DeviceUseRecordDO::getUseTimeStart);
        query.last("LIMIT 1");
        DeviceUseRecordDO recordDO = deviceUseRecordMapper.selectOne( query);
        return success(BeanUtils.toBean(recordDO, DeviceUseRecordRespVO.class));
    }

    @PostMapping("/create")
    @Operation(summary = "创建设备-使用记录")
    public CommonResult<DeviceUseRecordRespVO> createDeviceUseRecord(@Valid @RequestBody DeviceUseRecordSaveReqVO reqVO) {
        Long deviceId = reqVO.getDeviceId();
        if(deviceId == null)
            return CommonResult.error(DEVICE_USE_RECORD_NOT_EXISTS.getCode(), "设备ID不能为空");
        //检查设备状态
        CommonResult<Boolean> checkResult = deviceInfomationService.checkDeviceUsable(deviceId);
        if(!checkResult.isSuccess())
            return CommonResult.error(checkResult);
        return deviceUseRecordService.createDeviceUseRecord(reqVO);
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备-使用记录")
//    @PreAuthorize("@ss.hasPermission('qms:device-use-record:update')")
    public CommonResult<Boolean> updateDeviceUseRecord(@Valid @RequestBody DeviceUseRecordSaveReqVO reqVO) {
        Long deviceId = reqVO.getDeviceId();
        if(deviceId == null)
            return CommonResult.error(DEVICE_USE_RECORD_NOT_EXISTS.getCode(), "设备ID不能为空");
        deviceUseRecordService.updateDeviceUseRecord(reqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备-使用记录")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('qms:device-use-record:delete')")
    public CommonResult<Boolean> deleteDeviceUseRecord(@RequestParam("id") Long id) {
        deviceUseRecordService.deleteDeviceUseRecord(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除设备-使用记录")
                @PreAuthorize("@ss.hasPermission('qms:device-use-record:delete')")
    public CommonResult<Boolean> deleteDeviceUseRecordList(@RequestBody BatchDeleteReqVO req) {
        deviceUseRecordService.deleteDeviceUseRecordListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备-使用记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('qms:device-use-record:query')")
    public CommonResult<DeviceUseRecordRespVO> getDeviceUseRecord(@RequestParam("id") Long id) {
        DeviceUseRecordDO deviceUseRecord = deviceUseRecordService.getDeviceUseRecord(id);
        return success(BeanUtils.toBean(deviceUseRecord, DeviceUseRecordRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备-使用记录分页")
    public CommonResult<PageResult<DeviceUseRecordRespVO>> getDeviceUseRecordPage(@Valid DeviceUseRecordPageReqVO pageReqVO) {
        PageResult<DeviceUseRecordDO> pageResult = deviceUseRecordService.getDeviceUseRecordPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DeviceUseRecordRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备-使用记录 Excel")
    @PreAuthorize("@ss.hasPermission('qms:device-use-record:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceUseRecordExcel(@Valid DeviceUseRecordPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DeviceUseRecordDO> list = deviceUseRecordService.getDeviceUseRecordPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备-使用记录.xls", "数据", DeviceUseRecordRespVO.class,
                        BeanUtils.toBean(list, DeviceUseRecordRespVO.class));
    }

}