<template>
  <div class="material-selector-container">
    <splitpanes class="default-theme">
      <!-- 左侧分类树 -->
      <pane size="16" class="tree-pane">
        <TreeComponent
          ref="treeComponent"
          :tree-data="categoryTreeData"
          :tree-props="treeProps"
          :node-key="nodeKey"
          :show-search="true"
          search-placeholder="请输入分类名称"
          :default-expand-all="true"
          :highlight-current="true"
          :loading="loadingTree"
          @node-click="handleTreeClick"
        >
          <template #node-content="{ node, data }">
            <span class="custom-tree-node">{{ node.label }}</span>
          </template>
        </TreeComponent>
      </pane>

      <!-- 右侧物料列表 -->
      <pane size="84" class="table-pane">
        <div class="table-header">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
            <el-form-item label="SAP物料号" prop="sapNo">
              <el-input
                v-model="queryParams.sapNo"
                placeholder="请输入SAP物料号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName">
              <el-input
                v-model="queryParams.materialName"
                placeholder="请输入物料名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料分类" prop="categoryNameInput">
              <el-input
                v-model="queryParams.categoryNameInput"
                placeholder="请输入物料分类"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 表格容器：唯一滚动区域 -->
        <div class="table-container">
          <el-table
            ref="materialTable"
            v-loading="loading"
            :data="materialsList"
            @selection-change="handleSelectionChange"
            :scroll-x="true"
            :row-key="row => row.id" 
            @row-click="handleRowClick"
            :select-on-indeterminate="false"
            @select="handleTableSelect"
            @row-dblclick="handleRowDblClick"  
          >
            <!-- 单选模式下隐藏选择框 -->
            <el-table-column 
              type="selection" 
              width="55" 
              align="center"
              v-if="multiple"
            />
            <el-table-column type="index" label="序号" align="center"/>
            <el-table-column label="SAP物料号" align="center" prop="sapNo" />
            <el-table-column label="物料名称" align="center" prop="materialName" width="150"/>
            <el-table-column label="TS Code" align="center" prop="tsCode" />
            <el-table-column label="物料分类" align="center" prop="categoryCode">
              <template slot-scope="scope">
                {{ scope.row.displayCategory }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="计量单位" align="center" prop="materialUnit" />
            <el-table-column label="是否批次管理" align="center" prop="isBatchManaged">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isBatchManaged === 1 ? 'success' : 'info'" size="mini">
                  {{ scope.row.isBatchManaged === 1 ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="原始库存" align="center" prop="originalStock" />
            <el-table-column label="新增数量" align="center" prop="addedQuantity" />
            <el-table-column label="可用库存" align="center" prop="availableStock">
              <template slot-scope="scope">
                <span :style="{color: scope.row.availableStock <= 0 ? 'red' : 'inherit'}">
                  {{ scope.row.availableStock }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页：固定在底部 -->
        <div class="pagination-container">
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </pane>
    </splitpanes>
  </div>
</template>

<script>
import { ListMaterialsInventory } from "@/api/inventory/materials"
import { listMaterials_category } from "@/api/inventory/materials_category"
import { listLog } from "@/api/inventory/items"
import TreeComponent from '@/views/inventory/materials_category/treeComponent.vue'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'

export default {
  name: "MaterialSelector",
  components: { TreeComponent, Splitpanes, Pane },
  props: {
    value: {
      type: [Array, String, Number],
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: true
    },
    defaultCategoryCodes: {
      type: Array,
      default: () => []
    },
    selectedMaterialIds: { 
      type: Array,
      default: () => []
    },
    detailList: {
      type: Array,
      default: () => []
    },
    ordersId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      categoryTreeData: [],
      treeProps: { children: 'children', label: 'label', value: 'sid' },
      nodeKey: 'sid',
      loadingTree: false,
      categoryMap: {}, 
      categoryNameToCodeMap: {}, 
      categoryCodeToSidMap: {}, 
      currentNodeId: null,
      queryParams: { 
        pageNum: 1,
        pageSize: 10,
        sapNo: null,
        materialName: null,
        tsCode: null,
        categoryCode: null,
        categoryNameInput: null,
        specification: null,
      },
      materialsList: [],
      total: 0,
      loading: false,
      selectedRows: [],
      singleSelectedId: null,
      isSelecting: false,
      isRetrySync: false,
      inventoryCache: {},
      // 新增：存储listLog返回的订单明细数据
      orderLogData: []
    }
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler(val) {
        if (this.selectedMaterialIds.length === 0) {
          this.handleValueChange(val)
        }
      }
    },
    selectedMaterialIds: {
      immediate: true,
      deep: true,
      handler(val) {
        this.handleValueChange(val)
      }
    },
    multiple: {
      immediate: true,
      handler(val) {
        if (this.$refs.materialTable) {
          this.isSelecting = true
          try {
            this.$refs.materialTable.clearSelection()
            this.selectedRows = []
            this.singleSelectedId = null
            this.$nextTick(() => this.handleValueSync())
          } finally {
            this.isSelecting = false
          }
        }
      }
    },
    defaultCategoryCodes: {
      immediate: true,
      handler(val) {
        if (val && val.length && this.categoryTreeData.length) {
          this.$nextTick(() => this.selectCategoryNodes(val))
        }
      }
    },
    loading: {
      handler(newVal) {
        if (!newVal && !this.isSelecting && !this.isRetrySync) {
          this.$nextTick(() => {
            setTimeout(() => this.handleValueSync(), 200)
          })
        }
      }
    },
    detailList: {
      immediate: true,
      deep: true,
      handler() {
        if (this.materialsList.length > 0) {
          this.calculateMaterialStock()
        }
      }
    },
    // 监听订单ID变化，重新获取日志数据并计算库存
    ordersId: {
      immediate: true,
      handler(val) {
        console.log('MaterialSelector 接收的 ordersId 更新:', val);
        if (val) {
          this.getOrderLogData(val)
        }
      }
    }
  },
  async created() {
    await Promise.all([this.getCategoryList(), this.getCategoryTreeData()])
    // 如果有订单ID，先获取日志数据
    if (this.ordersId) {
      await this.getOrderLogData(this.ordersId)
    }
    this.getList()
    console.log('父组件接收的 ordersId:', this.ordersId);
  },
  methods: {
    // 新增：获取订单日志数据（listLog接口）
    async getOrderLogData(orderId) {
      try {
        const res = await listLog({ orderId })
        if (res.code === 200 && res.rows) {
          this.orderLogData = res.rows
          console.log('获取订单日志数据成功:', this.orderLogData)
          // 获取数据后重新计算库存
          if (this.materialsList.length > 0) {
            this.calculateMaterialStock()
          }
        }
      } catch (error) {
        console.error('获取订单日志数据失败:', error)
      }
    },

    // 重写：库存计算逻辑（可用库存 = 原始库存 + actualQuantity）
    calculateMaterialStock() {
      console.log("开始计算库存 - 订单日志数据:", this.orderLogData)
      if (!this.orderLogData.length) return

      // 按materialId汇总actualQuantity
      const materialQtyMap = {}
      this.orderLogData.forEach(item => {
        const materialId = item.materialId
        const actualQty = Number(item.actualQuantity) || 0
        
        if (!materialQtyMap[materialId]) {
          materialQtyMap[materialId] = 0
        }
        materialQtyMap[materialId] += actualQty
      })

      // 更新物料列表的库存数据
      this.materialsList.forEach(material => {
        const addedQty = materialQtyMap[material.id] || 0
        // 新增数量
        this.$set(material, 'addedQuantity', addedQty)
        // 可用库存 = 原始库存 + 新增数量
        this.$set(material, 'availableStock', (material.originalStock || 0) + addedQty)
      })
    },

    // 双击行事件处理
    handleRowDblClick(row) {
      if (this.isSelecting || !this.$refs.materialTable) return

      this.isSelecting = true
      try {
        if (!this.multiple) {
          this.$refs.materialTable.clearSelection()
          this.$refs.materialTable.toggleRowSelection(row, true)
          this.singleSelectedId = row.id
          this.selectedRows = [row]
          
          const selectedData = {
            id: row.id,
            sapNo: row.sapNo,
            materialName: row.materialName,
            tsCode: row.tsCode,
            categoryCode: row.categoryCode,
            categoryName: this.categoryMap[row.categoryCode] || row.categoryCode,
            specification: row.specification,
            materialUnit: row.materialUnit,
            isBatchManaged: row.isBatchManaged,
            originalStock: row.originalStock,
            addedQuantity: row.addedQuantity,
            availableStock: row.availableStock
          }
          
          this.$emit('input', row.id)
          this.$emit('change', selectedData)
          this.$emit('selection-change', {
            materialIds: [row.id],
            materials: [selectedData],
            names: [row.materialName],
            categoryIds: [row.categoryCode || '']
          })
          
          this.$emit('confirm', selectedData)
          this.$emit('close')
        } else {
          this.$refs.materialTable.toggleRowSelection(row)
        }
      } finally {
        this.isSelecting = false
      }
    },

    // 获取分类列表
    async getCategoryList() {
      try {
        const response = await listMaterials_category({ pageNum: 1, pageSize: 1000 })
        if (response.rows && response.rows.length > 0) {
          this.categoryMap = {}
          this.categoryNameToCodeMap = {}
          response.rows.forEach(item => {
            if (item.isUsed !== 0 && item.isUsed !== '0') {
              const code = item.categoryCode
              this.categoryMap[code] = item.categoryName
              if (!this.categoryNameToCodeMap[item.categoryName]) {
                this.categoryNameToCodeMap[item.categoryName] = code
              } else if (!Array.isArray(this.categoryNameToCodeMap[item.categoryName])) {
                this.categoryNameToCodeMap[item.categoryName] = [this.categoryNameToCodeMap[item.categoryName], code]
              } else {
                this.categoryNameToCodeMap[item.categoryName].push(code)
              }
            }
          })
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
      }
    },

    handleValueChange(val) {
      if (this.isSelecting) return

      if (!val || (Array.isArray(val) && !val.length)) {
        this.clearSelection()
        return
      }

      if (this.currentNodeId || this.queryParams.categoryCode) {
        this.currentNodeId = null
        this.queryParams.categoryCode = null
        this.getList()
        return
      }

      if (this.loading || !this.materialsList.length) {
        const timer = setTimeout(() => {
          this.handleValueSync()
          const retryTimer = setTimeout(() => {
            if (!this.isRetrySync) {
              this.handleValueSync(true)
            }
            clearTimeout(retryTimer)
          }, 500)
          clearTimeout(timer)
        }, 600)
      } else {
        this.handleValueSync()
      }
    },

    async getCategoryTreeData() {
      this.loadingTree = true
      try {
        const response = await listMaterials_category({ pageNum: 1, pageSize: 1000 })
        if (response.rows && response.rows.length > 0) {
          const activeCategories = response.rows.filter(item => item.isUsed !== 0 && item.isUsed !== '0')
          this.categoryTreeData = this.buildTreeData(activeCategories)
          this.buildCategoryCodeToSidMap(this.categoryTreeData)
        }
      } catch (error) {
        console.error('获取分类树数据失败:', error)
      } finally {
        this.loadingTree = false
      }
    },

    buildTreeData(list, parentId = null) {
      return list
        .filter(item => parentId === null 
          ? (!item.parentId || item.parentId === 0 || item.parentId === '0') 
          : Number(item.parentId) === Number(parentId)
        )
        .map(item => ({
          ...item,
          sid: String(item.id),
          label: item.categoryName,
          children: this.buildTreeData(list, item.id).length 
            ? this.buildTreeData(list, item.id) 
            : undefined
        }))
    },

    buildCategoryCodeToSidMap(treeData) {
      treeData.forEach(node => {
        if (node.categoryCode) {
          this.categoryCodeToSidMap[node.categoryCode] = node.sid
          const rawCode = node.categoryCode.replace(/-/g, '')
          if (rawCode !== node.categoryCode) {
            this.categoryCodeToSidMap[rawCode] = node.sid
          }
        }
        if (node.children && node.children.length) {
          this.buildCategoryCodeToSidMap(node.children)
        }
      })
    },

    selectCategoryNodes(categoryCodes) {
      if (!this.$refs.treeComponent || !this.$refs.treeComponent.$refs.tree) return
      const tree = this.$refs.treeComponent.$refs.tree
      categoryCodes.forEach(code => {
        const rawCode = code.replace(/-/g, '')
        const sid = this.categoryCodeToSidMap[rawCode] || this.categoryCodeToSidMap[code]
        if (sid) {
          tree.setCurrentKey(sid)
          this.currentNodeId = sid
          const node = tree.getNode(sid)
          if (node) tree.expandNode(node)
        }
      })
    },

    handleTreeClick(data) {
      this.currentNodeId = data.sid
      this.queryParams.categoryCode = data.categoryCode
      this.queryParams.categoryNameInput = null
      this.queryParams.pageNum = 1
      this.getList()
    },

    // 改造：获取物料列表并初始化库存字段
    getList() {
      this.loading = true
      ListMaterialsInventory(this.queryParams).then(response => {
        const materialRows = (response.rows || []).filter(item => item.isUsed !== 0 && item.isUsed !== '0').map(item => ({
          ...item,
          displayCategory: this.categoryMap[item.categoryCode] || '未匹配分类',
          originalStock: item.stock || 0, // 原始库存
          addedQuantity: 0, // 初始化新增数量（actualQuantity）
          availableStock: item.stock || 0 // 初始化可用库存
        }))
        
        this.materialsList = materialRows
        this.total = response.total || 0
        
        // 缓存库存数据
        materialRows.forEach(item => {
          this.inventoryCache[item.id] = item.stock || 0
        })
        
        // 计算库存（可用库存 = 原始库存 + actualQuantity）
        this.calculateMaterialStock()
        
        this.$nextTick(() => {
          setTimeout(() => this.handleValueSync(), 400)
        })
      }).catch(error => {
        console.error('获取物料列表失败:', error)
        this.materialsList = []
        this.total = 0
      }).finally(() => {
        this.loading = false
      })
    },

    handleQuery() {
      const inputName = this.queryParams.categoryNameInput
      if (inputName) {
        const matchedCode = this.categoryNameToCodeMap[inputName]
        if (matchedCode) {
          this.queryParams.categoryCode = Array.isArray(matchedCode) ? matchedCode[0] : matchedCode
        } else {
          const matchedCodes = Object.entries(this.categoryMap)
            .filter(([code, name]) => name.includes(inputName))
            .map(([code]) => code)
          if (matchedCodes.length > 0) {
            this.queryParams.categoryCode = matchedCodes[0]
          }
        }
      }
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sapNo: null,
        materialName: null,
        tsCode: null,
        categoryCode: null,
        categoryNameInput: null,
        specification: null,
      }
      this.currentNodeId = null
      if (this.$refs.treeComponent && this.$refs.treeComponent.$refs.tree) {
        this.$refs.treeComponent.$refs.tree.setCurrentKey(null)
      }
      this.clearSelection()
      this.getList()
    },

    // 改造：选择事件返回新增的库存数据
    handleSelectionChange(selection) {
      if (this.isSelecting || !this.$refs.materialTable) return

      this.isSelecting = true
      try {
        if (!this.multiple) {
          if (selection.length > 1) {
            const lastRow = selection.pop()
            this.$refs.materialTable.clearSelection()
            this.$refs.materialTable.toggleRowSelection(lastRow, true)
            this.singleSelectedId = lastRow.id
            this.selectedRows = [lastRow]
          } else {
            this.selectedRows = selection
            this.singleSelectedId = selection.length > 0 ? selection[0].id : null
          }
        } else {
          this.selectedRows = selection
        }

        const selectedIds = this.selectedRows.map(row => row.id)
        const selectedData = this.selectedRows.map(item => ({
          id: item.id,
          sapNo: item.sapNo,
          materialName: item.materialName,
          tsCode: item.tsCode,
          categoryCode: item.categoryCode,
          categoryName: this.categoryMap[item.categoryCode] || item.categoryCode,
          specification: item.specification,
          materialUnit: item.materialUnit,
          isBatchManaged: item.isBatchManaged,
          originalStock: item.originalStock,
          addedQuantity: item.addedQuantity,
          availableStock: item.availableStock
        }))

        this.$emit('selection-change', {
          materialIds: selectedIds,
          materials: selectedData,
          names: selectedData.map(item => item.materialName),
          categoryIds: selectedData.map(item => item.categoryCode)
        })

        if (this.multiple) {
          this.$emit('input', selectedIds)
          this.$emit('change', selectedData)
        } else {
          const singleId = selectedIds.length > 0 ? selectedIds[0] : ''
          const singleData = selectedData.length > 0 ? selectedData[0] : null
          this.$emit('input', singleId)
          this.$emit('change', singleData)
        }
      } finally {
        this.isSelecting = false
      }
    },

    handleTableSelect(selection, row) {
      if (this.isSelecting || this.multiple) return

      this.isSelecting = true
      try {
        const isSelected = selection.includes(row)
        this.$refs.materialTable.clearSelection()
        if (isSelected) {
          this.$refs.materialTable.toggleRowSelection(row, true)
          this.singleSelectedId = row.id
          this.selectedRows = [row]
          const selectedData = {
            id: row.id,
            sapNo: row.sapNo,
            materialName: row.materialName,
            tsCode: row.tsCode,
            categoryCode: row.categoryCode,
            categoryName: this.categoryMap[row.categoryCode] || row.categoryCode,
            specification: row.specification,
            materialUnit: row.materialUnit,
            isBatchManaged: row.isBatchManaged,
            originalStock: row.originalStock,
            addedQuantity: row.addedQuantity,
            availableStock: row.availableStock
          }
          this.$emit('input', row.id)
          this.$emit('change', selectedData)
          this.$emit('selection-change', {
            materialIds: [row.id],
            materials: [selectedData],
            names: [row.materialName],
            categoryIds: [row.categoryCode || '']
          })
        } else {
          this.singleSelectedId = null
          this.selectedRows = []
          this.$emit('input', '')
          this.$emit('change', null)
          this.$emit('selection-change', {
            materialIds: [],
            materials: [],
            names: [],
            categoryIds: []
          })
        }
      } finally {
        this.isSelecting = false
      }
    },

    handleRowClick(row) {
      if (this.isSelecting || !this.$refs.materialTable) return

      this.isSelecting = true
      try {
        if (!this.multiple) {
          const isCurrentlySelected = this.singleSelectedId === row.id
          this.$refs.materialTable.clearSelection()
          
          if (!isCurrentlySelected) {
            this.$refs.materialTable.toggleRowSelection(row, true)
            this.singleSelectedId = row.id
            this.selectedRows = [row]
            const selectedData = {
              id: row.id,
              sapNo: row.sapNo,
              materialName: row.materialName,
              tsCode: row.tsCode,
              categoryCode: row.categoryCode,
              categoryName: this.categoryMap[row.categoryCode] || row.categoryCode,
              specification: row.specification,
              materialUnit: row.materialUnit,
              isBatchManaged: row.isBatchManaged,
              originalStock: row.originalStock,
              addedQuantity: row.addedQuantity,
              availableStock: row.availableStock
            }
            this.$emit('input', row.id)
            this.$emit('change', selectedData)
            this.$emit('selection-change', {
              materialIds: [row.id],
              materials: [selectedData],
              names: [row.materialName],
              categoryIds: [row.categoryCode || '']
            })
          } else {
            this.singleSelectedId = null
            this.selectedRows = []
            this.$emit('input', '')
            this.$emit('change', null)
            this.$emit('selection-change', {
              materialIds: [],
              materials: [],
              names: [],
              categoryIds: []
            })
          }
        } else {
          this.$refs.materialTable.toggleRowSelection(row)
        }
      } finally {
        this.isSelecting = false
      }
    },

    clearSelection() {
      if (this.isSelecting || !this.$refs.materialTable) return

      this.isSelecting = true
      try {
        this.$refs.materialTable.clearSelection()
        this.selectedRows = []
        this.singleSelectedId = null
        this.$emit('input', this.multiple ? [] : '')
        this.$emit('change', this.multiple ? [] : null)
        this.$emit('selection-change', {
          materialIds: [],
          materials: [],
          names: [],
          categoryIds: []
        })
      } finally {
        this.isSelecting = false
      }
    },

    handleValueSync(isRetry = false) {
      if (this.loading || this.isSelecting || !this.$refs.materialTable) return
      
      if (isRetry) this.isRetrySync = true
      
      const val = this.selectedMaterialIds.length ? this.selectedMaterialIds : this.value
      if (!val || (Array.isArray(val) && !val.length)) {
        this.clearSelection()
        this.isRetrySync = false
        return
      }

      const targetIds = this.multiple 
        ? Array.isArray(val) ? val.map(id => String(id)) : [String(val)]
        : [String(Array.isArray(val) ? val[0] : val)]
      const validTargetIds = targetIds.filter(id => id && id !== 'undefined' && id !== 'null')

      if (!validTargetIds.length) {
        this.clearSelection()
        this.isRetrySync = false
        return
      }

      this.isSelecting = true
      try {
        this.$refs.materialTable.clearSelection()
        let matchedCount = 0

        this.materialsList.forEach(row => {
          const rowId = String(row.id)
          if (validTargetIds.includes(rowId)) {
            this.$refs.materialTable.toggleRowSelection(row, true)
            matchedCount++
          }
        })

        this.selectedRows = this.materialsList.filter(row => 
          validTargetIds.includes(String(row.id))
        )
        this.singleSelectedId = this.multiple ? null : (this.selectedRows[0]?.id || null)

        if (matchedCount === 0 && !isRetry) {
          this.$emit('selection-change', { 
            materialIds: [], 
            materials: [],
            names: [], 
            categoryIds: [] 
          })
          this.$emit('input', this.multiple ? [] : '')
        }

        if (matchedCount === 0 && isRetry) {
          console.warn('反显重试仍未匹配到ID', {
            targetIds: validTargetIds,
            listIds: this.materialsList.map(r => String(r.id))
          })
        }
      } catch (e) {
        console.error('反显同步失败:', e)
      } finally {
        this.isSelecting = false
        this.isRetrySync = false
      }
    },

    setSelectedIds(ids) {
      if (this.isSelecting) return
      
      this.isSelecting = true
      try {
        this.currentNodeId = null
        this.queryParams.categoryCode = null
        
        this.getList().then(() => {
          this.$nextTick(() => {
            this.$props.selectedMaterialIds = ids
            this.handleValueSync(true)
          })
        })
      } finally {
        this.isSelecting = false
      }
    },

    getSelectedMaterials() {
      if (this.multiple) {
        return this.selectedRows.map(row => ({
          id: row.id,
          sapNo: row.sapNo,
          materialName: row.materialName,
          tsCode: row.tsCode,
          categoryCode: row.categoryCode,
          categoryName: this.categoryMap[row.categoryCode] || row.categoryCode,
          specification: row.specification,
          materialUnit: row.materialUnit,
          isBatchManaged: row.isBatchManaged,
          originalStock: row.originalStock,
          addedQuantity: row.addedQuantity,
          availableStock: row.availableStock
        }))
      } else {
        return this.selectedRows[0] ? {
          id: this.selectedRows[0].id,
          sapNo: this.selectedRows[0].sapNo,
          materialName: this.selectedRows[0].materialName,
          tsCode: this.selectedRows[0].tsCode,
          categoryCode: this.selectedRows[0].categoryCode,
          categoryName: this.categoryMap[this.selectedRows[0].categoryCode] || this.selectedRows[0].categoryCode,
          specification: this.selectedRows[0].specification,
          materialUnit: this.selectedRows[0].materialUnit,
          isBatchManaged: this.selectedRows[0].isBatchManaged,
          originalStock: this.selectedRows[0].originalStock,
          addedQuantity: this.selectedRows[0].addedQuantity,
          availableStock: this.selectedRows[0].availableStock
        } : null
      }
    },

    setSingleSelection(id) {
      if (this.isSelecting || this.multiple) return

      this.isSelecting = true
      try {
        this.singleSelectedId = id
        this.$nextTick(() => {
          this.$refs.materialTable.clearSelection()
          const targetRow = this.materialsList.find(row => String(row.id) === String(id))
          if (targetRow) {
            this.$refs.materialTable.toggleRowSelection(targetRow, true)
            this.selectedRows = [targetRow]
            const selectedData = {
              id: targetRow.id,
              sapNo: targetRow.sapNo,
              materialName: targetRow.materialName,
              tsCode: targetRow.tsCode,
              categoryCode: targetRow.categoryCode,
              categoryName: this.categoryMap[targetRow.categoryCode] || targetRow.categoryCode,
              specification: targetRow.specification,
              materialUnit: targetRow.materialUnit,
              isBatchManaged: targetRow.isBatchManaged,
              originalStock: targetRow.originalStock,
              addedQuantity: targetRow.addedQuantity,
              availableStock: targetRow.availableStock
            }
            this.$emit('input', id)
            this.$emit('change', selectedData)
            this.$emit('selection-change', {
              materialIds: [id],
              materials: [selectedData],
              names: [targetRow.materialName],
              categoryIds: [targetRow.categoryCode || '']
            })
          } else {
            this.$emit('input', '')
            this.$emit('change', null)
            this.$emit('selection-change', {
              materialIds: [],
              materials: [],
              names: [],
              categoryIds: []
            })
          }
        })
      } finally {
        this.isSelecting = false
      }
    }
  }
}
</script>

<style scoped>
.material-selector-container {
  height: 100%;
  min-height: 500px;
  overflow: hidden !important;
}
.custom-tree-node {
  font-size: 14px;
}
.tree-pane {
  overflow: hidden !important;
  max-height: 100%;
  scrollbar-width: none;
  -ms-overflow-style: none;
}
.tree-pane::-webkit-scrollbar {
  display: none;
}
.table-pane {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden !important;
}
.table-header {
  flex-shrink: 0;
  padding: 10px;
}
.table-container {
  flex: 1;
  padding: 0 10px;
  overflow: auto !important;
  scrollbar-width: thin;
  scrollbar-color: #ccc #f5f5f5;
}
.table-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}
.table-container::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}
.table-container::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}
.pagination-container {
  flex-shrink: 0;
  padding: 10px;
  text-align: right;
}
/deep/ .el-table .el-table__header .cell {
  text-align: center;
}
/deep/ .el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #f5f5f5;
  cursor: pointer;
}
/deep/ .el-table__fixed-right,
/deep/ .el-table__fixed-left {
  pointer-events: auto !important;
}
/deep/ .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}
/deep/ .el-table__body tr.current-row td {
  background-color: #e8f4fd !important;
}
</style>