package com.zksy.web.controller.drainage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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 com.zksy.drainage.domain.PipeNetworkInfo;
import com.zksy.drainage.service.PipeNetworkInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 排水管网基础数据管理
 */
@Slf4j
@RestController
@RequestMapping("/api/drainage/pipeNetwork")
@Api(tags = "排水管网基础数据管理")
public class PipeNetworkInfoController {

    @Autowired
    private PipeNetworkInfoService service;

    @Anonymous
    @GetMapping("/page")
    @ApiOperation(value = "排水管网分页查询")
    public Page<PipeNetworkInfo> page(
            @ApiParam("页码") @RequestParam(defaultValue = "1") long pageNum,
            @ApiParam("每页数量") @RequestParam(defaultValue = "10") long pageSize,
            @ApiParam("管网名称") @RequestParam(required = false) String name,
            @ApiParam("行政区域") @RequestParam(required = false) String area,
            @ApiParam("管网类型") @RequestParam(required = false) String networkType) {
        return service.findByPage(pageNum, pageSize, name, area, networkType);
    }

    /**
     * 查询所有已被关联的设备ID列表
     * 返回 Map: { equipmentId -> 关联的管网名称 }
     * 可选excludeId参数排除某个管网自己的关联
     */
    @Anonymous
    @GetMapping("/boundEquipmentIds")
    @ApiOperation(value = "查询所有已关联的设备ID")
    public AjaxResult boundEquipmentIds(
            @ApiParam("排除的管网ID") @RequestParam(required = false) String excludeId) {
        List<PipeNetworkInfo> all = service.list();
        Map<String, String> boundMap = new java.util.HashMap<>();
        for (PipeNetworkInfo p : all) {
            if (p.getEquipmentId() != null && !p.getEquipmentId().isEmpty()) {
                // 排除当前管网自己的关联
                if (excludeId != null && p.getId().equals(excludeId)) continue;
                String[] ids = p.getEquipmentId().split(",");
                for (String id : ids) {
                    String trimId = id.trim();
                    if (!trimId.isEmpty()) {
                        boundMap.put(trimId, p.getName() != null ? p.getName() : "");
                    }
                }
            }
        }
        return AjaxResult.success(boundMap);
    }

    @Anonymous
    @GetMapping("/{id}")
    @ApiOperation(value = "查询排水管网详情")
    public AjaxResult getById(@PathVariable String id) {
        PipeNetworkInfo entity = service.getById(id);
        if (entity == null) {
            return AjaxResult.error("该排水管网不存在");
        }
        return AjaxResult.success(entity);
    }

    @Anonymous
    @GetMapping("/list")
    @ApiOperation(value = "查询所有排水管网")
    public AjaxResult list() {
        return AjaxResult.success(service.list());
    }

    @Anonymous
    @PostMapping
    @ApiOperation(value = "新增排水管网")
    @Log(title = "新增排水管网", businessType = BusinessType.INSERT)
    @Transactional
    public AjaxResult save(@RequestBody PipeNetworkInfo entity) {
        boolean saved = service.saveEntity(entity);
        return saved ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
    }

    @Anonymous
    @PutMapping
    @ApiOperation(value = "修改排水管网")
    @Log(title = "修改排水管网", businessType = BusinessType.UPDATE)
    @Transactional
    public AjaxResult update(@RequestBody PipeNetworkInfo entity) {
        boolean updated = service.updateEntity(entity);
        return updated ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }

    @Anonymous
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除排水管网")
    @Log(title = "删除排水管网", businessType = BusinessType.DELETE)
    @Transactional
    public AjaxResult deleteById(@PathVariable String id) {
        boolean deleted = service.removeEntity(id);
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    @Anonymous
    @DeleteMapping("/batch")
    @ApiOperation(value = "批量删除排水管网")
    @Log(title = "批量删除排水管网", businessType = BusinessType.DELETE)
    @Transactional
    public AjaxResult deleteBatch(@RequestBody List<String> ids) {
        boolean deleted = service.removeBatchEntity(ids);
        return deleted ? AjaxResult.success("批量删除成功") : AjaxResult.error("批量删除失败");
    }

    @Anonymous
    @PostMapping("/bindEquipment")
    @ApiOperation(value = "绑定设备到排水管网")
    public AjaxResult bindEquipment(@RequestBody Map<String, Object> params) {
        String partitionId = (String) params.get("partitionId");
        @SuppressWarnings("unchecked")
        List<String> equipmentIds = (List<String>) params.get("equipmentIds");
        if (partitionId == null || equipmentIds == null || equipmentIds.isEmpty()) {
            return AjaxResult.error("参数不完整");
        }
        boolean success = service.bindEquipment(partitionId, equipmentIds);
        return success ? AjaxResult.success() : AjaxResult.error("绑定失败");
    }
}
