package com.zksy.web.controller.gasbasic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.EquipmentType;
import com.zksy.base.domain.GasPipePoint;
import com.zksy.base.domain.GasPipePointDeviceRel;
import com.zksy.base.dto.GasPipePointPageInDTO;
import com.zksy.base.mapper.EquipmentBaseMapper;
import com.zksy.base.mapper.EquipmentTypeMapper;
import com.zksy.base.mapper.GasPipePointDeviceRelMapper;
import com.zksy.base.service.GasPipePointService;
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;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/gas-pipe-point")
@Api(tags = "燃气管点管理")
public class GasPipePointController {

    @Autowired
    private GasPipePointService service;

    @Autowired
    private GasPipePointDeviceRelMapper deviceRelMapper;

    @Autowired
    private EquipmentBaseMapper equipmentBaseMapper;

    @Autowired
    private EquipmentTypeMapper equipmentTypeMapper;

    @GetMapping("/findByPage")
    @ApiOperation("管点分页查询")
    @Anonymous
    public AjaxResult findByPage(GasPipePointPageInDTO dto) {
        Page<GasPipePoint> page = service.queryByPage(dto);
        return AjaxResult.success(page);
    }

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

    @GetMapping("/list-by-network/{networkId}")
    @ApiOperation("按管线ID查询管点列表")
    @Anonymous
    public AjaxResult listByNetworkId(@PathVariable String networkId) {
        return AjaxResult.success(service.listByNetworkId(networkId));
    }

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

    @PostMapping("/save")
    @ApiOperation("新增管点")
    @Log(title = "新增燃气管点", businessType = BusinessType.INSERT)
    public AjaxResult save(@RequestBody GasPipePoint 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 GasPipePoint 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 Long id) {
        boolean deleted = service.removeWithCheck(id);
        return deleted ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    // ============ 管点-设备关联 ============

    @GetMapping("/device/list/{pointId}")
    @ApiOperation("获取管点关联的设备列表")
    @Anonymous
    public AjaxResult listDevices(@PathVariable Long pointId) {
        LambdaQueryWrapper<GasPipePointDeviceRel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GasPipePointDeviceRel::getPointId, pointId);
        wrapper.orderByDesc(GasPipePointDeviceRel::getCreateTime);
        List<GasPipePointDeviceRel> list = deviceRelMapper.selectList(wrapper);

        List<String> needFillIds = list.stream()
                .filter(r -> StrUtil.isBlank(r.getEquipmentName()) || StrUtil.isBlank(r.getEquipmentType()))
                .map(GasPipePointDeviceRel::getEquipmentId)
                .collect(Collectors.toList());

        if (CollUtil.isNotEmpty(needFillIds)) {
            List<EquipmentBase> equipList = equipmentBaseMapper.selectBatchIds(needFillIds);
            Map<String, EquipmentBase> equipMap = equipList.stream()
                    .collect(Collectors.toMap(EquipmentBase::getEquipmentId, e -> e, (a, b) -> a));

            List<String> typeIds = equipList.stream()
                    .map(EquipmentBase::getEquipmentTypeId)
                    .filter(StrUtil::isNotBlank)
                    .distinct()
                    .collect(Collectors.toList());
            Map<String, String> typeNameMap = CollUtil.isEmpty(typeIds) ? Map.of() :
                    equipmentTypeMapper.selectBatchIds(typeIds).stream()
                            .collect(Collectors.toMap(EquipmentType::getId, EquipmentType::getTypeName, (a, b) -> a));

            for (GasPipePointDeviceRel rel : list) {
                if (StrUtil.isBlank(rel.getEquipmentName()) || StrUtil.isBlank(rel.getEquipmentType())) {
                    EquipmentBase equip = equipMap.get(rel.getEquipmentId());
                    if (equip != null) {
                        if (StrUtil.isBlank(rel.getEquipmentName())) {
                            rel.setEquipmentName(equip.getEquipmentName());
                        }
                        if (StrUtil.isBlank(rel.getEquipmentType())) {
                            rel.setEquipmentType(typeNameMap.get(equip.getEquipmentTypeId()));
                        }
                    }
                }
            }
        }

        return AjaxResult.success(list);
    }

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

    @PostMapping("/device/save-batch")
    @ApiOperation("批量关联设备到管点")
    @Anonymous
    public AjaxResult saveDeviceRelBatch(@RequestBody List<GasPipePointDeviceRel> relList) {
        if (relList == null || relList.isEmpty()) {
            return AjaxResult.error("关联列表不能为空");
        }
        for (GasPipePointDeviceRel 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("删除失败");
    }
}
