<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <el-form-item label="证书类型" prop="typeName">
          <el-input
            v-model="queryParams.typeName"
            placeholder="请输入证书类型"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleQuery">查找</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleAdd">添加</el-button>
          <el-button class="filter-item" type="info" icon="el-icon-sort" @click="toggleExpandAll">展开/折叠</el-button>
        </el-form-item>
      </el-form>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="deptList"
        row-key="id"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column prop="typeName" label="证书类型" min-width="180px"></el-table-column>
        <el-table-column prop="orderNum" label="排序" align="center"></el-table-column>
        <el-table-column prop="integral" label="积分" align="center"></el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="110px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="success"
              @click="handleAdd(scope.row)"
            >添加</el-button>
            <el-button
              v-if="scope.row.parentId != 0"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 添加或修改证书对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="24" v-if="form.parentId !== 0">
              <el-form-item label="上级类型" prop="parentId">
                <treeselect default-expand-all v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级类型" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="证书类型" prop="typeName">
                <el-input v-model="form.typeName" placeholder="请输入证书类型" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="积分" prop="integral">
                <el-input-number v-model="form.integral" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="显示排序" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/certManage";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  
  export default {
    components: { Treeselect },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 表格树数据
        deptList: [],
        // 证书树选项
        deptOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否展开，默认全部展开
        isExpandAll: true,
        // 重新渲染表格状态
        refreshTable: true,
        // 查询参数
        queryParams: {
          typeName: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          parentId: [
            { required: true, message: "上级类型不能为空", trigger: "blur" }
          ],
          typeName: [
            { required: true, message: "证书类型不能为空", trigger: "blur" }
          ],
          orderNum: [
            { required: true, message: "显示排序不能为空", trigger: "blur" }
          ],
          integral: [
            { required: true, message: "积分不能为空", trigger: "blur" }
          ],
          email: [
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ],
          phone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ]
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询证书列表 */
      getList() {
        this.loading = true;
        listDept(this.queryParams).then(response => {
          this.deptList = this.handleTree(response.data.data,'id');
          console.log(this.deptList);
          this.loading = false;
        });
      },
      /** 转换证书数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.typeName,
          children: node.children
        };
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          parentId: undefined,
          typeName: undefined,
          orderNum: undefined,
          integral:undefined,
          leader: undefined,
          phone: undefined,
          email: undefined,
          status: "0"
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        if (row != undefined) {
          this.form.parentId = row.id;
        }
        this.open = true;
        this.title = "添加证书";
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data.data, "id");
        });
      },
      /** 展开/折叠操作 */
      toggleExpandAll() {
        this.refreshTable = false;
        this.isExpandAll = !this.isExpandAll;
        this.$nextTick(() => {
          this.refreshTable = true;
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        getDept({id:row.id}).then(response => {
          this.form = response.data.data;
          this.open = true;
          this.title = "修改证书";
          listDeptExcludeChild({id:row.id}).then(response => {
            this.deptOptions = this.handleTree(response.data.data, "id");
            if (this.deptOptions.length == 0) {
              const noResultsOptions = { id: this.form.parentId, typeName: this.form.parentName, children: [] };
              this.deptOptions.push(noResultsOptions);
            }
          });
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateDept(this.form).then(response => {
                this.$notify({
                            title: '成功',
                            message: '修改成功',
                            type: 'success',
                            duration: 2000
                        })
                this.open = false;
                this.getList();
              });
            } else {
              addDept(this.form).then(response => {
                this.$notify({
                            title: '成功',
                            message: '新增成功',
                            type: 'success',
                            duration: 2000
                        })
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm('是否确认删除名称为"' + row.typeName + '"的数据项？', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
        .then(function() {
          return delDept({id:row.id});
        }).then(() => {
          this.getList();
          this.$notify({
                            title: '成功',
                            message: '删除成功',
                            type: 'success',
                            duration: 2000
                        })
        }).catch(() => {});
      }
    }
  };
  </script>
  