package com.zksy.web.controller.manhole;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.base.alarm.domain.WarningThreshold;
import com.zksy.base.alarm.service.WarningThresholdService;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.EquipmentStatus;
import com.zksy.base.domain.EquipmentType;
import com.zksy.base.manhole.domain.ManholeData;
import com.zksy.base.manhole.service.ManholeDataService;
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.common.utils.poi.ExcelUtil;
import com.zksy.manhole.dto.in.*;
import com.zksy.manhole.dto.out.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 窨井盖监测系统-监测设备信息管理Controller
 * 
 * @author xianggx
 * @date 2026-05-06
 */
@RestController
@RequestMapping("/manhole/device")
@Api(tags = "窨井盖监测系统-监测设备信息管理")
public class ManholeDeviceController extends BaseController
{
    @Autowired
    private EquipmentBaseService equipmentBaseService;

    @Autowired
    private EquipmentStatusService equipmentStatusService;

    @Autowired
    private EquipmentTypeService equipmentTypeService;

    @Autowired
    private ManholeDataService manholeDataService;

    @Autowired
    private WarningThresholdService warningThresholdService;

    /**
     * 分页查询监测设备台账列表
     */
    @Anonymous
    @PostMapping(value = "/findByPage")
    @ApiOperation(value = "分页查询监测设备台账列表")
    public AjaxResult2<Page<EquipmentBaseOutDTO>> findByPage(@RequestBody ManholeDevicePageInDTO pageInDTO)
    {
        return AjaxResult2.success(equipmentBaseService.findManholeDeviceByPage(pageInDTO));
    }

    /**
     * 查询井盖监测设备列表
     */
    @Anonymous
    @PostMapping(value = "/getManholeDataList")
    @ApiOperation(value = "查询井盖监测设备列表")
    public AjaxResult2<List<EquipmentBaseOutDTO>> getManholeDataList(@RequestBody ManholeDeviceListInDTO listInDTO)
    {
        return AjaxResult2.success(equipmentBaseService.getManholeDataList(listInDTO));
    }

    /**
     * 获取监测设备台账详情
     */
    @Anonymous
    @GetMapping(value = "/getById/{id}")
    @ApiOperation(value = "获取监测设备台账详情")
    public AjaxResult2<EquipmentBaseOutDTO> getById(@PathVariable("id") String id)
    {
        EquipmentBase equipmentBase = equipmentBaseService.getById(id);
        if(equipmentBase == null){
            return AjaxResult2.error("设备ID不存在");
        }
        EquipmentBaseOutDTO outDTO = BeanUtil.copyProperties(equipmentBase, EquipmentBaseOutDTO.class);
        // 查询设备状态
        EquipmentStatus equipmentStatus = equipmentStatusService.lambdaQuery()
                .eq(EquipmentStatus::getEquipmentId, outDTO.getEquipmentId())
                .one();
        if(equipmentStatus != null){
            EquipmentStatusOutDTO equipmentStatusOutDTO = BeanUtil.copyProperties(equipmentStatus, EquipmentStatusOutDTO.class);
            outDTO.setEquipmentStatus(equipmentStatusOutDTO);
        }
        // 查询设备类别名称
        EquipmentType equipmentType = equipmentTypeService.getById(outDTO.getEquipmentTypeId());
        if(equipmentType != null){
            outDTO.setEquipmentTypeName(equipmentType.getTypeName());
        }
        // 查询设备监测状态
        List<ManholeData> manholeDataList = manholeDataService.list(new LambdaQueryWrapper<ManholeData>()
                .eq(ManholeData::getImeiCardNumber, outDTO.getEquipmentCode())
                .orderByDesc(ManholeData::getCreateTime));
        if(CollUtil.isNotEmpty(manholeDataList)){
            ManholeData manholeData = manholeDataList.get(0);
            ManholeDataOutDTO manholeDataOutDTO = BeanUtil.copyProperties(manholeData, ManholeDataOutDTO.class);
            outDTO.setManholeData(manholeDataOutDTO);
        }
        // 查询设备预警阈值（支持多个设备编号，用逗号分隔）
        List<WarningThreshold> warningThresholdList = warningThresholdService.list(new LambdaQueryWrapper<WarningThreshold>()
                .apply("CONCAT(',', device_code, ',') LIKE CONCAT('%,', {0}, ',%')", outDTO.getEquipmentCode())
                .orderByDesc(WarningThreshold::getCreateTime));
        if(CollUtil.isNotEmpty(warningThresholdList)){
            List<WarningThresholdOutDTO> warningThresholdOutDTOList = BeanUtil.copyToList(warningThresholdList, WarningThresholdOutDTO.class);
            outDTO.setWarningThresholdList(warningThresholdOutDTOList);
        }
        return AjaxResult2.success(outDTO);
    }

    /**
     * 修改设备状态
     * @param inDTO
     * @return
     */
    @Anonymous
    @PostMapping("/updateDeviceStatus")
    @ApiOperation(value = "修改设备状态")
    public AjaxResult updateDeviceStatus(@RequestBody EquipmentStatusInDTO inDTO) {
        boolean updated = equipmentStatusService.updateDeviceStatus(inDTO);
        return updated ? AjaxResult.success("修改成功",updated)
                : AjaxResult.error("修改失败",updated);
    }

    /**
     * 保存设备预警阈值
     * @param inDTO
     * @return
     */
    @Anonymous
    @PostMapping("/saveWarningThreshold")
    @ApiOperation(value = "保存设备预警阈值")
    public AjaxResult saveWarningThreshold(@RequestBody WarningThresholdInDTO inDTO) {
        WarningThreshold warningThreshold = BeanUtil.copyProperties(inDTO, WarningThreshold.class);
        if(StringUtils.isNotEmpty(warningThreshold.getId())){
            warningThreshold.setUpdateTime(LocalDateTime.now());
        }
        boolean result = warningThresholdService.saveOrUpdate(warningThreshold);
        return result ? AjaxResult.success("保存成功",result)
                : AjaxResult.error("保存失败",result);
    }

    /**
     * 根据设备类别分组统计设备数量
     */
    @Anonymous
    @PostMapping(value = "/countByType")
    @ApiOperation(value = "根据设备类别分组统计设备数量")
    public AjaxResult2<List<EquipmentCountByTypeOutDTO>> countByType(@RequestBody EquipmentCountByTypeInDTO inDTO)
    {
        return AjaxResult2.success(equipmentBaseService.countByType(inDTO));
    }

    /**
     * 导出设备明细数据
     */
    @Anonymous
    @PostMapping(value = "/export")
    @ApiOperation(value = "导出设备明细数据")
    public void export(HttpServletResponse response, @RequestBody EquipmentExportInDTO inDTO)
    {
        List<EquipmentExportOutDTO> list = equipmentBaseService.exportEquipmentDetail(inDTO);
        ExcelUtil<EquipmentExportOutDTO> util = new ExcelUtil<>(EquipmentExportOutDTO.class);
        util.exportExcel(response, list, "设备明细数据");
    }
}
