<template>
  <div class="material-select-component">
    <el-dialog :title="title" :visible.sync="visible" width="900px" append-to-body>
      <!-- 左右分栏布局 -->
      <div class="split-layout">
        <!-- 左侧分类树 -->
        <div class="left-panel">
          <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="handleCategoryChange"
          >
            <!-- 自定义节点内容插槽 -->
            <template #node-content="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </TreeComponent>
        </div>
        
        <!-- 右侧物料列表 -->
        <div class="right-panel">
          <!-- 物料列表 -->
          <el-table v-loading="loading" :data="materialsList" @selection-change="handleSelectionChange" :scroll-x="true">
            <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" />
            <el-table-column label="物料名称" align="center" prop="materialName" />
            <el-table-column label="SAP物料号" align="center" prop="sapNo" />
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="计量单位" align="center" prop="materialUnit" />
          </el-table>
          
          <!-- 分页 -->
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
      
      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmSelection">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterials } from "@/api/inventory/materials"
import { listMaterials_category } from "@/api/inventory/materials_category"
import Pagination from "@/components/Pagination"
import TreeComponent from './treeComponent.vue'

export default {
  name: "MaterialSelectComponent",
  components: {
    Pagination,
    TreeComponent
  },
  props: {
    // 对话框标题
    title: {
      type: String,
      default: "选择物料"
    },
    // 是否显示对话框
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 树相关数据
      categoryTreeData: [],
      treeProps: {
        children: 'children',
        label: 'label',
        value: 'sid'
      },
      nodeKey: 'sid',
      loadingTree: false,
      
      // 分类映射
      categoryMap: {},
      // 选中的分类
      selectedCategory: null,
      
      // 加载状态
      loading: false,
      // 总条数
      total: 0,
      // 物料列表
      materialsList: [],
      // 选中的物料
      selectedMaterials: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryCode: null
      }
    }
  },
  watch: {
    // 监听对话框显示状态，当显示时加载物料列表和分类树
    visible(newVal) {
      if (newVal) {
        this.getCategoryTreeData()
        this.getList()
      }
    }
  },
  methods: {
    /** 获取分类树数据 */
    async getCategoryTreeData() {
      this.loadingTree = true
      try {
        // 调用物料分类列表API获取所有分类
        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.buildCategoryMap(activeCategories)
        }
      } catch (error) {
        console.error('获取分类树数据失败:', error)
      } finally {
        this.loadingTree = false
      }
    },
    
    /** 构建树形结构 */
    buildTreeData(list, parentId = null) {
      const result = list
        .filter(item => {
          if (parentId === null) {
            // 根节点：parentId为null、0或空
            return !item.parentId || item.parentId === 0 || item.parentId === '0'
          } else {
            // 子节点：parentId匹配
            return item.parentId == parentId
          }
        })
        .map(item => {
          const children = this.buildTreeData(list, item.id)
          return {
            ...item,
            sid: String(item.id),
            label: item.categoryName,
            children: children.length > 0 ? children : undefined
          }
        })
      
      return result
    },
    
    /** 构建分类映射 */
    buildCategoryMap(categories) {
      this.categoryMap = {}
      categories.forEach(item => {
        this.categoryMap[item.id] = item.categoryName
      })
    },
    
    /** 处理分类选择变化 */
    handleCategoryChange(data) {
      this.selectedCategory = data
      // 更新查询参数，按选中的分类筛选物料
      this.queryParams.categoryCode = data ? data.categoryCode : null
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    /** 获取物料列表 */
    async getList() {
      this.loading = true
      try {
        const response = await listMaterials(this.queryParams)
        this.materialsList = response.rows
        this.total = response.total
      } catch (error) {
        console.error('获取物料列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    /** 处理选择变化 */
    handleSelectionChange(selection) {
      this.selectedMaterials = selection
    },
    
    /** 确认选择 */
    confirmSelection() {
      // 提取选中物料的uuid和名称，用逗号隔开
      const uuids = this.selectedMaterials
        .map(item => item.uuid || item.id) // 兼容uuid和id字段
        .join(',')
      
      const names = this.selectedMaterials
        .map(item => item.materialName) // 提取物料名称
        .join(',')
      
      // 触发选择确认事件，将选中的uuid和名称传递给父组件
      this.$emit('selection-confirm', uuids, names)
      
      // 关闭对话框
      this.$emit('update:visible', false)
    },
    
    /** 取消选择 */
    cancel() {
      // 清空选择
      this.selectedMaterials = []
      this.selectedCategory = null
      this.queryParams.categoryCode = null
      
      // 触发取消事件
      this.$emit('selection-cancel')
      
      // 关闭对话框
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
.material-select-component {
  .dialog-footer {
    text-align: right;
  }
  
  .split-layout {
    display: flex;
    height: 500px;
    gap: 10px;
    
    .left-panel {
      width: 250px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      overflow: hidden;
      
      .tree-container {
        height: 100%;
      }
    }
    
    .right-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .el-table {
        flex: 1;
        overflow: auto;
      }
      
      .pagination {
        margin-top: 10px;
      }
    }
  }
}
</style>