<template>
  <PageWrapper dense fixedHeight contentFullHeight>
    <BasicTable @register="registerTable" isMenuTable>
      <template #toolbar>
        <a-button type="primary" v-auth="'role:add'" @click="handleCreate">
          {{ t('新增角色') }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              auth: 'role:addMember',
              label: '添加成员',
              onClick: handleAddUser.bind(null, record),
            },
            {
              auth: 'role:view',
              label: '查看成员',
              onClick: handleViewUser.bind(null, record),
            },
            {
              auth: 'role:functionalAuth',
              label: '功能授权',
              onClick: handleAuth.bind(null, record),
            },
            {
              auth: 'role:functionalAuth',
              label: '移动端功能授权',
              onClick: handleAppAuth.bind(null, record),
            },
            {
              auth: 'role:homeAuth',
              label: '首页授权',
              onClick: handleHomeAuth.bind(null, record),
            },
            {
              label: '编辑',
              auth: 'role:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              auth: 'role:delete',
              color: 'error',
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <RoleModal @register="registerRoleModal" @success="handleSuccess" />
    <RoleAuthModal
      @register="registerRoleAuthModal"
      @success="handleRoleAuthSuccess"
      :minHeight="500"
    />
    <AppAuthModal @register="registerAppAuthModal" :minHeight="500" />
    <SelectDepartment
      v-if="visible"
      :visible="visible"
      :multiple="true"
      :selectedList="selectedUserList"
      @close="
        () => {
          visible = false;
        }
      "
      @change="handleSelectUserSuccess"
    />
    <AuthModal @register="registerModal" />

    <HomeModal @register="registerHomeModal" @success="handleRoleAuthSuccess" :minHeight="0" />
  </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,
    updateRoleStatus,
  } from '/@/api/system/role';
  import AuthModal from './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 } from 'ant-design-vue';
  import { PageWrapper } from '/@/components/Page';
  import { useModal } from '/@/components/Modal';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();

  const { t } = useI18n();
  export const columns: BasicColumn[] = [
    {
      title: t('角色名称'),
      dataIndex: 'name',
      resizable: true,
    },
    {
      title: t('角色编码'),
      dataIndex: 'code',
      resizable: true,
    },
    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      resizable: true,
      customRender: ({ record }) => {
        if (!Reflect.has(record, 'pendingStatus')) {
          record.pendingStatus = false;
        }
        return h(Switch, {
          checked: record.enabledMark === 1,
          checkedChildren: t('已启用'),
          unCheckedChildren: t('已禁用'),
          loading: record.pendingStatus,
          disabled: !hasPermission('role:edit'),
          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',
      resizable: true,
    },
  ];

  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 selectedUserList = ref<any>([]);
      const selectedId = ref('');
      const [registerRoleAuthModal, { openModal: openRoleUserModal }] = useModal();
      const [registerAppAuthModal, { openModal: openAppAuthModal }] = useModal();
      const [registerModal, { openModal, setModalProps }] = useModal();
      const [registerRoleModal, { openModal: openRoleModal }] = useModal();
      const [registerHomeModal, { openModal: openHomeModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        title: t('角色列表'),
        api: getRolePageList,
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          actionColOptions: { span: 16 },
          showResetButton: false,
        },
        // clickToRowSelect:true,
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        showIndexColumn: false,
        actionColumn: {
          width: 500,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('role:edit')) {
                handleEdit(record);
              }
            },
          };
        },
      });

      function handleCreate() {
        openRoleModal(true, {
          isUpdate: false,
        });
      }
      function handleAuth(record) {
        if (record.id === '1') {
          notification.warning({
            message: t('警告'),
            description: t('超级管理员不允许授权'),
          });
          return;
        }
        openRoleUserModal(true, {
          id: record.id,
        });
      }
      function handleAppAuth(record) {
        if (record.id === '1') {
          notification.warning({
            message: t('警告'),
            description: t('超级管理员不允许授权'),
          });
          return;
        }
        openAppAuthModal(true, {
          id: record.id,
        });
      }
      function handleAddUser(record) {
        selectedId.value = record.id;
        getRoleUser(record.id).then((res) => {
          selectedUserList.value = res.map((item) => {
            return {
              name: item.name, //姓名
              id: item.id, //ID
              code: item.code, //code
              gender: !isNaN(item.gender) ? item.gender : -1, //性别
            };
          });
          visible.value = true;
        });
      }

      function handleSelectUserSuccess(rows, type) {
        let paramas;
        if (type === 0) {
          paramas = { type, id: selectedId.value, userIds: rows };
        } else {
          paramas = { type, id: selectedId.value, departmentIds: rows };
        }

        addRoleUser(paramas).then((_) => {
          notification.info({
            message: t('添加人员'),
            description: t('成功'),
          }); //提示消息
        });
      }
      function handleViewUser(record) {
        openModal(true, record.id);
        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(record) {
        openHomeModal(true, {
          id: record.id,
        });
      }
      return {
        registerTable,
        registerRoleModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleAuth,
        handleAddUser,
        handleViewUser,
        handleSelectUserSuccess,
        registerRoleAuthModal,
        handleRoleAuthSuccess,
        registerModal,
        visible,
        selectedUserList,
        registerHomeModal,
        handleHomeAuth,
        t,
        registerAppAuthModal,
        handleAppAuth,
      };
    },
  });
</script>
