<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { useTraceOrderStore } from '@/store';
import type { ColumnsType } from 'ant-design-vue/es/table/interface';
import {
  getEquipmentByCode,
  listEquipmentEntry,
  addEquipmentEntry,
  delEquipmentEntry,
} from '@/api/traceOrderManage/equipment';

const traceOrderStore = useTraceOrderStore();

interface EquipmentTableItem {
  key: string;
  equipmentName: string;
  equipmentCode: string;
  [key: string]: any;
}

const equipmentColumns = [
  { title: '序号', dataIndex: 'index', key: 'index', align: 'center', width: 80 },
  { title: '设备编码', dataIndex: 'equipmentCode', key: 'equipmentCode', align: 'center' },
  { title: '设备名称', dataIndex: 'equipmentTitle', key: 'equipmentTitle', align: 'center' },
  { title: '操作', dataIndex: 'action', key: 'action', align: 'center' },
];

const equipmentInfo = reactive({
  equipmentTitle: '',
  equipmentCode: '',
});

const fetchEquipmentInfo = async () => {
  const { data } = await getEquipmentByCode(equipmentInput.value)
  if (!data) {
    message.error('设备不存在');
    return;
  }
  Object.assign(equipmentInfo, data);
}

// 治具表格
const equipmentTableData = ref<EquipmentTableItem[]>([]);

const equipmentInput = ref<string>('');

const handleBind = async () => {
  if (!equipmentInput.value) return;
  try {
    await addEquipmentEntry({
      equipmentCode: equipmentInput.value,
      stationCode: traceOrderStore.currentStationCode,
    });
    message.success('绑定成功');
    equipmentInput.value = '';
    fetchBoundEquipmentList();
  } catch (error: any) {
    message.error(`绑定失败: ${ error.message }`);
  }
}

const handleUnbind = async (id: number) => {
  try {
    await delEquipmentEntry(id);
    message.success('解绑成功');
    fetchBoundEquipmentList();
  } catch (error: any) {
    message.error(`解绑失败: ${ error.message }`);
  }
}

// 获取已绑定的设备列表
const loadingEquipmentTableData = ref(false);
const fetchBoundEquipmentList = async () => {
  const stationId = traceOrderStore.currentStationCode;
  if (!stationId) return;
  loadingEquipmentTableData.value = true;
  try {
    const { rows } = await listEquipmentEntry({ stationId });
    equipmentTableData.value = rows;
  } catch (error: any) {
    message.error(error.message || '查询治具列表失败');
  } finally {
    loadingEquipmentTableData.value = false;
  }
}

const handleRefresh = () => {
  fetchBoundEquipmentList();
  renderTableHeight();
}

// 计算表格高度
const customTable = ref<HTMLElement | null>(null)
const tableHeight = ref(200)
const renderTableHeight = () => {
  if (customTable.value) {
    tableHeight.value = customTable.value.clientHeight - 50
    console.log('元素高度：', tableHeight.value)
  }
}

onMounted(() => {
  renderTableHeight()
})

defineExpose({
  renderTableHeight
});

fetchBoundEquipmentList()
</script>

<template>
  <div class="equipment__container">
    <Title name="绑定设备列表" showRefresh @refresh="handleRefresh" />
    <a-row class="main-content" :gutter="24">
      <a-col :span="10" class="input__container">
        <a-row :gutter="12">
          <a-col :span="21">
            <a-input size="large" v-model:value="equipmentInput" @pressEnter="fetchEquipmentInfo" placeholder="按下回车搜索" />
          </a-col>
          <a-col :span="3">
            <a-button type="primary" size="large" @click="handleBind">绑定</a-button>
          </a-col>
        </a-row>
        <div class="description-wrapper">
          <a-descriptions :column="1" bordered>
            <a-descriptions-item label="设备编码">{{ equipmentInfo.equipmentCode }}</a-descriptions-item>
            <a-descriptions-item label="设备名称">{{ equipmentInfo.equipmentTitle }}</a-descriptions-item>
          </a-descriptions>
        </div>
      </a-col>
      <a-col :span="14">
        <div class="table-wrapper" ref="customTable">
          <a-table :dataSource="equipmentTableData" :columns="equipmentColumns as ColumnsType<EquipmentTableItem>"
            :pagination="false" bordered sticky :scroll="{ y: tableHeight }" :loading="loadingEquipmentTableData">
            <template #bodyCell="{ column, index, record }">
              <template v-if="column.key === 'index'">{{ index + 1 }}</template>
              <template v-if="column.key === 'action'">
                <a-button @click="handleUnbind(record.id)">解绑</a-button>
              </template>
            </template>
          </a-table>
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<style scoped lang="scss">
.equipment__container {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.main-content {
  flex: 1;
  overflow: hidden;
}

.input__container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow: hidden;
  height: 100%;

  .description-wrapper {
    flex: 1;
    overflow: auto;
  }
}

.table-wrapper {
  height: 100%;
  overflow: auto;
}
</style>
