package com.zksy.web.controller.gasbasic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zksy.base.domain.EquipmentBase;
import com.zksy.base.domain.EquipmentPointRel;
import com.zksy.base.domain.EquipmentStatus;
import com.zksy.base.domain.GasPipePoint;
import com.zksy.base.domain.GasPipePointDeviceRel;
import com.zksy.base.domain.vo.EquipmentFullVO;
import com.zksy.base.service.GasEquipmentService;
import com.zksy.base.mapper.EquipmentPointRelMapper;
import com.zksy.base.mapper.EquipmentStatusMapper;
import com.zksy.base.mapper.GasPipePointDeviceRelMapper;
import com.zksy.base.mapper.GasPipePointMapper;
import com.zksy.common.annotation.Anonymous;
import com.zksy.common.annotation.Log;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.enums.BusinessType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/equipment")
@Api(tags = "监测设备管理")
public class GasEquipmentController {

    @Autowired
    private GasEquipmentService gasEquipmentService;

    @Autowired
    private GasPipePointDeviceRelMapper gasPipePointDeviceRelMapper;

    @Autowired
    private EquipmentStatusMapper equipmentStatusMapper;

    @Autowired
    private GasPipePointMapper gasPipePointMapper;

    @Autowired
    private EquipmentPointRelMapper equipmentPointRelMapper;

