<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 }} ({{ data.categoryCode || '-' }})</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="物料编码" prop="materialCode">
              <el-input
                v-model="queryParams.materialCode"
                placeholder="请输入物料编码"
                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="SAP物料号" prop="sapNo">
              <el-input
                v-model="queryParams.sapNo"
                placeholder="请输入SAP物料号"
                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="table"  
            v-loading="loading" 
            :data="materialsList" 
            @selection-change="handleSelectionChange" 
            :scroll-x="true"
            :row-key="row => row.materialCode"  
            @row-click="handleRowClick"
            :select-on-indeterminate="false"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="index" label="序号" align="center"/>
            <el-table-column label="物料编码" align="center" prop="materialCode" width="120"/>
            <el-table-column label="物料名称" align="center" prop="materialName"  width="150"/>
            <el-table-column label="SAP物料号" align="center" prop="sapNo" />
            <el-table-column label="TS Code" align="center" prop="tsCode" />
            <el-table-column label="物料分类编码（原始）" align="center" prop="categoryCode" width="150" />
            <el-table-column label="物料分类编码（格式化）" align="center" width="180">
              <template slot-scope="scope">
                {{ categoryCodeFormatMap[scope.row.categoryCode] || scope.row.categoryCode || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="物料分类名称" align="center" width="150">
              <template slot-scope="scope">
                {{ scope.row.displayCategory || categoryMap[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: {
    selectedMaterialCodes: {
      type: Array,
      default: () => []
    },
    defaultCategoryCodes: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      categoryTreeData: [],
      treeProps: { children: 'children', label: 'label', value: 'sid' },
      nodeKey: 'sid',
      loadingTree: false,
      categoryMap: {},
      categoryNameToCodeMap: {},
      categoryCodeToSidMap: {},
      categoryCodeFormatMap: {},
      currentNodeId: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        categoryNameInput: null,
        specification: null,
      },
      materialsList: [],
      total: 0,
      loading: true,
      selectedRows: []
    }
  },
  watch: {
    /**
     * 监听选中的物料编码变化，强制同步表格选中状态
     */
    selectedMaterialCodes: {
      immediate: true,
      deep: true,
      handler(val) {
        console.log('选择器接收的选中编码:', val)
        if (!val || !val.length || !this.materialsList.length) return
        
        this.$nextTick(() => {
          if (this.$refs.table) {
            // 先清空所有选中状态
            this.$refs.table.clearSelection()
            
            // 统一编码格式后再匹配
            const formattedCodes = val.map(code => code.trim().toUpperCase())
            // 重新选中指定编码的物料
            this.materialsList.forEach(row => {
              const rowCode = row.materialCode.trim().toUpperCase()
              if (formattedCodes.includes(rowCode)) { 
                this.$refs.table.toggleRowSelection(row, true)
              }
            })
          }
        })
      }
    },
    defaultCategoryCodes: {
      immediate: true,
      handler(val) {
        if (val && val.length && this.categoryTreeData.length) {
          this.$nextTick(() => {
            this.selectCategoryNodes(val)
          })
        }
      }
    }
  },
  async created() {
    await Promise.all([
      this.getCategoryTreeData(),
      this.getCategoryList()
    ])
    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 = {}
          this.categoryCodeFormatMap = {}
          
          response.rows.forEach(item => {
            if (item.isUsed !== 0 && item.isUsed !== '0') {
              const code = item.categoryCode
              this.categoryMap[code] = item.categoryName
              
              // 格式化分类编码
              let formattedCode = code
              if (code && code.length === 6) {
                formattedCode = `${code.substring(0, 4)}-${code.substring(4)}`
              } else if (code && code.length === 8) {
                formattedCode = `${code.substring(0, 4)}-${code.substring(4, 6)}-${code.substring(6)}`
              }
              this.categoryCodeFormatMap[code] = formattedCode
              
              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)
          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') 
          : item.parentId == 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 formattedCode = this.categoryCodeFormatMap[node.categoryCode]
          if (formattedCode) {
            this.categoryCodeToSidMap[formattedCode] = 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] || `${this.categoryCodeFormatMap[item.categoryCode] || item.categoryCode}（未匹配分类）`
        }))
        this.total = response.total
        console.log('物料选择器加载列表:', this.materialsList)
        
        // 强制同步选中状态
        this.$nextTick(() => {
          if (this.selectedMaterialCodes.length && this.$refs.table) {
            this.$refs.table.clearSelection()
            const formattedCodes = this.selectedMaterialCodes.map(code => code.trim().toUpperCase())
            this.materialsList.forEach(row => {
              const rowCode = row.materialCode.trim().toUpperCase()
              if (formattedCodes.includes(rowCode)) {
                this.$refs.table.toggleRowSelection(row, true)
              }
            })
          }
        })
      }).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,
        materialCode: null,
        materialName: null,
        sapNo: 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) {
      this.selectedRows = selection
      
      const categoryCodes = [...new Set(selection.map(item => item.categoryCode).filter(c => c))]
      const formattedCategoryIds = categoryCodes.map(code => this.categoryCodeFormatMap[code] || code)
      
      const selectionData = {
        materialCodes: selection.map(item => item.materialCode || ''),
        names: selection.map(item => item.materialName || ''),
        formattedCategoryIds: formattedCategoryIds
      }
      
      console.log('选择器选中数据:', selectionData)
      this.$emit('selection-change', selectionData)
      this.$emit('change', selectionData.materialCodes)
      this.$emit('input', selectionData.materialCodes)
    },
    
    handleRowClick(row) {
      if (!this.multiple) {
        this.$refs.table.clearSelection()
        this.$refs.table.toggleRowSelection(row, true)
        
        const categoryCode = row.categoryCode || ''
        const formattedCategoryId = this.categoryCodeFormatMap[categoryCode] || categoryCode
        
        const selectionData = {
          materialCodes: [row.materialCode || ''],
          names: [row.materialName || ''],
          formattedCategoryIds: [formattedCategoryId]
        }
        
        this.$emit('selection-change', selectionData)
        this.$emit('input', selectionData.materialCodes)
        this.$emit('select', row.materialCode)
      }
    },
    
    getSelection() {
      const categoryCodes = [...new Set(this.selectedRows.map(item => item.categoryCode).filter(c => c))]
      const formattedCategoryIds = categoryCodes.map(code => this.categoryCodeFormatMap[code] || code)
      
      return {
        materialCodes: this.selectedRows.map(item => item.materialCode || ''),
        names: this.selectedRows.map(item => item.materialName || ''),
        formattedCategoryIds: formattedCategoryIds
      }
    },
    
    getSelectedMaterials() {
      return this.selectedRows.map(item => item.materialCode || '')
    }
  }
}
</script>

<style scoped>
.material-selector-container {
  height: 100%;
  min-height: 500px;
}
.custom-tree-node {
  font-size: 14px;
}
</style>