<template>
  <page-wrapper>
    <el-card :bordered="false" class="mb-3 proCard">
      <el-space align="center">
        <el-input
          :style="{ width: '320px' }"
          v-model="params.roleName"
          clearable
          placeholder="请输入角色名称"
          @keyup.enter="reloadTable"
        />
        <el-button type="primary" @click="reloadTable">
          <template #icon>
            <el-icon>
              <SearchOutlined />
            </el-icon>
          </template>
          查询
        </el-button>
      </el-space>
    </el-card>
    <el-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        :pagination="{ hideOnSinglePage: false }"
        :tableSetting="{
          size: false,
          redo: false,
          fullscreen: false,
          striped: false,
          setting: false,
        }"
        ref="tableRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <el-button type="primary" @click="openCreateUserDrawer">
            <template #icon>
              <el-icon>
                <FileAddOutlined />
              </el-icon>
            </template>
            用户角色
          </el-button>
          <el-button type="primary" @click="openCreateDrawer">
            <template #icon>
              <el-icon>
                <FileAddOutlined />
              </el-icon>
            </template>
            管理员角色
          </el-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </el-card>

    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :permissionList="treeData"
      @change="reloadTable"
    />

    <CreateUserDrawer ref="createUserDrawerRef" :title="drawerTitle" @change="reloadTable" />
  </page-wrapper>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h, onMounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import { BasicTable, TableAction, BasicColumn } from '@/components/Table';
  import { roleList, permissionList, delAdminRole, delUserRole } from '@/api/system/role';
  import { columns } from './columns';
  import { FileAddOutlined, SearchOutlined } from '@vicons/antd';
  import CreateDrawer from './CreateDrawer.vue';
  import CreateUserDrawer from './CreateUserDrawer.vue';
  import { useUserStore } from '@/store/modules/user';

  const message = ElMessage;
  const tableRef = ref();
  const createDrawerRef = ref();
  const createUserDrawerRef = ref();
  const drawerTitle = ref('添加角色');
  const treeData = ref([]);
  const userStore = useUserStore();

  const params = reactive({
    roleName: '',
  });

  const actionColumn: BasicColumn = reactive({
    width: 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            isConfirm: true,
            popConfirm: {
              onConfirm: handleDelete.bind(null, record.row),
              title: '您确定要删除吗？',
              confirmButtonText: '确定',
              cancelButtonText: '取消',
            },
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record.row),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };
    return await roleList(_params);
  };

  function openCreateDrawer() {
    drawerTitle.value = '添加角色';
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  function openCreateUserDrawer() {
    drawerTitle.value = '添加角色';
    const { openDrawer } = createUserDrawerRef.value;
    openDrawer();
  }

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    tableRef.value.reload();
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    console.log('record.roleType', record.roleType);
    drawerTitle.value = '编辑角色';
    if (record.roleType === 1 || record.roleType === 2) {
      const { openDrawer } = createDrawerRef.value;
      openDrawer(record.roleId);
    } else {
      const { openDrawer } = createUserDrawerRef.value;
      openDrawer(record.roleId);
    }
  }

  function handleDelete(record: Recordable) {
    console.log('record.roleType', record.roleType);
    // if (userStore.getRoleTypes.includes(String(record.roleId))) {
    //   message.error('不能删除自己的角色');
    //   return;
    // }
    if (record.roleType === 1 || record.roleType === 2) {
      delAdminRole({ roleId: record.roleId }).then(() => {
        message.success('删除成功');
        reloadTable();
      });
    } else {
      delUserRole({ roleId: record.roleId }).then(() => {
        message.success('删除成功');
        reloadTable();
      });
    }
  }

  onMounted(async () => {
    const list = await permissionList();
    treeData.value = list.filter((item) => item.label !== '功能权限');
  });
</script>
