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

import com.alibaba.fastjson.JSONObject;
import com.zt.plat.module.qms.common.service.BusinessFileService;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
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.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
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_MAINTAIN_NOT_EXISTS;

import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceMaintainDO;
import com.zt.plat.module.qms.resource.device.service.DeviceMaintainService;

@Tag(name = "管理后台 - 设备-点检、保养记录")
@RestController
@RequestMapping("/qms/resource/device-maintain")
@Validated
@DeptDataPermissionIgnore(enable = "true")
@FileUploadController(source = "qms.devicemaintain")
public class DeviceMaintainController extends AbstractFileUploadController implements BusinessControllerMarker{

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

    @Resource private DeviceMaintainService deviceMaintainService;
    @Resource private DeviceInfomationService deviceInfomationService;
    @Resource private BusinessFileService businessFileService;

    @PostMapping("/saveMaintainVo")
    @Operation(summary = "创建或获取维护数据")
    public CommonResult<DeviceMaintainRespVO> saveMaintainVo(@RequestBody DeviceMaintainVO vo) {
        CommonResult<DeviceMaintainDO> ret =  deviceMaintainService.saveMaintainVo(vo);
        if(!ret.isSuccess())
            return ret.error(ret.getCode(), ret.getMsg());
        DeviceMaintainDO entity = ret.getData();
        return success(BeanUtils.toBean(entity, DeviceMaintainRespVO.class));
    }

    @PostMapping("/createOrGet")
    @Operation(summary = "创建或获取维护数据")
    public CommonResult<DeviceMaintainVO> createOrGet(@RequestBody JSONObject jsonObject) {
        Long deviceId = jsonObject.getLong("deviceId");
        String dataType = jsonObject.getString("dataType");
        String dateStr = jsonObject.getString("date");
        if (deviceId == null || dataType == null) {
            return CommonResult.error(DEVICE_MAINTAIN_NOT_EXISTS.getCode(), "参数错误");
        }
        //检查设备状态
        CommonResult<Boolean> checkResult = deviceInfomationService.checkDeviceUsable(deviceId);
        if(!checkResult.isSuccess()){
            return checkResult.error(checkResult.getCode(), checkResult.getMsg());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(ObjectUtils.isEmpty(dateStr))
            dateStr = sdf.format(new Date());
        return deviceMaintainService.createOrGet(deviceId, dateStr, dataType);
    }


    @GetMapping("/getMaintainDetail")
    @Operation(summary = "查询维护记录详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DeviceMaintainVO> getMaintainDetail(@RequestParam("id") Long id) {
        CommonResult<DeviceMaintainVO> ret = deviceMaintainService.getMaintainDetail(id);
        DeviceMaintainVO vo = ret.getData();
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return CommonResult.success(vo);
    }

    @GetMapping("/queryPageListWithCount")
    @Operation(summary = "维护-分页列表查询（以设备为主数据）")
    public CommonResult<PageResult<DeviceInfomationMaintainVO>> queryPageListWithCount(@Valid DeviceMaintainPageReqVO pageReqVO) {
        PageResult<DeviceInfomationMaintainVO> pageResult = deviceMaintainService.queryPageListWithCount(pageReqVO);
        return success(pageResult);
    }

    @PostMapping("/create")
    @Operation(summary = "创建设备-点检、保养记录")
//    @PreAuthorize("@ss.hasPermission('qms:device-maintain:create')")
    public CommonResult<DeviceMaintainVO> createDeviceMaintain(@RequestBody JSONObject jsonObject) {
        Long deviceId = jsonObject.getLong("deviceId");
        String dataType = jsonObject.getString("dataType");
        String dateStr = jsonObject.getString("date");
        if (deviceId == null || dataType == null) {
            return CommonResult.error(DEVICE_MAINTAIN_NOT_EXISTS.getCode(), "参数错误");
        }
        //检查设备状态
        CommonResult<Boolean> checkResult = deviceInfomationService.checkDeviceUsable(deviceId);
        if(!checkResult.isSuccess()){
            return checkResult.error(checkResult.getCode(), checkResult.getMsg());
        }
        LocalDateTime dateTime = LocalDate.now().atStartOfDay();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if(ObjectUtils.isEmpty(dateStr))
            dateTime = LocalDateTime.parse(dateStr, formatter);
        return deviceMaintainService.create(deviceId, dateTime, dataType);
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备-点检、保养记录")
//    @PreAuthorize("@ss.hasPermission('qms:device-maintain:update')")
    public CommonResult<Boolean> updateDeviceMaintain(@Valid @RequestBody DeviceMaintainSaveReqVO updateReqVO) {
        deviceMaintainService.updateDeviceMaintain(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备-点检、保养记录")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('qms:device-maintain:delete')")
    public CommonResult<Boolean> deleteDeviceMaintain(@RequestParam("id") Long id) {
        deviceMaintainService.deleteDeviceMaintain(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除设备-点检、保养记录")
    @PreAuthorize("@ss.hasPermission('qms:device-maintain:delete')")
    public CommonResult<Boolean> deleteDeviceMaintainList(@RequestBody BatchDeleteReqVO req) {
        deviceMaintainService.deleteDeviceMaintainListByIds(req.getIds());
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备-点检、保养记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<DeviceMaintainRespVO> getDeviceMaintain(@RequestParam("id") Long id) {
        DeviceMaintainDO deviceMaintain = deviceMaintainService.getDeviceMaintain(id);
        DeviceMaintainRespVO vo = BeanUtils.toBean(deviceMaintain, DeviceMaintainRespVO.class);
        vo.setBusinessFileRet(businessFileService.getBusinessFileList(id));
        return success(vo);
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备-点检、保养记录分页")
//    @PreAuthorize("@ss.hasPermission('qms:device-maintain:query')")
    public CommonResult<PageResult<DeviceMaintainRespVO>> getDeviceMaintainPage(@Valid DeviceMaintainPageReqVO pageReqVO) {
        PageResult<DeviceMaintainDO> pageResult = deviceMaintainService.getDeviceMaintainPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DeviceMaintainRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备-点检、保养记录 Excel")
    @PreAuthorize("@ss.hasPermission('qms:device-maintain:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDeviceMaintainExcel(@Valid DeviceMaintainPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DeviceMaintainDO> list = deviceMaintainService.getDeviceMaintainPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "设备-点检、保养记录.xls", "数据", DeviceMaintainRespVO.class,
                        BeanUtils.toBean(list, DeviceMaintainRespVO.class));
    }

}