<template>
  <div class="p-2">
    <el-card shadow="never">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="批次码" prop="batchCode">
          <el-input v-model="queryParams.batchCode" placeholder="请输入批次码" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="库位编码" prop="locationCode">
          <el-input v-model="queryParams.locationCode" placeholder="请输入库位编码" clearable @keyup.enter="handleQuery" />
        </el-form-item>
<!--        <el-form-item label="物料大类" prop="materialCategoryId">
          <el-select v-model="queryParams.materialCategoryId" placeholder="请选择物料大类" clearable>
            <el-option
              v-for="item in mategoryOptions"
              :key="item.materialCategoryId"
              :label="item.materialCategoryName"
              :value="item.materialCategoryId"
            />
          </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 8px" shadow="never">
      <el-table
        v-loading="loading"
        :data="inventoryList"
        @row-click="handleRowClick"
        @current-change="handleCurrentChange"
        ref="tableRef"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="批次码" align="center" prop="batchCode" />
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="物料名称" align="center" prop="materialName" />
        <el-table-column label="库位编码" align="center" prop="locationCode" />
        <el-table-column label="物料大类" align="center" prop="materialCategoryName" />
        <el-table-column label="库存数量" align="center" prop="inventoryQty" />
        <el-table-column label="锁定状态" align="center" prop="lockState">
          <template #default="scope">
            <dict-tag :options="lock_state" :value="scope.row.lockState"/>
          </template>
        </el-table-column>
        <el-table-column label="库存状态" align="center" prop="inventoryStatus">
          <template #default="scope">
            <dict-tag :options="inventory_status" :value="scope.row.inventoryStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="仓库编码" align="center" prop="warehouseCode" />
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup name="SelectInventoryInWMS" lang="ts">
import { listInventory } from '@/api/wms/inventory';
import { InventoryVO, InventoryQuery } from '@/api/wms/inventory/types';
import { getBaseMaterialCategoryListInWMS } from '@/api/wms/baseMaterialCategory';

// 定义 props
const props = defineProps({
  materialCategoryId: {
    type: [String, Number],
    default: undefined
  },
  warehouseId: {
    type: [String, Number],
    default: undefined
  }
});

// 定义 emits
const emit = defineEmits(['selection']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { lock_state, inventory_status } = toRefs<any>(proxy?.useDict('lock_state', 'inventory_status'));

const inventoryList = ref<InventoryVO[]>([]);
const loading = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const tableRef = ref();

const queryParams = ref<InventoryQuery>({
  pageNum: 1,
  pageSize: 10,
  batchCode: undefined,
  materialCode: undefined,
  locationCode: undefined,
  materialCategoryId: props.materialCategoryId as number,
  storeId: props.warehouseId,
  lockState: undefined, // 不限制锁定状态，在客户端过滤
  inventoryStatus: '1', // 只显示正常库存状态
  params: {}
});

let mategoryOptions = ref([]);

// 获取物料大类选项
const getMaterialCategorySelect = async () => {
  const res = await getBaseMaterialCategoryListInWMS(null);
  mategoryOptions.value = res.data;
};

// 查询库存列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await listInventory(queryParams.value);
    inventoryList.value = res.rows.filter(item =>
      item.inventoryQty > 0 && // 只显示有库存的物料
      (item.lockState === '0' || item.lockState === null || item.lockState === undefined || item.lockState === '') && // 允许未锁定或空值
      item.inventoryStatus === '1' // 只显示正常状态的库存
    );
    total.value = res.total;
  } catch (error) {
    console.error('获取库存列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.materialCategoryId = props.materialCategoryId as number;
  queryParams.value.storeId = props.warehouseId;
  handleQuery();
};

// 行点击事件
const handleRowClick = (row: InventoryVO) => {
  tableRef.value.setCurrentRow(row);
  emit('selection', row);
};

// 当前行改变事件
const handleCurrentChange = (currentRow: InventoryVO) => {
  emit('selection', currentRow);
};

// 监听 props 变化
watch(
  () => [props.materialCategoryId, props.warehouseId],
  ([newMaterialCategoryId, newWarehouseId]) => {
    queryParams.value.materialCategoryId = newMaterialCategoryId as number;
    queryParams.value.storeId = newWarehouseId;
    getList();
  },
  { immediate: false }
);

onMounted(async () => {
  // await getMaterialCategorySelect();
  await getList();
});

// 暴露表格引用给父组件
defineExpose({
  tableRef
});
</script>

<style scoped>
.p-2 {
  padding: 8px;
}
</style>
