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.DrainagePartition;
import com.zksy.drainage.service.DrainagePartitionService;
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/partition")
@Api(tags = "排水分区基础数据管理")
public class DrainagePartitionController {

    @Autowired
    private DrainagePartitionService service;

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

    /**
     * 查询所有已被关联的设备ID列表
     * 返回 Map: { equipmentId -> 关联的分区名称 }
     * 可选excludeId参数排除某个分区自己的关联
     */
    @Anonymous
    @GetMapping("/boundEquipmentIds")
    @ApiOperation(value = "查询所有已关联的设备ID")
    public AjaxResult boundEquipmentIds(
            @ApiParam("排除的分区ID") @RequestParam(required = false) String excludeId) {
        List<DrainagePartition> all = service.list();
        Map<String, String> boundMap = new java.util.HashMap<>();
        for (DrainagePartition 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) {
        DrainagePartition 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 DrainagePartition entity) {
        boolean saved = service.saveWithCheck(entity);
        return saved ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
    }

    @Anonymous
    @PutMapping
    @ApiOperation(value = "修改排水分区")
    @Log(title = "修改排水分区", businessType = BusinessType.UPDATE)
    @Transactional
    public AjaxResult update(@RequestBody DrainagePartition entity) {
        boolean updated = service.updateWithCheck(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.removeWithCheck(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.removeBatchWithCheck(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("绑定失败");
    }

}
