<template>
  <div class="material-selector-container" style="overflow: hidden;">
    <splitpanes class="default-theme">
      <!-- 左侧分类树 -->
      <pane size="16" style="overflow: auto;">
        <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" style="overflow: auto;">
        <div style="padding: 10px; display: flex; flex-direction: column;">
          <!-- 查询表单（恢复所有查询项，保留ID核心逻辑） -->
          <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>

          <!-- 物料表格（恢复所有字段显示） -->
          <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" 
          >
            <el-table-column 
              type="selection" 
              width="55" 
              align="center"
            />
            <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 || categoryMap[scope.row.categoryCode] || scope.row.categoryCode || '-' }}
              </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>

          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </pane>
    </splitpanes>
  </div>
</template>

<script>
import { listMaterials } from "@/api/inventory/materials"
import { listMaterials_category } from "@/api/inventory/materials_category"
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: { // 核心：基于ID的选中项
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      categoryTreeData: [],
      treeProps: { children: 'children', label: 'label', value: 'sid' },
      nodeKey: 'sid',
      loadingTree: false,
      categoryMap: {}, // 恢复分类名称映射（显示用）
      categoryNameToCodeMap: {}, // 恢复分类名称转编码（查询用）
      categoryCodeToSidMap: {}, // 恢复分类编码转SID（树选择用）
      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
    }
  },
  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)
          })
        }
      }
    }
  },
  async created() {
    // 恢复分类列表和树数据加载（显示分类名称用）
    await Promise.all([this.getCategoryList(), this.getCategoryTreeData()])
    this.getList()
  },
  methods: {
    // 恢复分类列表加载（分类名称映射）
    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
      listMaterials(this.queryParams).then(response => {
        // 恢复所有字段映射（显示用）
        this.materialsList = (response.rows || []).filter(item => item.isUsed !== 0 && item.isUsed !== '0').map(item => ({
          ...item,
          displayCategory: this.categoryMap[item.categoryCode] || `${item.categoryCode}（未匹配分类）`
        }))
        this.total = response.total || 0
        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()
    },
    // 核心：基于 ID 的选择事件（保留所有字段返回）
    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.selectedRows = [lastRow]
            this.singleSelectedId = lastRow.id
          } else {
            this.selectedRows = selection
            this.singleSelectedId = selection.length > 0 ? selection[0].id : null
          }
        } else {
          this.selectedRows = selection
        }

        // 返回数据保留所有字段，但核心标识为id
        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
        }))

        this.$emit('selection-change', {
          materialIds: selectedIds, // 核心：返回ID数组
          materials: selectedData,  // 保留所有字段数据
          names: selectedData.map(item => item.materialName),
          categoryIds: selectedData.map(item => item.categoryCode)
        })

        if (this.multiple) {
          this.$emit('input', selectedIds) // v-model绑定ID
          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
      }
    },
    // 单选模式下的选择事件（纯 ID 逻辑，保留字段返回）
    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
          }
          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
      }
    },
    // 行点击事件（纯 ID 逻辑，保留字段返回）
    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
            }
            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
      }
    },
    // 清空选择（纯 ID 逻辑）
    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
      }
    },
    // 核心：基于 ID 的反显逻辑（保留所有字段显示）
    handleValueSync(isRetry = false) {
      if (this.loading || this.isSelecting || !this.$refs.materialTable) return
      
      if (isRetry) this.isRetrySync = true
      
      // 优先使用 selectedMaterialIds，其次是 value
      const val = this.selectedMaterialIds.length ? this.selectedMaterialIds : this.value
      if (!val || (Array.isArray(val) && !val.length)) {
        this.clearSelection()
        this.isRetrySync = false
        return
      }

      // 统一处理 ID 格式（兼容字符串/数字）
      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

        // 基于 ID 精准匹配反显（保留所有字段）
        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
      }
    },
    // 外部设置选中 ID 的方法
    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
      }
    },
    // 获取选中物料（返回完整字段，核心为ID）
    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
        }))
      } 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
        } : null
      }
    },
    // 单选模式下设置选中 ID
    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
            }
            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;
}
.custom-tree-node {
  font-size: 14px;
}
/deep/ .el-table .el-table__header .cell {
  text-align: center;
}
/deep/ .el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #f5f7fa;
}
/deep/ .el-table__fixed-right,
/deep/ .el-table__fixed-left {
  pointer-events: auto !important;
}
</style>