<template>
  <div class="app-container">
    <PageTitle>
      <template #buttons>
       
        <el-button
          type="primary"
          plain
          size="medium"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['inventory:materials_category:add']"
        >新增</el-button>
      
        <el-button
          type="info"
          plain
          size="medium"
          icon="el-icon-sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      
        <el-button
          type="warning"
          plain
          size="medium"
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['inventory:materials_category:export']"
        >导出</el-button>
            
      </template>
    </PageTitle>

    <div class="page-container-noback flex1">
      <div class="flex-container flex1" style="min-height: 200px;overflow: hidden;">
        <div class="card-container shadow" style="overflow: auto;min-width: 16%;">
          <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%;"
          />
        </div>
        <div class="card-container shadow flex1 right-card flex-container" style="flex-direction: column;padding: 20px;min-height: 200px;">

          <page-wrapper-search 
            :model="queryParams" 
            ref="queryForm" 
            size="small" 
            @search="handleQuery"
            @reset="resetQuery"
          >
          <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>
          </page-wrapper-search>

          <!-- 树形数据表格 -->
          <div style="flex: 1;min-height: 200px;">
            <el-table 
              ref="treeTable"
              v-loading="loading" 
              :data="currentTreeNodeData" 
              height="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" 
                
                fixed="left"
              />
              <el-table-column label="物料分类编码" align="center" prop="categoryCode"  />
              <el-table-column label="排序" align="center" prop="sortNo" width="80" />
              <el-table-column label="创建时间" align="center" prop="createTime">
                <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">
                <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" fixed="right">
                <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>
      </div>
    </div>




    <!-- 添加/修改对话框 -->
    <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>
      <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,
      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,
        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: {
    startTimer() {
      setTimeout(() => {
        this.message = "更新内容"; 
      }, 800);
    },
    /** 查询分类树结构 */
    getCategoryOptions() {
      this.loadingTree = true
      categoryTreeSelect().then(response => {
        this.categoryOptions = response.data
        this.loadingTree = false
      }).catch(() => {
        this.loadingTree = false
      })
    },

    /** 处理树节点点击 */
    handleTreeClick(data) {
      if (!data || !data.sid) return;
      this.currentNodeId = String(data.sid);
      // 查找根节点并筛选分支数据
      const rootNode = this.findRootNode(data.sid, this.categoryOptions);
      if (rootNode) {
        
        this.filterRootBranchData(rootNode.sid);
        // 自动展开到当前节点
        this.expandToNode(data.sid);
      }
    },

    /** 查找根节点 */
    findRootNode(nodeId, treeData) {
      const findNode = (nodes, id) => {
        for (const node of nodes) {
          if (String(node.sid) === String(id)) {
            if (!node.parentId || node.parentId === 0) return node;
            return findNode(treeData, node.parentId);
          }
          if (node.children && node.children.length) {
            const found = findNode(node.children, id);
            if (found) return found;
          }
        }
        return null;
      };
      return findNode(treeData, nodeId);
    },

    /** 筛选根节点分支数据 */
    filterRootBranchData(rootNodeId) {
      // 获取根分支所有节点ID
      const branchIds = this.getBranchNodeIds(this.categoryOptions, rootNodeId);
      
      // 筛选数据并构建树形
      const filteredData = this.materials_categoryList.filter(item => 
        branchIds.includes(String(item.id))
      );
      this.currentTreeNodeData = this.buildTree(filteredData);
    },

    /** 获取分支所有节点ID */
    getBranchNodeIds(treeData, nodeId) {
      const ids = [];
      const collectIds = (nodes, targetId) => {
        for (const node of nodes) {
          if (String(node.sid) === String(targetId)) {
            ids.push(String(node.sid));
            if (node.children) this.collectChildIds(node.children, ids);
            return true;
          }
          if (node.children && collectIds(node.children, targetId)) {
            ids.push(String(node.sid));
            return true;
          }
        }
        return false;
      };
      collectIds(treeData, nodeId);
      return ids;
    },

    /** 收集子节点ID */
    collectChildIds(children, ids) {
      children.forEach(child => {
        ids.push(String(child.sid));
        if (child.children) this.collectChildIds(child.children, ids);
      });
    },

    /** 构建树形结构 */
    buildTree(data) {
      const map = {};
      const roots = [];
      
      // 创建节点映射
      data.forEach(item => {
        map[item.id] = { ...item, children: [] };
      });
      
      // 构建父子关系
      data.forEach(item => {
        if (item.parentId && map[item.parentId]) {
          map[item.parentId].children.push(map[item.id]);
        } else {
          roots.push(map[item.id]);
        }
      });
      
      return roots;
    },

    /** 展开到指定节点 */
    expandToNode(targetId) {
      const treeTable = this.$refs.treeTable;
      if (!treeTable || !this.currentTreeNodeData.length) return;

      const expandRecursive = (data, targetId, parents = []) => {
        for (const item of data) {
          if (String(item.id) === String(targetId)) {
            parents.forEach(p => treeTable.toggleRowExpansion(p, true));
            treeTable.toggleRowExpansion(item, true);
            return true;
          }
          if (item.children && expandRecursive(item.children, targetId, [...parents, item])) {
            return true;
          }
        }
        return false;
      };

      this.$nextTick(() => {
        expandRecursive(this.currentTreeNodeData, targetId);
      });
    },

    /** 转换treeselect数据结构 */
    normalizer(node) {
      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);
        
        // 初始化显示全部数据或当前节点数据
        if (!this.currentNodeId) {
          this.currentTreeNodeData = this.buildTree(this.materials_categoryList);
        } else {
          const rootNode = this.findRootNode(this.currentNodeId, this.categoryOptions);
          if (rootNode) this.filterRootBranchData(rootNode.sid);
        }
        
        this.loading = false;
        this.$emit("list-loaded", { list: response.rows, total: response.rows.length });
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.currentNodeId = null;
      this.getList();
    },

    /** 重置搜索条件 */
    resetQuery() {
      // this.$refs["queryRef"].resetFields();
      this.queryParams = {
        pageNum: 1,
        pageSize: 1000,
        categoryCode: null,
        categoryName: null,
        parentId: null,
        isUsed: 1,
        ...this.initQuery
      };
      this.currentNodeId = null;
      if (this.$refs.treeComponent?.resetTree) {
        this.$refs.treeComponent.resetTree();
      }
      this.getList();
    },

    /** 展开/折叠操作 */
   /** 展开/折叠操作 */
    toggleExpandAll() {
      this.isExpandAll = !this.isExpandAll;
      const treeTable = this.$refs.treeTable;
      if (!treeTable) return;

      // 递归处理所有节点的展开/折叠
      const toggleNodes = (data, expand) => {
        data.forEach(item => {
          // 切换当前节点展开状态
          treeTable.toggleRowExpansion(item, expand);
          // 递归处理子节点
          if (item.children && item.children.length) {
            toggleNodes(item.children, expand);
          }
        });
      };

      // 从根节点开始处理
      this.$nextTick(() => {
        toggleNodes(this.currentTreeNodeData, this.isExpandAll);
      });
    },

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

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

    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      const _id = row ? row.id : this.ids;
      console.log(_id)
      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(() => {
            const type = this.form.id ? "update" : "add";
            this.$modal.msgSuccess(`${type === "add" ? "新增" : "修改"}成功`);
            this.dialogOpen = false;
            
            // 重新加载数据
            Promise.all([
              this.getCategoryOptions(),
              new Promise(resolve => {
                this.getList();
                setTimeout(resolve, 100);
              })
            ]).then(() => {
              if (type === "add" && this.form.parentId) {
                this.selectTreeNode(this.form.parentId);
              } else if (this.currentNodeId) {
                this.selectTreeNode(this.currentNodeId);
              }
            });
            
            this.$emit("form-submit", { type, data: this.form });
          });
        }
      });
    },

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

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

    /** 对话框关闭事件 */
    handleDialogClose() {
      this.dialogOpen = false
      this.$emit("dialog-close");
    },

    /** 选择指定树节点 */
    selectTreeNode(nodeId) {
      const findNode = (nodes) => {
        for (const node of nodes) {
          if (String(node.sid) === String(nodeId)) return node;
          if (node.children) {
            const found = findNode(node.children);
            if (found) return found;
          }
        }
        return null;
      };
      
      const treeNode = findNode(this.categoryOptions);
      if (treeNode) this.handleTreeClick(treeNode);
    }
  }
}
</script>

<style lang="scss" scoped>
.right-card {
  margin-left: var(--container-pd);
}
</style>