<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { usePwoStore, useJobStore } from '@/store'
import type { ColumnsType } from 'ant-design-vue/es/table/interface';
import { message } from 'ant-design-vue'
import { listMainMaterialEntryLog, addWaferEntryLogByCarrier, addDieEntryLogByCarrier, addWaferEntryLog, addDieEntryLog, delMainMaterialEntryLog } from '@/api/pwoManage/station/primaryMaterial'

const pwoStore = usePwoStore();
const jobStore = useJobStore();

interface MaterialTableItem {
  key: string;
  carrierCode: string;
  qrCode: string;
  dieCode: string;
  waferCode: string;
  [key: string]: any;
}

const materialColumns = [
  { title: '序号', dataIndex: 'index', key: 'index', align: 'center', width: 80 },
  { title: '载具 ID', dataIndex: 'carrierCode', key: 'carrierCode', align: 'center' },
  { title: 'Wafer ID', dataIndex: 'waferCode', key: 'waferCode', align: 'center' },
  { title: 'Die ID', dataIndex: 'dieCode', key: 'dieCode', align: 'center' },
  { title: '二维码', dataIndex: 'qrCode', key: 'qrCode', align: 'center' },
  { title: '操作', key: 'action', align: 'center', width: 120 },
]

// 查询站点下主材信息
const loadingMaterialTableData = ref(false);
const fetchPrimaryMaterialList = async () => {
  const stationId = jobStore.jobInfo.id;
  if (!stationId) return;
  loadingMaterialTableData.value = true;
  try {
    const { rows } = await listMainMaterialEntryLog({ stationId });
    materialTableData.value = rows;
  } catch (error: any) {
    message.error(error.message || '查询站点下主材信息失败');
  } finally {
    loadingMaterialTableData.value = false;
  }
};

const carrierInput = ref<string>('');
// 录入载具
const insertCarrier = async () => {
  if (!carrierInput.value) return;
  const form = {
    carrierCode: carrierInput.value,
    stationCode: jobStore.jobInfo.code
  };
  try {
    if (materialType.value === "Wafer") {
      await addWaferEntryLogByCarrier(form);
    } else if (materialType.value === "Die") {
      await addDieEntryLogByCarrier(form);
    } else throw new Error('主材类型异常');
    carrierInput.value = '';
    message.success('添加成功');
    fetchPrimaryMaterialList();
  } catch (error: any) {
    message.error(error.message || '添加载具失败');
    return;
  }
}

// 主材料表格
const materialTableData = ref<MaterialTableItem[]>([]);
const materialInput = ref<string>('');
// 录入主材料
const insertMaterial = async () => {
  if (!materialInput.value) return;
  const form = {
    mainMaterialCodes: [materialInput.value],
    stationCode: jobStore.jobInfo.code
  };
  try {
    if (materialType.value === "Wafer") {
      await addWaferEntryLog(form);
    } else if (materialType.value === "Die") {
      await addDieEntryLog(form);
    } else throw new Error('主材类型异常');
    materialInput.value = '';
    message.success('添加成功');
    fetchPrimaryMaterialList();
  } catch (error: any) {
    message.error(error.message || '添加主材失败');
    return;
  }
}
// 移除主材料
const handleRemoveMaterial = async (row: MaterialTableItem) => {
  try {
    await delMainMaterialEntryLog(row.id);
    message.success('删除成功');
    fetchPrimaryMaterialList();
  } catch (error: any) {
    message.error(error.message || '删除主材失败');
    return;
  }
}

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

// 初始化主材类型
const materialType = ref()
if (pwoStore.pwoInfo.orderType) {
  const num = parseInt(pwoStore.pwoInfo.orderType)
  materialType.value = num % 4 === 0 ? 'Die' : 'Wafer'
} else {
  materialType.value = '主材类型异常'
}

fetchPrimaryMaterialList()
</script>

<template>
  <div class="primary-material__container">
    <div class="main-title">主材料进站</div>
    <a-form layout="inline" size="large">
      <a-form-item label="主材类型">
        <a-input v-model:value="materialType" disabled />
      </a-form-item>
      <a-form-item label="载具 ID">
        <a-input v-model:value="carrierInput" @pressEnter="insertCarrier" placeholder="按下回车录入" allow-clear />
      </a-form-item>
      <a-form-item label="物料编码">
        <a-input v-model:value="materialInput" @pressEnter="insertMaterial" placeholder="按下回车录入" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="insertMaterial">录入</a-button>
      </a-form-item>
      <a-form-item>
        <a-button @click="fetchPrimaryMaterialList">刷新</a-button>
      </a-form-item>
    </a-form>
    <div class="table-wrapper" ref="customTable">
      <a-table :dataSource="materialTableData" :columns="materialColumns as ColumnsType<MaterialTableItem>"
        :pagination="false" bordered sticky :scroll="{ y: tableHeight }" :loading="loadingMaterialTableData">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.key === 'index'">{{ index + 1 }}</template>
          <template v-if="column.key === 'action'">
            <a-button type="text" danger @click="handleRemoveMaterial(record as MaterialTableItem)">删除</a-button>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<style scoped lang="scss">
.primary-material__container {
  flex: 1;
  overflow: hidden;
  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>
