<template>
  <ele-page>
    <!-- 搜索表单 -->
    <role-search @search="reload" />

    <ele-tabs
      type="card"
      v-model="configGroup"
      :items="groupItems"
      @tabChange="reload()"
    />

    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="roleId"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        :highlight-current-row="true"
        :export-config="{ fileName: '角色数据', datasource: exportSource }"
        :print-config="{ datasource: exportSource }"
        :pagination="false"
        cache-key="systemRoleTable"
        :load-on-created="false"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openEdit()"
          >
            添加
          </el-button>
          <el-button
            type="danger"
            class="ele-btn-icon"
            :icon="DeleteOutlined"
            @click="remove()"
          >
            删除
          </el-button>
        </template>
        <template #action="{ row }">
          <el-link type="primary" underline="never" @click="openEdit(row)">
            修改
          </el-link>
          <el-divider direction="vertical" />
          <el-link type="danger" underline="never" @click="remove(row)">
            删除
          </el-link>
        </template>
        <template #status="{ row }">
          <el-switch
            size="small"
            :model-value="row.status === 0"
            @change="(checked: boolean) => editStatus(checked, row)"
          />
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <role-edit v-model="showEdit" :data="current" @done="reload" />
    <!-- 权限分配弹窗 -->
    <role-auth v-model="showAuth" :data="current" />
  </ele-page>
</template>

<script lang="ts" setup>
import {onMounted, ref} from 'vue';
  import { ElMessageBox } from 'element-plus';
  import { EleMessage } from 'ele-admin-plus';
  import type { EleProTable } from 'ele-admin-plus';
  import type {
    DatasourceFunction,
    Columns
  } from 'ele-admin-plus/es/ele-pro-table/types';
  import { PlusOutlined, DeleteOutlined } from '@/components/icons';
  import RoleSearch from './components/role-search.vue';
  import RoleEdit from './components/role-edit.vue';
  import RoleAuth from './components/role-auth.vue';
  import { pageRoles, removeRoles, listRoles } from '@/api/system/role';
  import type { Role, RoleParam } from '@/api/system/role/model';
import { listConfig } from "@/api/system/config";
import {getSysConfig} from "@/utils/sys-config";
import type {User} from "@/api/system/user/model";
import {updateUserStatus} from "@/api/system/user";

  defineOptions({ name: 'SystemRole' });

  /** 表格实例 */
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  /** 表格列配置 */
  const columns = ref<Columns>([
    {
      type: 'index',
      columnKey: 'index',
      width: 50,
      align: 'center'
    },
    {
      prop: 'name',
      label: '名称',
      sortable: 'custom',
      minWidth: 120
    },
    {
      prop: 'title',
      label: '标题',
      minWidth: 120
    },
    {
      prop: 'type',
      label: '类型',
      minWidth: 120
    },
    {
      prop: 'status',
      label: '状态',
      width: 90,
      align: 'center',
      sortable: 'custom',
      slot: 'status',
      formatter: (row) => (row.status == 0 ? '正常' : '冻结')
    },
    {
      prop: 'comments',
      label: '备注',
      minWidth: 140
    },
    {
      columnKey: 'action',
      label: '操作',
      width: 200,
      align: 'center' /* ,
      fixed: 'right' */,
      slot: 'action',
      hideInPrint: true,
      hideInExport: true
    }
  ]);

  /** 表格选中数据 */
  const selections = ref<Role[]>([]);

  /** 当前编辑数据 */
  const current = ref<Role | null>(null);

  /** 是否显示编辑弹窗 */
  const showEdit = ref(false);

  /** 是否显示权限分配弹窗 */
  const showAuth = ref(false);

  /** 表格数据源 */
  const datasource: DatasourceFunction = ({ pages, where, orders }) => {
    return listConfig({ ...where, ...orders, ...pages, group: configGroup.value });
  };

  /** 搜索 */
  const reload = (where?: RoleParam) => {
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  /** 打开编辑弹窗 */
  const openEdit = (row?: Role) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /** 打开权限分配弹窗 */
  const openAuth = (row?: Role) => {
    current.value = row ?? null;
    showAuth.value = true;
  };

  /** 删除单个 */
  const remove = (row?: Role) => {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
      EleMessage.error({ message: '请至少选择一条数据', plain: true });
      return;
    }
    ElMessageBox.confirm(
      '确定要删除“' + rows.map((d) => d.roleName).join(', ') + '”吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        const loading = EleMessage.loading({
          message: '请求中..',
          plain: true
        });
        removeRoles(rows.map((d) => d.roleId))
          .then((msg) => {
            loading.close();
            EleMessage.success({ message: msg, plain: true });
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error({ message: e.message, plain: true });
          });
      })
      .catch(() => {});
  };

  /** 导出和打印全部数据的数据源 */
  const exportSource: DatasourceFunction = ({ where, orders }) => {
    return listRoles({ ...where, ...orders });
  };
  /** 修改配置状态 */
  const editStatus = (checked: boolean, row: User) => {
    const status = checked ? 1 : 0;
    updateUserStatus(row.id, status)
      .then((msg) => {
        row.status = status;
        EleMessage.success({ message: msg, plain: true });
      })
      .catch((e) => {
        EleMessage.error({ message: e.message, plain: true });
      });
  };

  const groupItems = ref([]);
  const configGroup = ref("");
  onMounted(async ()=>{
    // 配置分组
    const group = [];
    const { valueData } = await getSysConfig( "system.config_group");
    for (const name in valueData) {
      group.push({ name: name, label: valueData[name] })
    }
    groupItems.value = group
    if(group.length > 0){
      configGroup.value = group[0].name
    }
    reload();
  })
</script>
