<template>
  <div class="app-container">
    <div class="flex-col content-container">
      <el-row type="flex" justify="space-between" ref="listQueryContainer" class="query-container">
        <el-col>
          <el-form ref="listQuery" :inline="true" :model="listQuery" style="flex-wrap: wrap" @submit.native.prevent
                   @keyup.enter.native="onSubmit">
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="listQuery.name" clearable maxlength="16" placeholder="请输入名称"
                        @clear="listQuery.name=undefined" @keyup.enter.native="onFilterChange">
                <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
              </el-input>
            </el-form-item>
            <el-form-item label="是否禁用" prop="disabled">
              <el-select v-model="listQuery.disabled" clearable placeholder="请选择" @change="onFilterChange"
                         @clear="listQuery.disabled=undefined">
                <el-option v-for="item in disableStatusList" :key="item.id" :label="item.label"
                           :value="item.id"></el-option>
              </el-select>

            </el-form-item>
            <el-form-item label="创建时间范围" prop="createTimeRange">
              <el-date-picker
                  v-model="listQuery.createTimeRange"
                  value-format="timestamp"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['00:00:00', '23:59:59']"
                  @change="onFilterChange">
              </el-date-picker>
            </el-form-item>

            <el-form-item label-width="0">
              <el-button @click="onFilterChange" type="primary">查询</el-button>
              <el-button @click="resetFields" plain type="primary">重置</el-button>
              <el-button @click="onExport" plain type="primary">导出</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <form-clear :shrinkable="shrinkable" @clear="resetFields" @change="onExpansion"/>
      </el-row>

      <el-row>
        <el-button @click="onAdd" type="primary">添加</el-button>
        <el-button v-if="!editing" @click="onBatchDelete" plain type="primary">批量删除</el-button>
        <el-button v-if="editing" :disabled="!(selectIds&&selectIds.length)" type="danger" @click="onDeleteSelect">删除
        </el-button>
        <el-button v-if="editing" @click="onCancel" plain>取消</el-button>
      </el-row>

      <!--角色管理-->
      <div class="flex flex1 over-scroll pt10" style="width:1200px;">
        <el-table ref="table" :data="list" border height="100%" highlight-current-row stripe
                  @sort-change="onSortChange" @selection-change="onTableSelectionChange" @row-click="onRowClick">
          <el-table-column v-if="editing" type="selection" width="55" fixed></el-table-column>
          <el-table-column type="index" :index="indexCompute" label="序号" align="center" fixed="left" width="60px"/>
          <el-table-column prop="name" label="名称" sortable="custom" align="center" min-width="74px"/>
          <el-table-column prop="disabled" label="是否禁用" sortable="custom" align="center" width="120px">
             <template v-slot="scope">
              <el-switch
                  v-model="scope.row.disabled"
                  @click.native.stop
                  @change="onChangeEnabled(scope.row, scope.row.disabled)">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" sortable="custom" align="center" width="160px">
             <template v-slot="scope">
              {{ scope.row.createTime | dateFormat }}
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="110px">
             <template v-slot="scope">
              <router-link :to="{name:'SystemUser',params:{roleId:scope.row.id}}">
                <el-link type="primary" icon="el-icon-view">查看用户</el-link>
              </router-link>
            </template>
          </el-table-column>
        </el-table>

        <el-form ref="dataForm" :model="dataForm" :rules="dataRules" class="h100p ml10 border-box p4 flex-col" label-width="100px"
                 style="width: 500px;">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="dataForm.name" type="text" maxlength="15"></el-input>
          </el-form-item>

          <el-form-item class="tree-container flex1" label="启用的权限" prop="permissions">
            <el-input
                placeholder="输入关键字进行查找"
                clearable @clear="keyword=undefined"
                v-model="keyword">
            </el-input>
            <el-tree
                class="permissions-tree"
                :data="permissions"
                :default-expanded-keys="expanded"
                :props="{label:'name'}"
                :filter-node-method="filterPermissions"
                show-checkbox
                node-key="id"
                ref="permissions">
            </el-tree>
          </el-form-item>
          <el-form-item label-width="0" class="save-button">
            <el-button :disabled="!permissions || !selectItem" @click="onSave" type="primary">保存</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-dialog class="dialog"
                 :visible.sync="addDialogVisible"
                 center
                 title="添加角色"
                 append-to-body
                 :before-close="onBeforeClose"
                 width="400px"
                 @close="$refs['addRoleForm'].resetFields()">

        <el-form label-width="120px" ref="addRoleForm" :model="addRoleForm" :rules="dataRules">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="addRoleForm.name" type="text" maxlength="15" show-word-limit>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer">
          <el-button :disabled="!this.selectItem" type="primary" @click="onAddRole">确 认</el-button>
          <el-button @click="addDialogVisible=false">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="exportVisible" title="导出"
                 width="600px">
        <el-progress :text-inside="true" :stroke-width="24" :percentage="exportProgress" status="success"></el-progress>
        <el-button slot="footer" @click="onCancelExport">取 消</el-button>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {dateFormat} from "@/utils/dateUtil"
