<template>
  <div>
    <!-- 搜索栏 -->
    <search-bar :conditionForm="conditionForm" @submitSearch="receiveSearch"></search-bar>
    <!-- 操作栏 -->
    <operate-bar :pageOptList="pageOptList" @submitPageOpt="receviceOpt"></operate-bar>
    <!-- 列表 -->
    <vxe-table ref="vxeGrid" :data="tableData" v-bind="gridOptions" highlight-hover-row>
      <vxe-table-column type="checkbox" width="60" align="center">
        <template #header="row">
          <span class="custom-checkbox">
            <el-checkbox
              :indeterminate="row.indeterminate"
              v-model="row.checked"
              @change="handleToggleAllCheck"
            ></el-checkbox>
          </span>
        </template>
        <template #checkbox="scoped">
          <span class="custom-checkbox">
            <el-checkbox
              :indeterminate="scoped.indeterminate"
              v-model="scoped.checked"
              @change="handleToggleCheck(scoped.row)"
            ></el-checkbox>
          </span>
        </template>
      </vxe-table-column>
      <vxe-table-column type="seq" width="60" align="center" title="序号"></vxe-table-column>
      <vxe-table-column
        align="left"
        header-align="center"
        title="应用功能名称"
        field="label"
        :treeNode="true"
      ></vxe-table-column>
      <vxe-table-column align="center" title="红名单级别" field="level">
        <template #default="{ row }">
          {{ levelToLabel(row.level) }}
        </template>
      </vxe-table-column>
      <vxe-table-column align="center" title="操作" field="operate">
        <template #default="{ row }">
          <div class="u-table__operation">
            <el-tooltip content="删除" effect="dark" placement="top-end">
              <i :class="'删除' | optIcon" @click="handleRemove(row)"></i>
            </el-tooltip>
          </div>
        </template>
      </vxe-table-column>
    </vxe-table>
    <!-- 分页器 -->
    <div class="pagination-section">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import batchAddAppFunc from './batch-add-appfunc.vue';
import batchSetLevelAppFunc from './batch-setlevel-appfunc.vue';
import batchDeleteAppFunc from './batch-delete-appfunc.vue';
import { getRedAppFuncList, delRedAppFunc } from '@/api/list-manage';
import { allAppFuncTree } from '@/api/permission-selfhelp-manage';
import jzApi from '@/api/jz-base';
import operateBar from '@/components/operate-bar';
import searchBar from '@/components/search-bar';
import { searchOpt } from '@/mixins/page-opt';
import { appRestApi } from '@/api/application';

export default {
  components: { operateBar, searchBar },
  mixins: [searchOpt],
  data() {
    return {
      pageOptList: ['批量添加', '批量设置名单级别', '批量删除'],
      // 分页器
      currentPage: 1,
      total: 0,
      pageSize: 10,
      // 数据
      tableData: [],
      gridOptions: {
        border: true,
        rowId: 'id',
        treeConfig: { children: 'child', indent: 40 },
        loading: false,
        checkboxConfig: {
          // 设置复选框支持分页勾选，需要设置 rowId 行数据主键
          reserve: true
        }
      },
      conditionForm: [
        {
          label: '应用系统名称',
          name: 'appName',
          op: 'like',
          value: '',
          component: 'SelectApp',
          apiUrl: appRestApi.table,
          valueName: 'applyName',
          labelName: 'applyName'
        }
      ]
    };
  },
  methods: {
    receviceOpt(type) {
      if (type == '批量添加') {
        this.handleAdd();
      } else if (type == '批量设置名单级别') {
        this.handleSetListLevel();
      } else if (type == '批量删除') {
        this.handleBatchRemove();
      }
    },
    handleToggleCheck(row) {
      this.$refs.vxeGrid.toggleCheckboxRow(row);
    },
    handleToggleAllCheck() {
      this.$refs.vxeGrid.toggleAllCheckboxRow();
    },
    /**
     * @description:查询
     */
    receiveSearch(value) {
      this.condition = value;
      this.reloadTable();
    },
    reloadTable() {
      this.currentPage = 1;
      const selectedData = this.$refs.vxeGrid.getCheckboxRecords(true).filter((item) => !item.isTreeNode);
      this.$refs.vxeGrid.reloadData(selectedData);
      this.getList();
    },
    // 打开弹窗
    openLayer(title, content, operate) {
      const vm = this;
      const checkboxReserveRecords = this.$refs.vxeGrid.getCheckboxReserveRecords(true);
      const checkboxRecords = this.$refs.vxeGrid.getCheckboxRecords(true);
      const indeterminateRecords = this.$refs.vxeGrid.getCheckboxIndeterminateRecords(true);
      const selectedData = [...checkboxRecords, ...checkboxReserveRecords, ...indeterminateRecords].filter(
        (item) => item.pid
      );
      const layer = this.$dgLayer({
        title,
        content,
        props: {
          data: this.allTree,
          selectedData,
          operate,
          value: selectedData.map((item) => item.id)
        },
        on: {
          success() {
            vm.reloadTable();
            layer.close(layer.dialogIndex);
          }
        },
        cancel: function (index) {
          // 关闭对应弹窗的ID
          layer.close(index);
          return false;
        },
        area: ['1000px', '800px']
      });
    },
    /**
     * 添加
     */
    handleAdd() {
      this.openLayer('批量添加应用功能红名单', batchAddAppFunc, 'add');
    },
    /**
     * 验证是否有批量选中
     */
    verify() {
      const selectedData = this.$refs.vxeGrid.getCheckboxRecords(true);
      if (selectedData.length == 0) {
        this.$message.warning('请至少选择一个应用功能!');
        return false;
      } else {
        return true;
      }
    },
    /**
     * 设置名单级别
     */
    handleSetListLevel() {
      if (!this.verify()) return;
      this.openLayer('批量设置红名单级别', batchSetLevelAppFunc, 'set');
    },
    /**
     * 批量删除
     */
    handleBatchRemove() {
      if (!this.verify()) return;
      this.openLayer('批量删除应用功能红名单', batchDeleteAppFunc, 'del');
    },

    /**
     * 单挑删除
     */
    handleRemove(row) {
      this.$dgConfirm(`是否确定删除这条数据！`, '提示', {}).then(() => {
        const params = {
          isTreeNode: row.isTreeNode,
          resourceId: row.id,
          resourceType: row.type
        };
        delRedAppFunc(params).then((res) => {
          this.$message.success('删除成功！');
          this.getList();
        });
      });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },
    /**
     * 获取列表
     */
    getList() {
      const params = {
        page: this.currentPage - 1,
        size: this.pageSize,
        searchCondition: this.condition
      };
      getRedAppFuncList(params).then((res) => {
        const { content, totalElements } = res.data;
        this.tableData = content;
        this.total = totalElements;
      });
    },
    /**
     * 获取全量的应用功能树
     */
    getAllFuncTree() {
      allAppFuncTree(false).then((res) => {
        this.allTree = res.data.content;
      });
    },
    /**
     * 获取级别级别枚举
     */
    getLevelEnum() {
      return new Promise((resolve) => {
        jzApi.fetchEnum('ListLevelEnum').then((res) => {
          this.levelList = res.data;
          resolve(res.data);
        });
      });
    },

    levelToLabel(val) {
      if (val) {
        return this.levelList.find((item) => item.value == val).label;
      } else {
        return '';
      }
    },
    async init() {
      await this.getLevelEnum();
      this.getList();
    }
  },
  created() {
    this.init();
    this.getAllFuncTree();
  }
};
</script>
<style lang="scss" scoped>
@import url('../index.scss');
</style>
