<template>
  <div class="app-container" style="overflow: hidden;">
    <splitpanes class="default-theme" style="height: 100%;">
      <!-- 树结构：左侧面板 -->
      <pane size="16" style="height: 100%; overflow: auto;">
        <TreeComponent
          :tree-data="categoryOptions"
          :tree-props="defaultProps"
          :node-key="nodeKey"
          :show-search="true"
          search-placeholder="请输入分类名称"
          :default-expand-all="true"
          :highlight-current="true"
          :loading="loadingTree"
          @node-click="handleTreeClick"
          style="height: 100%;"
        />
      </pane>

      <!-- 物料分类管理：右侧面板 -->
      <pane size="84" style="height: 100%; overflow: auto;">
        <div style="padding: 10px; height: 100%; display: flex; flex-direction: column;">
          <!-- 搜索表单 -->
          <el-form 
            :model="queryParams" 
            ref="queryRef" 
            :inline="true" 
            v-show="showSearch" 
            label-width="128px"
            style="margin-bottom: 10px;"
          >
            <el-form-item label="物料分类编码" prop="categoryCode">
              <el-input
                v-model="queryParams.categoryCode"
                placeholder="请输入物料分类编码"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料分类名称" prop="categoryName">
              <el-input
                v-model="queryParams.categoryName"
                placeholder="请输入物料分类名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 操作按钮 -->
          <el-row :gutter="10" class="mb8" style="margin-bottom: 10px;">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                @click="handleAdd"
                v-hasPermi="['inventory:materials_category:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['inventory:materials_category:edit']"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['inventory:materials_category:remove']"
              >删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-sort"
                @click="toggleExpandAll"
              >展开/折叠</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                @click="handleExport"
                v-hasPermi="['inventory:materials_category:export']"
              >导出</el-button>
            </el-col>
            <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <!-- 树形数据表格（移除分页） -->
          <div style="flex: 1; overflow: auto;">
            <el-table 
              ref="treeTable"
              v-if="refreshTable"
              v-loading="loading" 
              :data="currentTreeNodeData" 
              @selection-change="handleSelectionChange"
              style="width: 100%;"
              row-key="id"
              :default-expand-all="isExpandAll"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column 
                label="物料分类名称" 
                align="center" 
                prop="categoryName" 
                min-width="200"
              />
              <el-table-column label="物料分类编码" align="center" prop="categoryCode" width="200" />
              <el-table-column label="排序" align="center" prop="sortNo" width="100" />
              <el-table-column label="创建时间" align="center" prop="createTime" width="200">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="修改时间" align="center" prop="updateTime" width="200">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    link
                    type="text"
                    icon="el-icon-plus"
                    @click="handleAdd(scope.row.id)"
                    v-hasPermi="['inventory:materials_category:add']"
                  >新增下级</el-button>
                  <el-button 
                    size="mini"
                    link 
                    type="text" 
                    icon="el-icon-edit" 
                    @click="handleUpdate(scope.row)" 
                    v-hasPermi="['inventory:materials_category:edit']"
                  >修改</el-button>
                  <el-button 
                    size="mini"
                    link 
                    type="text" 
                    icon="el-icon-delete" 
                    @click="handleDelete(scope.row)" 
                    v-hasPermi="['inventory:materials_category:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </pane>
    </splitpanes>

    <!-- 添加/修改对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogOpen" 
      width="600px" 
      append-to-body
      @close="handleDialogClose"
    >
      <el-form 
        ref="materials_categoryRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
      >
        <el-form-item label="上级分类" prop="parentId" v-if="form.id && form.parentId">
          <treeselect 
            v-model="form.parentId" 
            :options="categoryOptions" 
            :normalizer="normalizer" 
            placeholder="选择上级分类"
            :disabled="!!form.id"
          />
        </el-form-item>
        <el-form-item label="物料分类编码" prop="categoryCode">
          <el-input v-model="form.categoryCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input v-model="form.sortNo" placeholder="请输入排序" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="isUsed">
          <el-radio-group v-model="form.isUsed">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleDialogClose">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { 
  listMaterials_category, 
  getMaterials_category, 
  delMaterials_category, 
  addMaterials_category, 
  updateMaterials_category,
  categoryTreeSelect
} from "@/api/inventory/materials_category"
import { Splitpanes, Pane } from 'splitpanes'
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import 'splitpanes/dist/splitpanes.css'
import Treeselect from "@riophae/vue-treeselect"
import TreeComponent from "./treeComponent.vue"

