<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import { message } from 'ant-design-vue';
import type { ColumnsType } from 'ant-design-vue/es/table/interface';
import { listMaskCombination } from "@/api/pwoManage/maskCombination";
import { listStationBindMask, bindMaskCombinationToStations, unbindStationMask } from "@/api/pwoManage/mask";
import { usePwoStore } from '@/store';

const pwoStore = usePwoStore();

interface MaskTableItem {
  key: string;
  operationTitle: string;
  operationCode: string;
  maskName: string;
  maskCode: string;
  [key: string]: any;
}

interface MaskCombinationItem {
  key: string;
  combinationCode: string;
  combinationName: string;
  combinationStatus: string;
  [key: string]: any;
}

const maskColumns = [
  { title: '序号', dataIndex: 'index', key: 'index', align: 'center', width: 80 },
  { title: '工序编码', dataIndex: 'operationCode', key: 'operationCode', align: 'center' },
  { title: '工序名称', dataIndex: 'operationTitle', key: 'operationTitle', align: 'center' },
  { title: '治具编码', dataIndex: 'maskCode', key: 'maskCode', align: 'center' },
  { title: '治具名称', dataIndex: 'maskName', key: 'maskName', align: 'center' },
  { title: '操作', dataIndex: 'action', key: 'action', align: 'center' },
];

// 治具表格
const maskTableData = ref<MaskTableItem[]>([]);

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

const openMaskModal = ref(false)
const maskCombinationColumns = [
  { title: '序号', dataIndex: 'index', key: 'index', align: 'center', width: 80 },
  { title: '组合编码', dataIndex: 'combinationCode', key: 'combinationCode', align: 'center' },
  { title: '组合名称', dataIndex: 'combinationName', key: 'combinationName', align: 'center' },
  { title: '组合状态', dataIndex: 'combinationStatus', key: 'combinationStatus', align: 'center' },
  { title: '操作', dataIndex: 'action', key: 'action', align: 'center', width: 100 },
]
const maskCombinationTableData = ref<MaskCombinationItem[]>([])
const fetchCombinationList = async () => {
  try {
    const { rows, total } = await listMaskCombination({})
    if (total as number <= 0) throw new Error('未查询到组合列表');
    maskCombinationTableData.value = rows;
  } catch (error: any) {
    message.error(error.message || '获取工单信息失败');
  }
}

const handleBind = async (id: number) => {
  try {
    await bindMaskCombinationToStations({
      lotTraceOrderId: pwoStore.pwoInfo.id,
      maskCombinationId: id
    });
    message.success('绑定成功');
    fetchBoundMaskList();
    openMaskModal.value = false;
  } catch (error: any) {
    message.error(`绑定失败: ${ error.message }`);
  }
}

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

// 获取已绑定的治具列表
const loadingMask = ref(false);
const fetchBoundMaskList = async () => {
  const traceOrderId = pwoStore.pwoInfo.id;
  if (!traceOrderId) return;
  loadingMask.value = true;
  try {
    const { rows, total } = await listStationBindMask({ traceOrderId })
    if (total as number <= 0) return;
    maskTableData.value = rows;
  } catch (error: any) {
    message.error(error.message || '查询治具列表失败');
  } finally {
    loadingMask.value = false;
  }
}

const inspectingMask = reactive({
  maskCode: '',
  maskName: '',
})

const rowClick = (record: MaskTableItem) => {
  inspectingMask.maskCode = record.maskCode;
  inspectingMask.maskName = record.maskName;
}

// 计算表格高度
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
});

fetchCombinationList()
fetchBoundMaskList()
</script>

<template>
  <div class="mask__container">
    <a-row class="main-content" :gutter="24">
      <a-col :span="14" class="mask-item__container">
        <div class="main-title">治具组合信息</div>
        <a-space>
          <a-button size="large" @click="() => openMaskModal = true">绑定治具组合</a-button>
          <a-button size="large" @click="fetchBoundMaskList">刷新</a-button>
        </a-space>
        <div class="table-wrapper" ref="customTable">
          <a-table :dataSource="maskTableData" :columns="maskColumns as ColumnsType<MaskTableItem>"
            :pagination="false" bordered sticky size="middle" :scroll="{ y: tableHeight }" :loading="loadingMask">
            <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-col :span="10" class="mask-item__container">
        <div class="main-title">治具校验</div>
        <a-row>
          <a-col :span="20">
            <a-input size="large" v-model:value="maskInput" @pressEnter="" placeholder="按下回车校验" />
          </a-col>
          <a-col :span="3" :offset="1">
            <a-button size="large" @click="">校验</a-button>
          </a-col>
        </a-row>
        <div class="table-wrapper">
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="治具编码"></a-descriptions-item>
            <a-descriptions-item label="治具名称"></a-descriptions-item>
            <a-descriptions-item label="治具组合"></a-descriptions-item>
            <a-descriptions-item label="标准使用次数"></a-descriptions-item>
            <a-descriptions-item label="当前使用次数"></a-descriptions-item>
            <a-descriptions-item label="关联工序"></a-descriptions-item>
          </a-descriptions>
        </div>
      </a-col>
    </a-row>

    <a-modal v-model:open="openMaskModal" title="绑定治具组合" width="50vw" :bodyStyle="{ padding: '20px 0' }" :footer="null">
      <a-table :dataSource="maskCombinationTableData" :columns="maskCombinationColumns as ColumnsType<MaskCombinationItem>"
        :pagination="false" bordered sticky :scroll="{ y: tableHeight }">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.key === 'index'">{{ index + 1 }}</template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleBind(record.id)">绑定</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

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

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

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

    .main-title {
      font-size: 20px;
      font-weight: 600;
      border-bottom: 1px solid #c9c9c9;
      padding: 0 0 8px;
    }

    .table-wrapper {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
