package com.zksy.web.controller.manhole;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.base.domain.CaseInfo;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.EquipmentStatus;
import com.zksy.base.domain.EquipmentType;
import com.zksy.base.service.CaseInfoService;
import com.zksy.base.service.EquipmentBaseService;
import com.zksy.base.service.EquipmentStatusService;
import com.zksy.base.service.EquipmentTypeService;
import com.zksy.common.annotation.Anonymous;
import com.zksy.common.core.controller.BaseController;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.core.domain.AjaxResult2;
import com.zksy.manhole.dto.in.CaseInfoPageInDTO;
import com.zksy.manhole.dto.in.CaseInfoSaveInDTO;
import com.zksy.manhole.dto.in.CaseInfoVerifyInDTO;
import com.zksy.manhole.dto.out.CaseInfoOutDTO;
import com.zksy.manhole.dto.out.EquipmentStatusOutDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Random;

/**
 * 窨井盖监测系统-案件流转管理Controller
 * 
 * @author xianggx
 * @date 2026-05-06
 */
@RestController
@RequestMapping("/manhole/caseInfo")
@Api(tags = "窨井盖监测系统-案件流转管理")
public class CaseInfoController extends BaseController
{
    @Autowired
    private CaseInfoService caseInfoService;

    @Autowired
    private EquipmentBaseService equipmentBaseService;

    @Autowired
    private EquipmentStatusService equipmentStatusService;

    @Autowired
    private EquipmentTypeService equipmentTypeService;

    /**
     * 生成案件编号
     * @return
     */
    public static String generateCaseNo() {
        // 1. 获取当前时间，格式化为14位年月日时分秒
        String currentDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 2. 生成4位随机数，不足补0
        String randomNum = String.format("%04d", new Random().nextInt(10000));
        // 3. 拼接完整编号
        return "CS" + currentDateTime + randomNum;
    }

    /**
     * 分页查询案件信息列表
     */
    @Anonymous
    @PostMapping(value = "/findByPage")
    @ApiOperation(value = "分页查询案件信息列表")
    public AjaxResult2<Page<CaseInfoOutDTO>> findByPage(@RequestBody CaseInfoPageInDTO pageInDTO)
    {
        return AjaxResult2.success(caseInfoService.findByPage(pageInDTO));
    }

    /**
     * 获取案件信息详情
     */
    @Anonymous
    @GetMapping(value = "/getById/{id}")
    @ApiOperation(value = "获取案件信息详情")
    public AjaxResult2<CaseInfoOutDTO> getById(@PathVariable("id") Long id)
    {
        CaseInfo caseInfo = caseInfoService.getById(id);
        if(caseInfo == null){
            return AjaxResult2.error("案件ID不存在");
        }
        CaseInfoOutDTO outDTO = BeanUtil.copyProperties(caseInfo, CaseInfoOutDTO.class);
        // 查询设备状态
        EquipmentStatus equipmentStatus = equipmentStatusService.lambdaQuery()
                .eq(EquipmentStatus::getEquipmentId, outDTO.getDeviceId())
                .one();
        if(equipmentStatus != null){
            EquipmentStatusOutDTO equipmentStatusOutDTO = BeanUtil.copyProperties(equipmentStatus, EquipmentStatusOutDTO.class);
            outDTO.setEquipmentStatus(equipmentStatusOutDTO);
        }
        // 查询设备类别名称
        EquipmentBase equipmentBase = equipmentBaseService.getById(outDTO.getDeviceId());
        if(equipmentBase != null){
            outDTO.setDeviceCode(equipmentBase.getEquipmentCode());
            EquipmentType equipmentType = equipmentTypeService.getById(equipmentBase.getEquipmentTypeId());
            if(equipmentType != null){
                outDTO.setEquipmentTypeName(equipmentType.getTypeName());
            }
        }
        return AjaxResult2.success(outDTO);
    }

    /**
     * 核查案件信息
     * @param inDTO
     * @return
     */
    @Anonymous
    @PostMapping("/verifyCaseInfo")
    @ApiOperation(value = "核查案件信息")
    public AjaxResult verifyCaseInfo(@RequestBody CaseInfoVerifyInDTO inDTO) {
        CaseInfo caseInfo = caseInfoService.getById(inDTO.getCaseId());
        if(caseInfo == null){
            return AjaxResult.error("案件ID不存在");
        }
        CaseInfo entity = new CaseInfo();
        entity.setCaseId(inDTO.getCaseId());
        entity.setVerifyUser(inDTO.getVerifyUser());
        entity.setVerifyTime(new Date());
        if(inDTO.getVerifyResult() != null){
            if(inDTO.getVerifyResult() == 1){
                //1-待处理
                entity.setCaseStatus(2);
            } if(inDTO.getVerifyResult() == 2){
                //2-误报
                entity.setCaseStatus(4);
            }
        }
        boolean updated = caseInfoService.updateById(entity);
        return updated ? AjaxResult.success("操作成功",updated)
                : AjaxResult.error("操作失败",updated);
    }

    /**
     * 新增案件信息
     * @param inDTO
     * @return
     */
    @Anonymous
    @PostMapping("/saveCaseInfo")
    @ApiOperation(value = "新增案件信息")
    public AjaxResult saveWarningThreshold(@RequestBody CaseInfoSaveInDTO inDTO) {
        CaseInfo caseInfo = BeanUtil.copyProperties(inDTO, CaseInfo.class);
        caseInfo.setCaseNo(generateCaseNo());
        caseInfo.setCaseSource(4);
        caseInfo.setCaseStatus(1);
        boolean result = caseInfoService.save(caseInfo);
        return result ? AjaxResult.success("保存成功",result)
                : AjaxResult.error("保存失败",result);
    }
}
