<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;">
          <!-- 查询表单 -->
          <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" 
          >
            <!-- 修复单选/多选列：单选模式下不限制selectable，通过事件控制唯一选中 -->
            <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: {
    // 支持传入默认选中的物料ID（单选传单个ID，多选传数组）
    value: {
      type: [Array, Number, String],
      default: () => []
    },
    // 是否允许多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 默认选中的分类编码
    defaultCategoryCodes: {
      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, // 单选模式下的选中ID
      isSelecting: false // 防止选择事件重复触发的锁
    }
  },
  watch: {
    // 监听外部传入的选中值变化
    value: {
      immediate: true,
      deep: true,
      handler(val) {
        // 防止加载中或正在选择时触发，避免锁定
        if (this.loading || this.isSelecting) return

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

        this.$nextTick(() => {
          if (!this.$refs.materialTable || !this.materialsList.length) return
          
          // 统一处理值格式：单选转单个ID，多选转数组
          const targetIds = this.multiple 
            ? Array.isArray(val) ? val.map(id => Number(id)) : [Number(val)]
            : [Array.isArray(val) ? Number(val[0]) : Number(val)]

          this.isSelecting = true // 加锁，防止重复触发
          try {
            // 清空原有选择
            this.$refs.materialTable.clearSelection()

            if (this.multiple) {
              // 多选模式：选中所有匹配的行
              this.materialsList.forEach(row => {
                if (targetIds.includes(Number(row.id))) {
                  this.$refs.materialTable.toggleRowSelection(row, true)
                }
              })
            } else {
              // 单选模式：只选中第一个匹配的行
              this.singleSelectedId = targetIds[0] || null
              const targetRow = this.materialsList.find(row => Number(row.id) === this.singleSelectedId)
              if (targetRow) {
                this.$refs.materialTable.toggleRowSelection(targetRow, true)
              }
            }
          } finally {
            this.isSelecting = false // 解锁
          }
        })
      }
    },

    // 监听多选状态切换：彻底重置选择状态，避免锁定
    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.$watchers.find(w => w.expression === 'value').handler(this.value)
            })
          } finally {
            this.isSelecting = false
          }
        }
      }
    },

    // 监听默认分类编码变化
    defaultCategoryCodes: {
      immediate: true,
      handler(val) {
        if (val && val.length && this.categoryTreeData.length) {
          this.$nextTick(() => {
            this.selectCategoryNodes(val)
          })
        }
      }
    }
  },
  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)
      }
    },

    /**
     * 获取分类树数据
     */
    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)
          // 构建分类编码到树节点sid的映射
          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
        }))
    },

    /**
     * 构建分类编码到树节点sid的映射
     */
    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
        
        // 列表加载完成后重新同步选中状态（延迟执行，避免DOM未更新）
        setTimeout(() => {
          this.$watchers.find(w => w.expression === 'value').handler(this.value)
        }, 100)
      }).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.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.selectedRows = [lastRow]
            this.singleSelectedId = Number(lastRow.id)
          } else {
            this.selectedRows = selection
            this.singleSelectedId = selection.length > 0 ? Number(selection[0].id) : null
          }
        } else {
          // 多选模式
          this.selectedRows = selection
        }

        // 组装选中数据并触发事件
        const selectedIds = this.selectedRows.map(row => Number(row.id))
        const selectedData = this.selectedRows.map(item => ({
          id: Number(item.id),
          sapNo: item.sapNo,
          materialName: item.materialName,
          categoryCode: item.categoryCode,
          specification: item.specification,
          materialUnit: item.materialUnit,
          isBatchManaged: item.isBatchManaged
        }))

        // 触发事件：input用于v-model绑定，change返回详细数据
        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 = Number(row.id)
          this.selectedRows = [row]
          this.$emit('input', Number(row.id))
          this.$emit('change', row)
        } else {
          this.singleSelectedId = null
          this.selectedRows = []
          this.$emit('input', '')
          this.$emit('change', null)
        }
      } finally {
        this.isSelecting = false
      }
    },

    /**
     * 表格行点击事件
     */
    handleRowClick(row) {
      if (this.isSelecting || !this.$refs.materialTable) return

      this.isSelecting = true
      try {
        if (!this.multiple) {
          // 单选模式：点击行切换选中状态
          const isCurrentlySelected = Number(this.singleSelectedId) === Number(row.id)
          this.$refs.materialTable.clearSelection()
          
          if (!isCurrentlySelected) {
            this.$refs.materialTable.toggleRowSelection(row, true)
            this.singleSelectedId = Number(row.id)
            this.selectedRows = [row]
            this.$emit('input', Number(row.id))
            this.$emit('change', row)
          } else {
            this.singleSelectedId = null
            this.selectedRows = []
            this.$emit('input', '')
            this.$emit('change', null)
          }
        } 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)
      } finally {
        this.isSelecting = false
      }
    },

    /**
     * 获取选中的物料详情（外部调用）
     */
    getSelectedMaterials() {
      return this.multiple ? [...this.selectedRows] : (this.selectedRows[0] || null)
    },

    /**
     * 设置单选选中项（外部调用）
     */
    setSingleSelection(materialId) {
      if (this.isSelecting || this.multiple) return

      this.isSelecting = true
      try {
        const targetId = Number(materialId)
        this.singleSelectedId = targetId
        this.$nextTick(() => {
          this.$refs.materialTable.clearSelection()
          const targetRow = this.materialsList.find(row => Number(row.id) === targetId)
          if (targetRow) {
            this.$refs.materialTable.toggleRowSelection(targetRow, true)
            this.selectedRows = [targetRow]
            this.$emit('input', targetId)
            this.$emit('change', targetRow)
          }
        })
      } 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>