<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAddGroup"
            >新增分组</el-button
          >
          <el-input
            v-model="groupName"
            placeholder="请输入分组名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-top: 10px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="tagGroupTreeList"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            :current-node-key="formGroup.parentId"
            :render-content="renderContent"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          :class="showSearch ? '' : ' hide'"
          label-width="68px"
        >
          <el-form-item label="标签名称" prop="tagName">
            <el-input
              v-model="queryParams.tagName"
              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-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system/base:tag:add']"
              >新增</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tagList">
          <el-table-column label="标签名称" prop="tagName" />
          <el-table-column label="描述" prop="remark" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{
                parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system/base:tag:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system/base:tag:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改标签管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属分组" prop="groupId">
          <treeselect
            v-model="form.groupId"
            :options="tagGroupSelectTreeList"
            :show-count="true"
            placeholder="请选择所属分组"
          />
        </el-form-item>
        <el-form-item label="标签名称" prop="tagName">
          <el-input v-model="form.tagName" placeholder="请输入标签名称" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :loading="submitting">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改标签分组对话框 -->
    <el-dialog
      :title="titleGroup"
      :visible.sync="openGroup"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formGroup"
        :model="formGroup"
        :rules="rulesGroup"
        label-width="80px"
      >
        <el-form-item label="上级分组" prop="parentId">
          <treeselect
            v-model="formGroup.parentId"
            :options="tagGroupSelectTreeList"
            :show-count="true"
            placeholder="请选择上级分组"
          />
        </el-form-item>
        <el-form-item label="分组名称" prop="groupName">
          <el-input
            v-model="formGroup.groupName"
            placeholder="请输入分组名称"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormGroup" :loading="submitting">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTag,
  getTag,
  delTag,
  addTag,
  updateTag,
} from "@/api/system/base/tag";
import {
  listTaggroup,
  getTaggroup,
  addTaggroup,
  updateTaggroup,
  delTaggroup,
} from "@/api/system/base/tagGroup";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Tag",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      submitting: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标签管理表格数据
      tagList: [],
      // 标签分组原始数据
      tagGroupList: [],
      // 标签分组树形数据
      tagGroupTreeList: [],
      // 标签分组选择树数据
      tagGroupSelectTreeList: [],
      // 新增分组弹出层
      openGroup: false,
      defaultProps: {
        children: "children",
        label: "label",
      },
      titleGroup: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
        tagName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        groupId: [
          { required: true, message: "所属分组不能为空", trigger: "change" },
        ],
        tagName: [
          { required: true, message: "标签名称不能为空", trigger: "change" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "change" },
        ],
      },
      groupName: undefined,
      formGroup: {
        parentId: "",
      },
      rulesGroup: {
        groupName: [
          { required: true, message: "分组名称不能为空", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    groupName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTaggroupList();
    this.getList();
  },
  methods: {
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    renderContent(h, { node, data, store }) {
      return (
        <div class="custom-tree-node">
          <div class="label">{node.label}</div>
          <div class="action">
            <el-button
              size="mini"
              type="text"
              on-click={() => this.handleAddGroup(data.id)}
            >
              <i class="el-icon-plus"></i>
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.handleUpdateGroup(data)}
            >
              <i class="el-icon-edit"></i>
            </el-button>
            <el-button
              size="mini"
              type="text"
              on-click={() => this.handleDeleteGroup(data)}
            >
              <i class="el-icon-delete"></i>
            </el-button>
          </div>
        </div>
      );
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.groupId = data.id;
      this.handleQuery();
    },
    /** 查询标签分组 */
    getTaggroupList() {
      this.loading = true;
      listTaggroup({}).then((response) => {
        this.tagGroupList = response.data;
        let groupTreeList = [];
        if (response.data && response.data.length > 0) {
          response.data.forEach((p) => {
            groupTreeList.push({
              id: p.id,
              parentId: p.parentId,
              label: p.groupName,
              children: p.children,
            });
          });
        }
        this.tagGroupSelectTreeList = this.handleTree(groupTreeList);

        this.tagGroupTreeList = [
          {
            id: "",
            label: "全部",
            children: this.tagGroupSelectTreeList,
          },
        ];
        this.loading = false;
      });
    },
    /** 查询标签管理列表 */
    getList() {
      this.loading = true;
      listTag(this.queryParams).then((response) => {
        this.tagList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openGroup = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        groupId: null,
        tagName: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");

      this.formGroup = {
        id: null,
        parentId: null,
        groupName: null,
      };
      this.resetForm("formGroup");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加标签管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getTag(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改标签管理";
      });
    },
    /** 新增按钮操作 */
    handleAddGroup(parentId = null) {
      this.reset();
      if (parentId > 0) {
        this.formGroup.parentId = parentId;
      }

      this.openGroup = true;
      this.titleGroup = "添加标签分组";
    },
    /** 修改按钮操作 */
    handleUpdateGroup(row) {
      this.reset();
      const id = row.id || this.ids;
      getTaggroup(id).then((response) => {
        this.formGroup = response.data;
        this.openGroup = true;
        this.titleGroup = "修改标签分组";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.submitting = true;
          if (this.form.id != null) {
            updateTag(this.form).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.submitting = false;
            });
          } else {
            addTag(this.form).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.submitting = false;
            });
          }
        }
      });
    },
    submitFormGroup() {
      this.$refs["formGroup"].validate((valid) => {
        if (valid) {
          this.submitting = true;
          if (this.formGroup.id != null) {
            updateTaggroup(this.formGroup).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("修改成功");
              this.openGroup = false;
              this.getTaggroupList();
            }).catch(() => {
              this.submitting = false;
            });
          } else {
            addTaggroup(this.formGroup).then((response) => {
              this.submitting = false;
              this.$modal.msgSuccess("新增成功");
              this.openGroup = false;
              this.getTaggroupList();
            }).catch(() => {
              this.submitting = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除标签管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delTag(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDeleteGroup(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除标签分组？")
        .then(function () {
          return delTaggroup(ids);
        })
        .then(() => {
          this.getTaggroupList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/base/tag/export",
        {
          ...this.queryParams,
        },
        `tag_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