import {validateNotEmpty} from "@/utils/validate";

export default {
  name: "SystemRole",
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      keyword: undefined, // 过滤关键字
      expanded: [], // 展开的权限
      listQuery: { // 查询对象
        name: undefined, // 名称
        disabled: undefined, // 是否禁用
        createTimeRange: [], // 创建时间
        createTimeStart: undefined,
        createTimeEnd: undefined,
        order: undefined,
      },
      addRoleForm: {
        name: undefined, // 角色名称
      },
      dataForm: {
        id: undefined, // 角色id
        name: undefined, // 角色名称
        permissions: undefined, // 权限
      },
      permissions: undefined, // 所有权限
      list: [], // 结果列表

      selectItem: undefined, // 选中行

      exportVisible: false, // 是否显示导出对话框

      exportProgress: 0, // 导出进度
      exportCancel: false, // 是否取消导出

      addDialogVisible: false, // 添加对话框是否可见

      editing: false, // 表格编辑中

      selectIds: undefined, // 选中多条记录的id

      disableStatusList: [{id: false, label: "启用"}, {id: true, label: "禁用"}],

      dataRules: {
        name: [{validator: validateNotEmpty, errorMessage: "角色名称不能为空", required: true, trigger: 'empty'}],
      },
    }
  },

  watch: {
    'listQuery.createTimeRange'(value) {
      if (value) {
        this.listQuery.createTimeStart = value[0];
        this.listQuery.createTimeEnd = value[1];
      } else {
        this.listQuery.createTimeStart = undefined;
        this.listQuery.createTimeEnd = undefined;
      }
    },
    keyword(val) {
      this.$refs["permissions"].filter(val);
    }
  },

  // 页面创建
  created() {
  },

  // 页面挂载
  mounted() {
    this.initQuery();
    this.getList();
    this.initData();
    this.initView();
    this.onCancel();
  },

  // keep-alive 显示界面时调用
  activated() {
    this.initData();
    this.$refs["table"].doLayout();
    if (this.list.length > 0) {
      this.onRowClick(this.list[0])
    }
  },

  // keep-alive 页面隐藏
  deactivated() {
  },

  methods: {
    // 初始化数据
    initData() {
      this.$axios.get("/v1/system/permissions/list/tree").then((data) => {
        this.permissions = data;
        this.expanded = data.map(p => p.id);
      });
    },
    // 初始化查询条件
    initQuery() {
      if (this.$store.state.app.paramCache) {
        let query = this.$storage.getData(this.$options.name);
        if (Object.keys(query).length > 0) {
          this.listQuery = query;
          if (query.order) {
            this.$refs.table.sort(query.order.substring(1), query.order.substring(0, 1) === "+" ? "ascending" : "descending");
          } else {
            this.$refs.table.clearSort();
          }
        }
      }
    },

    // 初始化视图
    initView() {
      this.$nextTick(() => {
        this.shrinkable = this.$store.state.app.filterShrink && this.$refs['listQuery'].$el.offsetHeight > 51;
      })
    },

    // 展开/收起查询条件
    onExpansion(show) {
      this.$refs['listQueryContainer'].$el.style.height = show ? "auto" : "51px";
    },

    // 表格索引
    indexCompute(index) {
      return index + 1;
    },

    // 表单提交
    onSubmit() {
      this.onFilterChange();
    },

    // 表单清除
    resetFields() {
      this.$refs['listQuery'].resetFields();
      this.listQuery.order = undefined;
      this.$refs.table.clearSort();
      this.onFilterChange();
    },

    // 添加
    onAdd() {
      this.onCancel();
      this.addDialogVisible = true;
    },

    // 添加
    onAddRole() {
      this.$axios.post("/v1/system/role/add", this.addRoleForm).then(() => {
        this.$message.success("添加成功！");
        this.addDialogVisible = false;
        this.getList();
      });
    },

    // 编辑
    onBatchDelete() {
      this.editing = true;
    },

    // 删除选中
    onDeleteSelect() {
      this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete("/v1/system/role/delete", {params: {ids: this.selectIds}}).then(() => {
          this.getList();
        }).catch(() => {
        });
      });
    },

    // 取消编辑
    onCancel() {
      this.$refs['table'].clearSelection();
      this.editing = false;
    },

    // 禁用改变状态
    onChangeEnabled(data, val) {
      this.$confirm('此操作将 ' + (val ? '禁用 ' : '启用 ') + data.name + '角色, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.put("/v1/system/role/update/status", {id: data.id, disabled: data.disabled}).then(() => {
          this.$message.success("更新成功！");
        }).catch(() => {
          data.disabled = !data.disabled
        })
      }).catch(() => {
        data.disabled = !data.disabled
      })
    },

    // 数据选择
    onTableSelectionChange(val) {
      this.selectIds = val.map(item => item.id);
    },

    // 排序改变
    onSortChange({prop, order}) {
      if (order === "ascending") {
        this.listQuery.order = "+" + prop;
      } else if (order === "descending") {
        this.listQuery.order = "-" + prop;
      } else {
        this.listQuery.order = undefined;
      }
      this.onFilterChange();
    },

    // 行点击
    onRowClick(row, column) {
      this.$refs["table"].setCurrentRow(row);
      if (this.editing) {
        this.$refs["table"].toggleRowSelection(row);
      } else {
        this.selectItem = row;
        this.dataForm.id = row.id;
        this.dataForm.name = row.name;
        this.$axios.get(`/v1/system/role/list/${this.dataForm.id}/permissions`).then((data) => {
          this.$refs.permissions.setCheckedKeys(data)
        });
      }
    },

    // 权限显示过滤
    filterPermissions(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 更新角色名称及权限
    onSave() {
      this.dataForm.permissions = this.$refs.permissions.getCheckedNodes(false, true).map(item => item.id);
      this.$axios.put("/v1/system/role/update", this.dataForm).then(() => {
        this.selectItem.name = this.dataForm.name;
        this.$message.success("保存成功！");
      });
    },

    // 条件改变
    onFilterChange() {
      this.getList();
    },

    // 加载列表
    getList() {
      // 缓存参数
      if (this.$store.state.app.paramCache) {
        this.$storage.setData(this.$options.name, this.listQuery);
      }
      this.$axios.get("/v1/system/role/list", {params: this.listQuery}).then(data => {
        this.list = data;
        this.$refs["table"].doLayout();
        if (this.list.length > 0) {
          this.onRowClick(this.list[0])
        }
      });
    },

    // 关闭前确认
    onBeforeClose(done) {
      if (this.$store.state.app.closeConfirmEnable) {
        this.$confirm("确认关闭？").then(() => done());
      } else {
        done();
      }
    },

    // 导出数据
    onExport() {
      if (this.list && this.list.length > 0) {
        this.exportVisible = true;
        this.getExportData();
      }
    },

    // 取消导出
    onCancelExport() {
      this.exportVisible = false;
      this.exportCancel = true;
    },

    // 获取数据并导出
    getExportData() {
      if (!this.exportCancel) {
        this.$axios.get("/v1/system/role/list", {params: {...this.listQuery, ...this.exportPagination}}).then(data => {
          this.exportProgress = Math.round(data.list.length * 100 / data.list.length);
          this.exportVisible = false;

          let tHeader = ["序号",
            "名称",
            "是否禁用",
            "创建时间",
          ];
          let filterVal = ["index",
            "name",
            "disabled",
            "createTime",
          ];
          data = data.list.map((value, index) => filterVal.map((key) => {
            if (key === "index") {
              return index + 1;
            } else if (key === "createTime") {
              return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
            } else if (key === "disabled") {
              return this.disableStatusList.find(item => item.id === Number(value[key])).label;
            } else {
              return value[key];
            }
          }));
          import('@/utils/Export2Excel').then(excel => {
            excel.export_json_to_excel({
              header: tHeader, // 表头 必填
              data, // 具体数据 必填
              filename: '系统设置-角色信息列表', // 非必填
              autoWidth: true, // 非必填
              bookType: 'xlsx' // 非必填
            })
          })
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../../styles/variables";

.app-container {
  height: calc(100vh - #{$headerHeight} - 20px);
  overflow-x: auto;

  .content-container {
    min-width: 1200px;
    height: 100%;

    .tree-container {
      overflow: auto;

      ::v-deep .el-form-item__content {
        height: 100%;
        display: flex;
        flex-direction: column;

        .permissions-tree {
          margin-top: 10px;
          flex: 1;
          overflow: auto;
        }
      }
    }

    .save-button {
      height: 50px;
      display: flex;
      align-items: center;
      margin: 0;
      justify-content: center;
    }
  }
}
</style>
