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.ManholeBase;
import com.zksy.base.domain.ManholeDeviceRel;
import com.zksy.base.dto.ManholePageInDTO;
import com.zksy.base.mapper.ManholeDeviceRelMapper;
import com.zksy.base.service.ManholeBaseService;
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/manhole")
@Api(tags = "窨井管理")
public class GasManholeController {

    @Autowired
    private ManholeBaseService service;

    @Autowired
    private ManholeDeviceRelMapper deviceRelMapper;

    @GetMapping("/findByPage")
    @ApiOperation("窨井分页查询")
    @Anonymous
    public AjaxResult findByPage(ManholePageInDTO dto) {
        Page<ManholeBase> page = service.findByPage(dto);
        return AjaxResult.success(page);
    }

    @GetMapping("/getById/{id}")
    @ApiOperation("根据ID查询窨井")
    @Anonymous
    public AjaxResult getById(@PathVariable String id) {
        ManholeBase entity = service.getById(id);
        return entity != null ? AjaxResult.success(entity) : AjaxResult.error("窨井信息不存在");
    }

    @GetMapping("/options")
    @ApiOperation("窨井下拉选项")
    @Anonymous
    public AjaxResult options() {
        return AjaxResult.success(service.getOptions());
    }

    @GetMapping("/list")
    @ApiOperation("窨井列表（全量，用于地图展示）")
    @Anonymous
    public AjaxResult list() {
        return AjaxResult.success(service.list());
    }

    @PostMapping("/save")
    @ApiOperation("新增窨井")
    @Log(title = "新增窨井信息", businessType = BusinessType.INSERT)
    public AjaxResult save(@RequestBody ManholeBase entity) {
        boolean saved = service.saveWithCheck(entity);
        return saved ? AjaxResult.success("新增成功", saved) : AjaxResult.error("新增失败");
    }

    @PutMapping("/updateById")
    @ApiOperation("修改窨井")
    @Log(title = "修改窨井信息", businessType = BusinessType.UPDATE)
    public AjaxResult updateById(@RequestBody ManholeBase entity) {
        boolean updated = service.updateWithCheck(entity);
        return updated ? AjaxResult.success("修改成功", updated) : AjaxResult.error("修改失败");
    }

    @DeleteMapping("/deleteById")
    @ApiOperation("删除窨井")
    @Log(title = "删除窨井信息", businessType = BusinessType.DELETE)
    public AjaxResult deleteById(@RequestParam String id) {
        boolean deleted = service.removeById(id);
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    // ============ 窨井-设备关联 ============

    @GetMapping("/device/list/{manholeId}")
    @ApiOperation("获取窨井关联的设备列表")
    @Anonymous
    public AjaxResult listDevices(@PathVariable String manholeId) {
        LambdaQueryWrapper<ManholeDeviceRel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManholeDeviceRel::getManholeId, manholeId);
        wrapper.orderByDesc(ManholeDeviceRel::getCreateTime);
        List<ManholeDeviceRel> list = deviceRelMapper.selectList(wrapper);
        return AjaxResult.success(list);
    }

    @PostMapping("/device/save")
    @ApiOperation("关联设备到窨井")
    @Anonymous
    public AjaxResult saveDeviceRel(@RequestBody ManholeDeviceRel rel) {
        boolean saved = deviceRelMapper.insert(rel) > 0;
        return saved ? AjaxResult.success("关联成功") : AjaxResult.error("关联失败");
    }

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

    @DeleteMapping("/device/delete")
    @ApiOperation("删除窨井设备关联")
    @Anonymous
    public AjaxResult deleteDeviceRel(@RequestParam Long relId) {
        boolean deleted = deviceRelMapper.deleteById(relId) > 0;
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }
}
