<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" v-auth="'role:add'" @click="handleCreate">
          {{ t('新增角色') }}
        </a-button>

        <a-button type="primary" v-auth="'role:addMember'" @click="handleAddUser">
          {{ t('添加成员') }}
        </a-button>

        <a-button type="primary" v-auth="'role:view'" @click="handleViewUser">
          {{ t('查看成员') }}
        </a-button>
        <!-- <a-button type="primary" v-auth="'role:functionalAuth'" @click="handleAuth">
          {{ t('功能授权') }}
        </a-button> -->
        <a-dropdown v-auth="'role:functionalAuth'" >
          <template #overlay>
            <a-menu @click="handleAuth">
              <a-menu-item key="4">全部</a-menu-item>
              <a-menu-item key="0">菜单</a-menu-item>
              <a-menu-item key="1">按钮</a-menu-item>
              <a-menu-item key="2">字段</a-menu-item>
              <a-menu-item key="3">表单</a-menu-item>
            </a-menu>
          </template>
          <a-button type="primary" >
            {{ t('功能授权') }}
            <DownOutlined />
          </a-button>
        </a-dropdown>
        <a-button type="primary" v-auth="'role:functionalAuth'" @click="handleAppAuth">
          {{ t('移动端功能授权') }}
        </a-button>
        <a-button type="primary" v-auth="'role:interfaceAuth'" @click="handleInterfaceAuth">
          {{ t('接口授权') }}
        </a-button>
        <a-button type="primary" v-auth="'role:homeAuth'" @click="handleHomeAuth">
          {{ t('首页授权') }}
        </a-button>
        <a-button type="primary" v-auth="'role:logoutRole'" @click="handleLogoutRole">
          {{ t('登出角色用户') }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              auth: 'role:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              auth: 'role:delete',
              color: 'error',
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <RoleModal @register="registerRoleModal" @success="handleSuccess" />
    <SelectInterfaceModal
      @register="registerInterfaceModal"
      @success="handleInterfaceSuccess"
      :minHeight="500"
    />
    <RoleAuthModal
      @register="registerRoleAuthModal"
      @success="handleRoleAuthSuccess"
      :minHeight="500"
    />
    <AppAuthModal @register="registerAppAuthModal" :minHeight="500" />
    <SelectDepartment
      v-if="visible"
      :visible="visible"
      :multiple="true"
      :selectedIds="selectedUserId"
      @close="
        () => {
          visible = false;
        }
      "
      @change="handleSelectUserSuccess"
    />
    <AuthModal @register="registerModal" />

    <HomeModal @register="registerHomeModal" @success="handleRoleAuthSuccess" :minHeight="500" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';

  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import {
    getRolePageList,
    updateRoleStatus,
    deleteRole,
    addRoleUser,
    getRoleUser,
    addRoleInterface,
    logoutByRoleId,
  } from '/@/api/system/role';
  import AuthModal from '../dataAuthority/components/AuthModal.vue';
  import HomeModal from './components/HomeModal.vue';
  import RoleModal from './components/RoleModal.vue';
  import SelectInterfaceModal from './components/SelectInterfaceModal.vue';
  import RoleAuthModal from './components/RoleAuthModal.vue';
  import AppAuthModal from './components/AppAuthModal.vue';
  import { SelectDepartment } from '/@/components/SelectOrganizational/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Switch, Modal } from 'ant-design-vue';
  import { PageWrapper } from '/@/components/Page';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  export const columns: BasicColumn[] = [
    {
      title: t('角色名称'),
      dataIndex: 'name',
      sorter: true,
      align: 'left',
    },
    {
      title: t('角色编码'),
      dataIndex: 'code',
      sorter: true,
      align: 'left',
    },
    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      sorter: true,
      align: 'left',
      customRender: ({ record }) => {
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.enabledMark === 1,
          checkedChildren: t('已启用'),
          unCheckedChildren: t('已禁用'),
          loading: record.pendingStatus,
          onChange(checked: boolean) {
            record.pendingStatus = true;
            const newStatus = checked ? 1 : 0;
            const { createMessage } = useMessage();
            updateRoleStatus(record.id, newStatus)
              .then(() => {
                record.enabledMark = newStatus;
                createMessage.success(t('已成功修改角色状态'));
              })
              .catch(() => {
                createMessage.error(t('修改角色状态失败'));
              })
              .finally(() => {
                record.pendingStatus = false;
              });
          },
        });
      },
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      sorter: true,
      align: 'left',
    },
  ];

  export const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('角色名称'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'code',
      label: t('角色编码'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'Select',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
      colProps: { lg: 8, md: 12, sm: 12 },
    },
  ];

  export default defineComponent({
    name: 'RoleManagement',
    components: {
      BasicTable,
      RoleModal,
      TableAction,
      RoleAuthModal,
      AuthModal,
      SelectDepartment,
      SelectInterfaceModal,
      PageWrapper,
      HomeModal,
      AppAuthModal,
    },
    setup() {
      const { notification } = useMessage();
      const visible = ref<boolean>(false);
      const selectedUserId = ref<string[]>([]);
      const [registerRoleAuthModal, { openModal: openRoleUserModal }] = useModal();
      const [registerAppAuthModal, { openModal: openAppAuthModal }] = useModal();
      const [registerInterfaceModal, { openModal: openInterfaceModal }] = useModal();
      const [registerModal, { openModal, setModalProps }] = useModal();
      const [registerRoleModal, { openModal: openRoleModal }] = useModal();
      const [registerHomeModal, { openModal: openHomeModal }] = useModal();
      const [registerTable, { reload, getSelectRows }] = useTable({
        title: t('角色列表'),
        api: getRolePageList,
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          actionColOptions: { span: 16 },
          showResetButton: false,
        },
        // clickToRowSelect:true,
        rowSelection: {
          type: 'radio',
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        showIndexColumn: false,
        actionColumn: {
          width: 80,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        tableSetting: {
          size: false,
          setting: false,
        },
      });

      function handleCreate() {
        openRoleModal(true, {
          isUpdate: false,
        });
      }
      function handleInterfaceAuth() {
        let res = warning(true);
        if (!res) {
          return;
        }
        openInterfaceModal(true, {
          isUpdate: false,
          title: t('接口授权') + ' - ' + res.name,
          id: res.id,
        });
      }
      function handleAuth() {
        let res = warning(true);
        if (!res) {
          return;
        }

        openRoleUserModal(true, {
          id: res.id,
        });
      }
      function handleAppAuth() {
        let res = warning(true);
        if (!res) {
          return;
        }

        openAppAuthModal(true, {
          id: res.id,
        });
      }
      function handleAddUser() {
        let rows = warning();
        if (!rows) {
          return;
        }
        getRoleUser(rows.id).then((res) => {
          selectedUserId.value = res.map((item) => {
            return item.id;
          });
          console.log(selectedUserId.value);
          visible.value = true;
        });
      }
      function warning(isAdminCantUse = false) {
        const selectRows = getSelectRows();
        if (selectRows.length === 0) {
          notification.warning({
            message: t('警告'),
            description: t('必须选中一行！'),
          }); //提示消息
          return false;
        } else if (isAdminCantUse && selectRows[0].id === '1') {
          notification.warning({
            message: t('警告'),
            description: t('超级管理员不允许授权'),
          });
          return false;
        } else {
          return selectRows[0];
        }
      }
      function handleSelectUserSuccess(rows, type) {
        const selectRows = getSelectRows();
        let paramas;
        if (type === 0) {
          paramas = { type, id: selectRows[0].id, userIds: rows };
        } else {
          paramas = { type, id: selectRows[0].id, departmentIds: rows };
        }

        addRoleUser(paramas).then((_) => {
          notification.info({
            message: t('添加人员'),
            description: t('成功'),
          }); //提示消息
        });
      }
      function handleInterfaceSuccess(rows) {
        const selectRows = getSelectRows();

        addRoleInterface(selectRows[0].id, rows).then((_) => {
          notification.info({
            message: t('接口授权成功'),
            description: t('成功'),
          }); //提示消息
        });
      }
      function handleViewUser() {
        let rows = warning();
        if (!rows) {
          return;
        }
        getRoleUser(rows.id).then((res) => {
          openModal(true, res);
          setModalProps({ title: t('查看成员') });
        });
      }
      function handleRoleAuthSuccess() {}

      function handleEdit(record: Recordable) {
        openRoleModal(true, {
          record,
          isUpdate: true,
        });
      }

      function handleDelete(record: Recordable) {
        deleteRole([record.id]).then((_) => {
          reload();
          notification.success({
            message: t('删除角色'),
            description: t('成功'),
          }); //提示消息
        });
      }

      function handleSuccess() {
        reload();
      }
      function handleHomeAuth() {
        let res = warning();
        if (!res) {
          return;
        }

        openHomeModal(true, {
          id: res.id,
        });
      }
      function handleLogoutRole() {
        let res = warning();
        if (!res) {
          return;
        }
        Modal.confirm({
          title: '确认是否登出角色用户?',
          // content: '确认是否登出角色用户',
          okText: '是',
          okType: 'danger',
          cancelText: '否',
          onOk() {
            logoutByRoleId(res.id).then((_) => {
              notification.info({
                message: t('登出成功'),
                description: t('成功'),
              }); //提示消息
            });
          },
          onCancel() {
            console.log('Cancel');
          },
        });
      }
      return {
        registerTable,
        registerRoleModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleAuth,
        handleAddUser,
        handleViewUser,
        handleSelectUserSuccess,
        handleInterfaceSuccess,
        registerRoleAuthModal,
        handleRoleAuthSuccess,
        registerModal,
        visible,
        selectedUserId,
        registerInterfaceModal,
        handleInterfaceAuth,
        registerHomeModal,
        handleHomeAuth,
        t,
        registerAppAuthModal,
        handleAppAuth,
        handleLogoutRole,
      };
    },
  });
</script>