export default {
  name: "MaterialsCategory",
  components: { Treeselect, Splitpanes, Pane, TreeComponent },
  dicts: ['sys_normal_disable'],
  props: {
    initQuery: {
      type: Object,
      default: () => ({})
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dialogFormData: {
      type: Object,
      default: () => ({})
    },
    dialogTitle: {
      type: String,
      default: "新增物料分类"
    }
  },
  data() {
    return {
      materials_categoryList: [],
      currentTreeNodeData: [],
      loading: true,
      loadingTree: false,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      dialogOpen: false,
      categoryOptions: [], 
      defaultProps: { 
        children: 'children',
        label: 'label',
        value: 'sid'
      },
      nodeKey: 'sid',
      currentNodeId: null,
      isExpandAll: true,
      refreshTable: true,
      form: {
        id: null,
        categoryCode: null,
        categoryName: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null,
        parentId: null,
        isUsed: 1
      },
      queryParams: {
        pageNum: 1,
        pageSize: 1000, // 设置为较大的值，一次性获取所有数据
        categoryCode: null,
        categoryName: null,
        sortNo: null,
        createTime: null,
        updateTime: null,
        parentId: null,
        isUsed: 1
      },
      rules: {
        categoryCode: [{required: true, message:'请输入物料分类编码',trigger:'blur'}],
        categoryName: [{required: true, message:'请输入物料分类名称', trigger:'blur'}]
      }
    }
  },
  watch: {
    dialogVisible: {
      immediate: true,
      handler(val) {
        this.dialogOpen = val
      }
    },
    dialogFormData: {
      immediate: true,
      handler(val) {
        this.form = { ...val }
      }
    },
    initQuery: {
      immediate: true,
      handler(val) {
        this.queryParams = { ...this.queryParams, ...val }
        this.getList()
      }
    }
  },
  created() {
    this.getList()
    this.getCategoryOptions()
  },
  methods: {
    /** 查询分类树结构 */
    getCategoryOptions() {
      this.loadingTree = true
      categoryTreeSelect().then(response => {
        this.categoryOptions = response.data
        this.loadingTree = false
      }).catch(() => {
        this.loadingTree = false
      })
    },

    /** 处理树节点点击 */
    /** 处理树节点点击 */
    handleTreeClick(data) {
      console.log('点击树节点:', data)
      // 确保数据存在且有sid属性
      if (!data || !data.sid) {
        console.warn('无效的节点数据，缺少sid属性');
        return;
      }
      
      // 确保使用字符串类型的id进行操作，避免类型转换问题
      this.currentNodeId = String(data.sid)
      console.log(this.categoryOptions)
      // 1. 找到当前节点的根节点
      const rootNode = this.findRootNode(this.currentNodeId, this.categoryOptions);
      
      if (rootNode) {
        // 2. 筛选根节点的完整分支数据
        const rootNodeIdStr = String(rootNode.sid);
        this.filterRootBranchData(this.materials_categoryList, rootNodeIdStr);
        
        // 3. 自动展开到当前节点
          this.$nextTick(() => {
            // 尝试展开节点，即使数据可能尚未完全准备好
            // expandToNode方法内部已经有适当的错误处理
            this.expandToNode(this.currentNodeId);
          });
      }
    },
    
    /** 查找表格数据中的节点ID */
    findTableNodeId(treeNode) {
      if (!treeNode) return null
      
      // 首先在materials_categoryList中查找对应的节点
      const tableNode = this.materials_categoryList.find(item => 
        item.categoryCode === treeNode.categoryCode || 
        item.categoryName === treeNode.label ||
        item.id === treeNode.id
      )
      
      return tableNode ? tableNode.id : null
    },

    /** 筛选根节点的完整分支数据 */
    filterRootBranchData(allData, rootNodeId) {
      // 确保rootNodeId为字符串类型
      const rootNodeIdStr = String(rootNodeId);
      
      // 获取根节点分支的所有节点ID（包含根节点和所有子节点）
      const branchNodeIds = this.getAllChildNodeIds(allData, rootNodeIdStr);
      
      // 筛选出根分支的所有数据
      // 使用字符串比较避免类型转换问题
      const filteredData = allData.filter(item => 
        branchNodeIds.some(branchId => String(branchId) === String(item.id))
      );
      
      // 构建树形结构并赋值给表格
      this.currentTreeNodeData = this.handleTree(filteredData, "id");
    },
    
    /** 展开到指定节点 */
    expandToNode(nodeId) {
      const treeTable = this.$refs.treeTable;
      // 增加对treeTable.store.nodesMap的检查
      if (!treeTable || !treeTable.store || !treeTable.store.nodesMap) {
        console.log(treeTable)
        console.warn('树表格组件未完全初始化或nodesMap不存在');
        return;
      }
      
      // 确保nodeId为字符串类型
      const nodeIdStr = String(nodeId);
      
      // 找到节点路径
      const nodePath = this.findNodePath(this.currentTreeNodeData, nodeIdStr);
      
      // 逐级展开
      if (nodePath && nodePath.length > 0) {
        nodePath.forEach(id => {
          const idStr = String(id);
          try {
            // 安全地查找节点，避免访问不存在的属性
            const node = treeTable.store.nodesMap[idStr] || 
                        treeTable.store.nodesMap[id];
            if (node && typeof node === 'object' && node.expanded === false && node.expandable) {
              node.expanded = true;
            }
          } catch (error) {
            console.warn(`展开节点时出错: ${error.message}, 节点ID: ${idStr}`);
          }
        });
      }
    },
    
    /** 查找节点路径 */
    findNodePath(treeData, targetId, path = []) {
      // 确保targetId为字符串类型
      const targetIdStr = String(targetId);
      
      for (const item of treeData) {
        if (String(item.id) === targetIdStr) {
          return [...path, item.id];
        }
        
        if (item.children && item.children.length) {
          const found = this.findNodePath(item.children, targetIdStr, [...path, item.id]);
          if (found) return found;
        }
      }
      return null;
    },

    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.sid,
        label: node.label,
        children: node.children
      }
    },

    /** 查询物料分类列表 */
    /** 查询物料分类列表 */
    getList() {
      this.loading = true
      listMaterials_category(this.queryParams).then(response => {
        this.materials_categoryList = response.rows.filter(item => item.isUsed !== 0 && item.isUsed !== '0');
        
        // 如果没有选中树节点，显示所有数据
        if (!this.currentNodeId) {
          this.currentTreeNodeData = this.handleTree(this.materials_categoryList, "id");
        } else {
          // 如果有选中的树节点，保持当前显示
          // 直接使用 currentNodeId（sid）作为表格数据的 id
          const rootNode = this.findRootNode(this.currentNodeId, this.categoryOptions);
          if (rootNode) {
            // rootNode.sid 就是表格中的 id
            this.filterRootBranchData(this.materials_categoryList, rootNode.sid);
          }
        }
        
        this.loading = false
        this.$emit("list-loaded", {
          list: response.rows,
          total: response.rows.length
        })
      })
    },

    /** 选择指定的树节点 */
    selectTreeNode(nodeId) {
      if (!nodeId) return;
      
      // 确保nodeId为字符串类型
      const nodeIdStr = String(nodeId);
      
      // 查找对应的树节点
      const findTreeNode = (nodes) => {
        for (const node of nodes) {
          if (String(node.sid) === nodeIdStr) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findTreeNode(node.children);
            if (found) return found;
          }
        }
        return null;
      };
      
      // 在categoryOptions中查找节点
      const treeNode = findTreeNode(this.categoryOptions);
      
      if (treeNode) {
        // 如果找到节点，触发点击事件
        this.handleTreeClick(treeNode);
      } else {
        console.warn(`未找到ID为${nodeIdStr}的树节点`);
        // 如果未找到节点，可能是根节点已变更，尝试找到新的根节点
        const rootNode = this.findRootNode(nodeIdStr, this.materials_categoryList);
        if (rootNode) {
          this.filterRootBranchData(this.materials_categoryList, rootNode.id);
        }
      }
    },
    
    /** 获取节点及其所有子节点的ID（基于表格数据） */
    getAllChildNodeIds(tableData, nodeId) {
      const result = [];
      // 确保nodeId为字符串类型
      const nodeIdStr = String(nodeId);
      
      // 递归查找所有子节点
      const findChildren = (parentId) => {
        const parentIdStr = String(parentId);
        // 使用字符串比较确保兼容性
        const children = tableData.filter(item => 
          item.parentId && String(item.parentId) === parentIdStr
        );
        children.forEach(child => {
          result.push(child.id);
          findChildren(child.id);
        });
      };
      
      // 添加当前节点
      // 使用字符串比较查找当前节点
      const currentNode = tableData.find(item => String(item.id) === nodeIdStr);
      if (currentNode) {
        result.push(currentNode.id);
        findChildren(currentNode.id);
      }
      
      return result;
    },

    /** 查找当前节点的根节点 */
    findRootNode(nodeId, treeData) {
      // 确保nodeId为字符串类型
      const nodeIdStr = String(nodeId);
      
      // 首先找到当前节点
      const findNodeById = (nodes, id) => {
        // 检查nodes是否有效
        if (!nodes || !Array.isArray(nodes)) return null;
        
        for (const node of nodes) {
          // 确保比较时使用字符串类型，处理表格数据和树数据的不同字段名
          if (String(node.sid || node.id) === id) {
            return node;
          }
          if (node.children && node.children.length > 0) {
            const found = findNodeById(node.children, id);
            if (found) return found;
          }
        }
        return null;
      };
      
      const currentNode = findNodeById(treeData, nodeIdStr);
      
      if (!currentNode) return null;
      
      // 查找根节点（parentId为null或空或0）
      const findRoot = (node) => {
        if (!node) return null;
        
        // 检查多种可能的根节点条件
        const parentId = String(node.parentId || '');
        if (!parentId || parentId === '0' || parentId === 'null' || parentId === 'undefined') {
          return node;
        }
        
        const parentNode = findNodeById(treeData, parentId);
        // 如果找不到父节点，当前节点就是根节点
        console.log(parentNode)
        return parentNode ? findRoot(parentNode) : node;
      };
      
      return findRoot(currentNode);
    },

    /** 处理树形数据 */
    handleTree(data, id, parentId, children) {
      id = id || 'id'
      parentId = parentId || 'parentId'
      children = children || 'children'
      
      // 确保根节点筛选逻辑正确，处理各种可能的parentId值
      const rootNodes = data.filter(item => {
        const pId = item[parentId];
        return !pId || pId === null || pId === 0 || String(pId) === '0' || String(pId) === '';
      })
      
      const addChildren = (parent) => {
        // 使用字符串比较查找子节点，确保类型一致性
        const childNodes = data.filter(item => {
          return String(item[parentId]) === String(parent[id]);
        })
        
        if (childNodes.length > 0) {
          parent[children] = childNodes
          childNodes.forEach(child => addChildren(child))
        }
      }
      
      rootNodes.forEach(root => addChildren(root))
      return rootNodes
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.currentNodeId = null // 搜索时清除当前选中的节点
      this.getList()
    },

    /** 重置搜索条件 */
    resetQuery() {
      this.$refs["queryRef"].resetFields()
      this.queryParams = {
        pageNum: 1,
        pageSize: 1000,
        categoryCode: null,
        categoryName: null,
        sortNo: null,
        createTime: null,
        updateTime: null,
        parentId: null,
        ...this.initQuery
      }
      // 重置时清除当前选中的节点
      this.currentNodeId = null
      // 重置左侧树的选择状态
      if (this.$refs.treeComponent && this.$refs.treeComponent.resetTree) {
        this.$refs.treeComponent.resetTree();
      }
      this.getList()
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
        // 手动设置展开/折叠
        const treeTable = this.$refs.treeTable;
        if (treeTable && treeTable.store) {
          Object.keys(treeTable.store.nodesMap).forEach(key => {
            const node = treeTable.store.nodesMap[key];
            if (node && node.expandable) {
              node.expanded = this.isExpandAll;
            }
          });
        }
      })
    },

    /** 多选框选中事件 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.$emit("selection-change", selection)
    },

    /** 新增按钮操作 */
    handleAdd(parentId) {
      this.form = {
        id: null,
        categoryCode: null,
        categoryName: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null,
        parentId: parentId || null,
        isUsed: 1
      }
      this.dialogOpen = true
      this.$emit("dialog-open", { type: "add", form: this.form })
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      const _id = row ? row.id : this.ids
      getMaterials_category(_id).then(response => {
        this.form = response.data
        this.dialogOpen = true
        this.$emit("dialog-open", { type: "edit", form: this.form })
      })
    },

    /** 提交表单 */
    submitForm() {
      this.$refs["materials_categoryRef"].validate(valid => {
        if (valid) {
          const submitPromise = this.form.id 
            ? updateMaterials_category(this.form) 
            : addMaterials_category(this.form)
          
          submitPromise.then(response => {
            const type = this.form.id ? "update" : "add"
            this.$modal.msgSuccess(`${type === "add" ? "新增" : "修改"}成功`)
            this.dialogOpen = false
            
            // 保存当前节点ID，用于数据重新加载后恢复选择
            const currentNodeIdBeforeReload = this.currentNodeId;
            const isAddChild = type === "add" && this.form.parentId;
            
            // 重新加载数据
            Promise.all([
              // 先重新加载树数据
              new Promise(resolve => {
                this.getCategoryOptions();
                // 延迟一下确保树数据加载完成
                setTimeout(() => resolve(), 100);
              }),
              // 再重新加载列表数据
              new Promise(resolve => {
                this.getList();
                // 延迟一下确保列表数据加载完成
                setTimeout(() => resolve(), 100);
              })
            ]).then(() => {
              // 数据加载完成后，恢复或更新选择
              this.$nextTick(() => {
                if (isAddChild) {
                  // 新增下级后，选择父节点
                  this.selectTreeNode(this.form.parentId);
                } else if (currentNodeIdBeforeReload) {
                  // 修改后，保持当前选择
                  this.selectTreeNode(currentNodeIdBeforeReload);
                }
              });
            });
            
            this.$emit("form-submit", {
              type,
              data: this.form,
              response
            })
          })
        }
      })
    },

    /** 删除操作 */
    handleDelete(row) {
      const _ids = row ? row.id : this.ids
      this.$modal.confirm(`是否确认删除物料分类编号为"${_ids}"的数据项？`).then(() => {
        return delMaterials_category(_ids)
      }).then(() => {
        // 重新加载数据
        this.getList()
        this.getCategoryOptions()
        this.$modal.msgSuccess("删除成功")
        this.$emit("item-delete", { ids: _ids })
      }).catch(() => {})
    },

    /** 导出操作 */
    handleExport() {
      this.download('inventory/materials_category/export', {
        ...this.queryParams
      }, `materials_category_${new Date().getTime()}.xlsx`)
      this.$emit("export-data", this.queryParams)
    },

    /** 对话框关闭事件 */
    handleDialogClose() {
      this.$refs["materials_categoryRef"]?.resetFields()
      this.$emit("dialog-close")
    },

    /** 表单重置 */
    resetForm() {
      this.form = {
        id: null,
        categoryCode: null,
        categoryName: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null,
        parentId: null,
        isUsed: 1
      }
      this.$refs["materials_categoryRef"]?.resetFields()
    }
  }
}
</script>

<style scoped>
.app-container {
  height: 100%;
}

.mb8 {
  margin-bottom: 8px;
}

/* 添加滚动条样式 */
.el-table {
  max-height: 100%;
  overflow-y: auto;
}
</style>