<!-- 列表选择器 -->
<template>
  <table-select
    :text="text"
    :select-config="selectConfig"
    @confirm-click="handleConfirm"
    @clear-click="handleClearSelection"
  >
    <template #status="scope">
      <el-tag :type="scope.row[scope.prop] === '1' ? 'success' : 'danger'">
        {{ scope.row[scope.prop] === "1" ? "启用" : "停用" }}
      </el-tag>
    </template>
  </table-select>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from "vue";
import type { ISelectConfig } from "@/components/TableSelect/index.vue";
import GatewayAPI from "@/api/module_business/gateway";

// 父组件双向绑定的值（选中网关ID）
const props = defineProps<{ modelValue?: number }>();

// 事件向上派发，支持父组件监听和 v-model（仅回传选中网关ID）
const emit = defineEmits<{
  confirmClick: [data: IGateway[]];
  "update:modelValue": [val: number | undefined];
}>();

const selectConfig: ISelectConfig = {
  pk: "id",
  width: "167.5px", // 与搜索表单其他输入宽度一致
  placeholder: "请选择网关",
  popover: {
    width: 720, // 弹出层宽度，提升可用性（约 720px）
  },
  formItems: [
    {
      type: "select",
      label: "状态",
      prop: "status",
      initialValue: "1",
      attrs: {
        placeholder: "全部",
        clearable: true,
        style: {
          width: "140px",
        },
      },
      options: [
        { label: "启用", value: "1" },
        { label: "停用", value: "0" },
      ],
    },
  ],
  indexAction(params) {
    // 映射查询参数到后端接口
    const query: any = { ...params };
    // 清理空字符串/空值，避免后端 422
    Object.keys(query).forEach((k) => {
      const v = query[k];
      if (v === "" || v === null || v === undefined) {
        delete query[k];
      }
    });
    // 规范化状态为布尔值
    if (typeof query.status === "string") {
      if (query.status === "true") query.status = true;
      else if (query.status === "false") query.status = false;
    }
    // 请求用户分页列表并适配 TableSelect 需要的结构
    return GatewayAPI.listGateway(query).then((res: any) => {
      return {
        total: res.data.data.total,
        list: res.data.data.items,
      };
    });
  },
  tableColumns: [
    { type: "selection", width: 50, align: "center" },
    { label: "网关名称", align: "center", prop: "gateway_name" },
    { label: "网关IP", align: "center", prop: "gateway_ipaddress" },
    { label: "行车", align: "center", prop: "crane_name" },
    {
      label: "状态",
      align: "center",
      prop: "status",
      templet: "custom",
      slotName: "status",
    },
  ],
};

interface IGateway {
  id: number;
  gateway_name: string;
  gateway_ipaddress: string;
  crane_name:string;
  status?: string;
}
const selectedGateway = ref<IGateway>();

// 核心：使用详情接口查询行车信息
const getGatewayDetail = async (id: number) => {
  try {
    // 调用专属详情接口 detailBizCrane
    const res = await GatewayAPI.detailGateway(id);
    // 严格校验核心字段，避免接口返回异常数据
    if (res.data.status_code === 200 && res.data.data && res.data.data.id) {
      selectedGateway.value = res.data.data;
    } else {
      selectedGateway.value = undefined;
    }
  } catch (error) {
    selectedGateway.value = undefined;
  }
};

function handleConfirm(data: IGateway[]) {
  selectedGateway.value = data[0];
  const id = selectedGateway.value?.id;
  emit("update:modelValue", id);
  emit("confirmClick", data);
}

function handleClearSelection() {
  selectedGateway.value = undefined;
  emit("update:modelValue", undefined);
}

// 监听modelValue变化：有值则查询详情回显，无值则清空
watch(
  () => props.modelValue,
  async (val) => {
    if (val !== undefined && val !== null && val > 0) {
      await getGatewayDetail(val); // 有有效ID则查询详情
    } else {
      selectedGateway.value = undefined; // 无ID则清空
    }
  },
  { immediate: true } // 初始化时立即执行
);

// 组件挂载时兜底查询，确保编辑页初始化回显
onMounted(async () => {
  const { modelValue } = props;
  if (modelValue !== undefined && modelValue !== null && modelValue > 0) {
    await getGatewayDetail(modelValue);
  }
});

const text = computed(() => {
  return selectedGateway.value 
    ? `${selectedGateway.value.gateway_name}` 
    : "";
});
</script>