<template>
  <div
    class="data-list"
    v-loading="tableLoading"
    element-loading-text="加载中..."
    element-loading-spinner="el-icon-loading"
  >
    <el-table
      ref="dataTable"
      :data="dataList"
      stripe
      lazy
      :load="loadData"
      row-key="id"
      :tree-props="{ children: 'child', hasChildren: 'hasChildren' }"
      show-overflow-tooltip
      style="width: 100%"
      header-row-class-name="headerBg"
      empty-text="没有分类信息"
    >
      <el-table-column prop="id" label="ID" width="180" />
      <el-table-column
        prop="name"
        label="分类名称"
        align="left"
        min-width="180"
      >
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" />
      <el-table-column prop="status" label="分类状态" align="center">
        <template #default="scope">
          <div v-if="scope.row.status == 5">启用</div>
          <div v-if="scope.row.status == 6">停用</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="300">
        <template #default="scope">
          <div class="btns">
            <el-button type="primary" size="small" @click="Subclass(scope.row)"
              ><svg-icon icon-class="edit" />创建子类</el-button
            >
            <el-button type="primary" size="small" @click="btnEdit(scope.row)"
              ><svg-icon icon-class="edit" />编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="btnDelete(scope.row.id)"
              ><svg-icon icon-class="delete" />删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="page-info">
      <el-pagination
        :currentPage="queryForm.page"
        :page-size="queryForm.pageSize"
        :total="recordCount"
        :page-count="pageTotal"
        background
        layout="prev, pager, next"
        @current-change="ChangePage"
      >
      </el-pagination>
    </div>

    <el-dialog
      :visible.sync="SubclassVisible"
      append-to-body
      v-el-drag-dialog
      width="50%"
      custom-class="prod-verify"
      title="创建子类"
      @closed="handleSubClosed"
    >
      <!--       <dataInfo
        :id="currentDataId"
        @onClose="onClose"
        ref="currentInfoRef"
        @onSearch="search"
      ></dataInfo> -->
      <el-card>
        <el-form :model="dataForm" ref="dataFormRef" label-width="120px">
          <!-- <el-form-item label="父级分类:">
            <el-select
              v-model="dataForm.parent_id"
              placeholder="请选择你级分类"
              size="large"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in parentList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="分类名称:">
            <el-input v-model="dataForm.name"></el-input>
          </el-form-item>
          <!-- <el-form-item label="分类介绍:">
           <el-input type="textarea" v-model="dataForm.intro"></el-input>
       </el-form-item> -->
          <el-form-item label="分类状态:">
            <el-select
              v-model="dataForm.status"
              placeholder="请选择分类状态"
              size="large"
              style="width: 100%"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
      <div style="text-align: right; margin-top: 20px">
        <el-button type="warning" @click="btnSave">确认保存</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogVisible"
      append-to-body
      v-el-drag-dialog
      width="50%"
      custom-class="prod-verify"
      title="编辑分类"
      @closed="handleDialogClosed"
    >
      <dataInfo
        :id="currentDataId"
        @onClose="onClose"
        ref="currentInfoRef"
        @onSearch="search"
      ></dataInfo>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchTemplateCategory,
  deleteTemplateCategory,
  createTemplateCategory,
  updateTemplateCategory,
  getTemplateCategoryInfo,
} from "@/api/template";
import dataInfo from "./dataInfo.vue";
import elDragDialog from "@/directive/el-drag-dialog";
import Vue from "vue";
export default {
  components: {
    dataInfo,
  },
  directives: { elDragDialog },
  props: {
    queryForm: {
      type: Object,
      default: () => {
        return {
          page: 1,
          pageSize: 10,
          name: "",
          parent_id: 0,
          sign: "",
        };
      },
    },
  },
  watch: {
    queryForm: {
      handler: function (val) {
        this.search();
      },
      immediate: true, //立即执行
      deep: true,
    },
  },
  data() {
    return {
      dialogVisible: false, //控制产品审核
      currentDataId: 0,
      recordCount: 0,
      pageTotal: 1,
      dataList: [],
      currentData: {},
      activeName: "base",
      currentCategory: [],
      tableLoading: false,
      dataForm: {
        id: 0,
        name: "",
        parent_id: 0,
        intro: "",
        status: 5,
      },
      parentList: [],
      statusOptions: [
        {
          value: "",
          label: "请选择状态",
        },
        {
          value: 5,
          label: "启用",
        },
        {
          value: 6,
          label: "停用",
        },
      ],
      SubclassVisible: false,
      expandedRows: new Set(),
    };
  },
  mounted() {
    this.search();
    this.initParentCategory();
  },
  methods: {
    /* 弹窗 */
    initParentCategory() {
      let _this = this;
      searchTemplateCategory({
        page: 1,
        pageSize: 999,
        parent_id: 0,
        status: 5,
      }).then((res) => {
        if (res.status != 200) return;
        _this.parentList.push({ id: 0, name: "父级分类" });
        /* for (var i = 0; i < res.data.dataList.length; i++) {
          _this.parentList.push({
            id: res.data.dataList[i].id,
            name: res.data.dataList[i].name,
          });
        } */
      });
    },
    //保存更新
    btnSave(e) {
      let _this = this;
      if (_this.dataForm.id > 0) {
        updateTemplateCategory(_this.dataForm).then((res) => {
          if (res.status != 200) return;
          _this.$message.success("模板类别信息更新成功");
          _this.SubclassVisible = false;
          _this.search();
          _this.refreshAndExpandParent();
        });
      } else {
        createTemplateCategory(_this.dataForm).then((res) => {
          if (res.status != 200) return;
          _this.$message.success("模板类别信息创建成功");
          _this.SubclassVisible = false;
          _this.search();
          _this.refreshAndExpandParent();
        });
      }
    },
    refreshAndExpandParent() {
      const parentId = this.dataForm.parent_id;
      this.expandedRows.add(parentId);
      this.search(); // 这里已经重新加载了数据
      this.$nextTick(() => {
        // 使用 $refs 来访问 el-table 组件
        const table = this.$refs.dataTable;
        if (table) {
          // 找到父行并展开
          const parentRow = this.dataList.find((row) => row.id === parentId);
          if (parentRow) {
            table.toggleRowExpansion(parentRow, true);
          }
        }
      });
    },

    //产品详情
    getInfo(id) {
      let _this = this;
      let par = {
        id: id,
      };
      getTemplateCategoryInfo(par).then((res) => {
        if (!res) return;
        if (res.status != 200) return;
        res.data.parent_id = Number(res.data.parent_id);
        _this.dataForm = res.data;
      });
    },

    onChangeStatus(e) {
      this.dataForm.status = e;
    },
    //修改分类信息
    onChangeCategory(e) {
      let _this = this;
      _this.dataForm.categoryId = e;
    },

    /* 创建子类 */
    Subclass(item) {
      this.dataForm.parent_id = item.id;
      //this.dataForm.child_count=item.child_count
      this.SubclassVisible = true;
    },
    handleSubClosed() {
      this.dataForm = {
        name: "",
        intro: "",
        status: 5,
      };
    },
    handleDialogClosed() {
      // 清空 dataInfo 组件内的表单
      if (this.$refs.dataInfoRef) {
        this.$refs.dataInfoRef.resetForm(); // 假设 dataInfo 组件有一个 resetForm 方法
      }
    },
    btnView(e) {
      let _this = this;
      _this.queryForm.parent_id = e;
      _this.search();

      // _this.$router.push({path:"/template/category/search",params:{parent_id:e}});
      // location.href="?parent_id="+e;
    },
    loadData(row, node, resolve) {
      setTimeout(() => {
        searchTemplateCategory({ parent_id: row.id }).then((res) => {
          if (res.data.length == 0) {
            this.$message.warning("暂无数据!");
          }
          res.data.map((el) => {
            if (el.child_count > 0) {
              el.hasChildren = true;
            } else {
              el.hasChildren = false;
            }
          });
          resolve(res.data);
          this.expandedRows.add(row.id);
        });

        /*    resolve(row.children); */
      }, 0);
    },

    btnDelete(e) {
      let _this = this;
      let par = {
        id: e,
      };
      _this.queryForm.name = "";
      _this
        .$confirm("您是否确认删除该记录？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then((res) => {
          deleteTemplateCategory(par).then((res) => {
            _this.search();
          });
        })
        .catch(() => {});
    },

    searchData() {
      let _this = this;
      _this.dialogVisible = false;
      _this.search();
    },

    //编辑
    btnEdit(e) {
      let _this = this;
      _this.currentDataId = e.id;
      _this.dialogVisible = true;
    },

    onClose() {
      let _this = this;
      _this.currentDataId = 0;
      _this.dialogVisible = false;
      _this.search();
    },

    //搜索
    search() {
      let _this = this;
      _this.dataList = [];
      _this.tableLoading = true;
      searchTemplateCategory(_this.queryForm)
        .then((res) => {
          if (!res) {
            _this.tableLoading = false;
            return;
          }
          const newDataList = res.data.dataList.map((el) => {
            if (el.child_count > 0) {
              el.hasChildren = true;
            } else {
              el.hasChildren = false;
            }
          });
          _this.dataList = res.data.dataList;
          _this.recordCount = res.data.totalRecord;
          _this.pageTotal = res.data.totalPage;
          _this.$forceUpdate();

          // 使用 nextTick 确保 DOM 已更新
          _this.$nextTick(() => {
            // 这里可以添加任何需要在 DOM 更新后执行的操作
            console.log("View updated");
            _this.tableLoading = false;
          });
        })
        .catch(() => {
          _this.tableLoading = false;
        });
    },
    //修改分页
    ChangePage(e) {
      let _this = this;
      _this.queryForm.page = e;
      _this.search();
    },
  },
};
</script>

<style lang="scss">
@import "./dataList.scss";
</style>