    @GetMapping("/status/{equipmentId}")
    @ApiOperation("获取设备实时运行状态")
    @Anonymous
    public AjaxResult getEquipmentStatus(@PathVariable String equipmentId) {
        LambdaQueryWrapper<EquipmentStatus> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentStatus::getEquipmentId, equipmentId);
        EquipmentStatus status = equipmentStatusMapper.selectOne(wrapper);
        return status != null ? AjaxResult.success(status) : AjaxResult.error("设备状态信息不存在");
    }

    @GetMapping("/abnormal")
    @ApiOperation("异常设备列表（关联报警统计）")
    @Anonymous
    public AjaxResult getAbnormalList() {
        LambdaQueryWrapper<EquipmentStatus> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentStatus::getAlarmStatus, 1);
        List<EquipmentStatus> list = equipmentStatusMapper.selectList(wrapper);
        return AjaxResult.success(list);
    }

    @GetMapping("/point-rel/{equipmentId}")
    @ApiOperation("获取设备关联的测点")
    @Anonymous
    public AjaxResult getPointRelByEquipment(@PathVariable String equipmentId) {
        LambdaQueryWrapper<EquipmentPointRel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentPointRel::getEquipmentId, equipmentId);
        List<EquipmentPointRel> list = equipmentPointRelMapper.selectList(wrapper);
        return AjaxResult.success(list);
    }

    @PostMapping("/point-rel/save")
    @ApiOperation("新增设备测点关联")
    @Anonymous
    public AjaxResult savePointRel(@RequestBody EquipmentPointRel rel) {
        boolean saved = equipmentPointRelMapper.insert(rel) > 0;
        return saved ? AjaxResult.success("关联成功") : AjaxResult.error("关联失败");
    }

    @DeleteMapping("/point-rel/delete")
    @ApiOperation("删除设备测点关联")
    @Anonymous
    public AjaxResult deletePointRel(@RequestParam String relId) {
        boolean deleted = equipmentPointRelMapper.deleteById(relId) > 0;
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @GetMapping("/point-rel/by-point/{pointId}")
    @ApiOperation("获取管点关联的设备")
    @Anonymous
    public AjaxResult getPointRelByPoint(@PathVariable String pointId) {
        LambdaQueryWrapper<EquipmentPointRel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EquipmentPointRel::getPointId, pointId);
        List<EquipmentPointRel> list = equipmentPointRelMapper.selectList(wrapper);
        return AjaxResult.success(list);
    }

    @PostMapping("/point-rel/save-batch")
    @ApiOperation("批量关联设备到管点")
    @Anonymous
    public AjaxResult savePointRelBatch(@RequestBody List<EquipmentPointRel> relList) {
        if (relList == null || relList.isEmpty()) {
            return AjaxResult.error("关联列表不能为空");
        }
        for (EquipmentPointRel rel : relList) {
            equipmentPointRelMapper.insert(rel);
        }
        return AjaxResult.success("批量关联成功");
    }

    @PostMapping("/device-rel/save")
    @ApiOperation("更新设备管点关联（删旧插新）")
    @Anonymous
    public AjaxResult saveDeviceRel(@RequestBody GasPipePointDeviceRel rel) {
        LambdaQueryWrapper<GasPipePointDeviceRel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GasPipePointDeviceRel::getEquipmentId, rel.getEquipmentId());
        gasPipePointDeviceRelMapper.delete(wrapper);
        gasPipePointDeviceRelMapper.insert(rel);
        return AjaxResult.success("关联成功");
    }

    @PostMapping("/save")
    @ApiOperation("新增燃气设备(含管网关联)")
    @Log(title = "新增燃气设备", businessType = BusinessType.INSERT)
    public AjaxResult save(@RequestBody EquipmentBase entity,
                           @RequestParam(required = false) String networkId,
                           @RequestParam(required = false) Long pointId) {
        boolean saved = gasEquipmentService.saveWithCheck(entity);
        if (!saved) return AjaxResult.error("新增失败");
        saveDeviceRel(entity.getEquipmentId(), networkId, pointId);
        return AjaxResult.success("新增成功", entity.getEquipmentId());
    }

    @PutMapping("/updateById")
    @ApiOperation("修改燃气设备(含管网关联)")
    @Log(title = "修改燃气设备", businessType = BusinessType.UPDATE)
    public AjaxResult updateById(@RequestBody EquipmentBase entity,
                                  @RequestParam(required = false) String networkId,
                                  @RequestParam(required = false) Long pointId) {
        boolean updated = gasEquipmentService.updateWithCheck(entity);
        if (!updated) return AjaxResult.error("修改失败");
        saveDeviceRel(entity.getEquipmentId(), networkId, pointId);
        return AjaxResult.success("修改成功");
    }

    private void saveDeviceRel(String equipmentId, String networkId, Long pointId) {
        // 优先用 pointId；否则通过 networkId 找管点
        Long pid = pointId;
        if (pid == null && networkId != null && !networkId.isEmpty()) {
            List<GasPipePoint> points = gasPipePointMapper.selectList(
                    new LambdaQueryWrapper<GasPipePoint>().eq(GasPipePoint::getNetworkId, networkId));
            if (!points.isEmpty()) pid = points.get(0).getPointId();
        }
        if (pid == null) return;
        LambdaQueryWrapper<GasPipePointDeviceRel> w = new LambdaQueryWrapper<>();
        w.eq(GasPipePointDeviceRel::getEquipmentId, equipmentId);
        gasPipePointDeviceRelMapper.delete(w);
        GasPipePointDeviceRel rel = new GasPipePointDeviceRel();
        rel.setEquipmentId(equipmentId);
        rel.setPointId(pid);
        gasPipePointDeviceRelMapper.insert(rel);
    }

    @DeleteMapping("/deleteById")
    @ApiOperation("删除燃气设备")
    @Log(title = "删除燃气设备", businessType = BusinessType.DELETE)
    public AjaxResult deleteById(@RequestParam String id) {
        boolean deleted = gasEquipmentService.removeWithCheck(id);
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @GetMapping("/findFullByPage")
    @ApiOperation("设备全信息分页查询（联查管点→管线→状态）")
    @Anonymous
    public AjaxResult findFullByPage(@RequestParam(defaultValue = "1") Long pageNum,
                                     @RequestParam(defaultValue = "10") Long pageSize,
                                     @RequestParam(required = false) String equipmentCode,
                                     @RequestParam(required = false) String equipmentName,
                                     @RequestParam(required = false) String equipmentModel,
                                     @RequestParam(required = false) String manufacturer,
                                     @RequestParam(required = false) String district) {
        Page<EquipmentFullVO> page = gasEquipmentService.findFullByPage(pageNum, pageSize,
                equipmentCode, equipmentName, equipmentModel, manufacturer, district);
        return AjaxResult.success(page);
    }
}
