<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="物料编码" 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="materialTable"
            v-loading="loading" 
            :data="materialsList" 
            @selection-change="handleSelectionChange" 
            :scroll-x="true"
            :row-key="row => row.id"
            @row-click="handleRowClick"
          >
            <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" >
              <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（可选）
    value: {
      type: [Array, Number, String],
      default: () => []
    },
    // 是否允许多选
    multiple: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      categoryTreeData: [],
      treeProps: { children: 'children', label: 'label', value: 'sid' },
      nodeKey: 'sid',
      loadingTree: false,
      categoryMap: {},
      categoryNameToCodeMap: {},
      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: {
    value: {
      immediate: true,
      handler(val) {
        // 初始化选中状态（如果需要）
        if (val && val.length) {
          this.$nextTick(() => {
            if (this.$refs.table) {
              this.materialsList.forEach(row => {
                if (val.includes(row.id)) {
                  this.$refs.table.toggleRowSelection(row, true)
                }
              })
            }
          })
        }
      }
    }
  },
  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 = {};
          response.rows.forEach(item => {
            if (item.isUsed !== 0 && item.isUsed !== '0') {
              this.categoryMap[item.categoryCode] = item.categoryName;
              if (!this.categoryNameToCodeMap[item.categoryName]) {
                this.categoryNameToCodeMap[item.categoryName] = item.categoryCode;
              } else if (!Array.isArray(this.categoryNameToCodeMap[item.categoryName])) {
                this.categoryNameToCodeMap[item.categoryName] = [this.categoryNameToCodeMap[item.categoryName], item.categoryCode];
              } else {
                this.categoryNameToCodeMap[item.categoryName].push(item.categoryCode);
              }
            }
          });
        }
      } 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);
        }
      } 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
        }));
    },
    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;
      }).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 selectedData = selection.map(item => ({
        id: item.id,
        materialCode: item.materialCode,
        materialName: item.materialName,
        // specification: item.specification,  // 可选：规格型号
        // materialUnit: item.materialUnit     // 可选：计量单位
      }));
      this.$emit('change', selectedData);  // 返回包含所需字段的对象
      this.$emit('input', selection.map(item => item.id));
    },
    handleRowClick(row) {
      if (!this.multiple) {
        // 单选模式下点击行直接选中并触发事件
        this.$refs.table.clearSelection();
        this.$refs.table.toggleRowSelection(row, true);
        this.$emit('input', row.id);
        this.$emit('select', row);
      }
    },
    // 提供外部调用的方法：获取选中的物料详情
    getSelectedMaterials() {
      return this.selectedRows;
    },
    // 清空复选框选择
    clearSelection() {
      if (this.$refs.materialTable) {
        this.$refs.materialTable.clearSelection(); // 直接清空表格选择
        this.selectedRows = []; // 同步清空选中数据
        this.$emit('change', []); // 通知父组件
        this.$emit('input', []); // 更新v-model绑定值
      }
    }
  }
}
</script>

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