<script setup lang="tsx">
import { ref, watch, withDirectives } from 'vue';
import { type DataTableColumn, NButton, NPopconfirm, NTag } from 'naive-ui';
import { usePagination } from '@/hooks/common/pagination';
import { allocatedUserList, authUserCancel, authUserCancelAll } from '@/service/api/system/role';
import { $t } from '@/locales';
import { specialEnableStatusRecord } from '@/constants/business';
import SearchForm from '@/components/advanced/search-form.vue';
import hasPermission from '@/directive/permission/hasPermission';

defineOptions({
  name: 'RoleAuthUserOperateModal'
});

const { roleId } = defineProps<{
  roleId: Api.SystemManage.Role['roleId'];
}>();

const visible = defineModel<boolean>('visible', { default: false });

// 用户信息
const userList = ref<Api.SystemManage.User[]>([]);
// 选中的值
const checkedRowKeys = ref<Api.SystemManage.User['userId'][]>([]);

const { loading, mobilePagination, searchParams, startLoading, endLoading, updatePagination, resetSearchParams } =
  usePagination({
    queryParams: {
      roleId: '',
      userName: null,
      phonenumber: null
    }
  });

const columns: Array<DataTableColumn> = [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    title: '用户名称',
    key: 'userName',
    width: 180
  },
  {
    title: '用户昵称',
    key: 'nickName',
    width: 130
  },
  {
    title: '邮箱',
    key: 'email',
    width: 140
  },
  {
    title: '手机号',
    key: 'phonenumber',
    width: 130
  },
  {
    title: '状态',
    key: 'status',
    width: 120,
    align: 'center',
    render: row => {
      if (row.status === null) {
        return null;
      }
      const tagMap: Record<Api.Common.SpecialEnableStatus, NaiveUI.ThemeColor> = {
        '0': 'success',
        '1': 'warning'
      };
      const label = $t(specialEnableStatusRecord[row.status as Api.Common.SpecialEnableStatus]);
      return <NTag type={tagMap[row.status as Api.Common.SpecialEnableStatus]}>{label}</NTag>;
    }
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 160
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    width: 150,
    render: row => {
      return (
        <div>
          {withDirectives(
            <div>
              <NPopconfirm onPositiveClick={() => handleCancel(row.userId as Api.SystemManage.User['userId'])}>
                {{
                  default: () => `确认取消用户“${row.nickName}”角色吗？`,
                  trigger: () => (
                    <NButton type="primary" ghost size="small">
                      取消授权
                    </NButton>
                  )
                }}
              </NPopconfirm>
            </div>,
            [[hasPermission, ['system:role:remove']]]
          )}
        </div>
      );
    }
  }
];

watch(visible, val => {
  if (val) {
    getList();
  } else {
    resetSearchParams();
    checkedRowKeys.value = [];
  }
});

function handleCancel(id: Api.SystemManage.User['userId']) {
  authUserCancel({ userId: id, roleId }).then(res => {
    if (!res.error) {
      getList();
      window.$message?.success('取消授权成功');
    }
  });
}

// 取消授权
function batchCancel() {
  authUserCancelAll({ roleId, userIds: checkedRowKeys.value.join(',') }).then(res => {
    if (!res.error) {
      getList();
      window.$message?.success('取消授权成功');
    }
  });
}

function getList() {
  startLoading();
  searchParams.value.roleId = roleId;
  allocatedUserList(searchParams.value)
    .then(res => {
      if (!res.error) {
        userList.value = res.data.data;
        updatePagination({ itemCount: res.response.data.total });
      }
    })
    .finally(() => {
      endLoading();
    });
}

const emit = defineEmits<{
  (e: 'addUser'): void;
}>();

function addUser() {
  emit('addUser');
}

defineExpose({ getList });
</script>

<template>
  <NModal v-model:show="visible" title="分配用户" preset="card" class="w-1200px">
    <NScrollbar class="max-h-500px pr-20px">
      <NSpace wrap justify="start" class="mb-20px">
        <SearchForm v-model:model="searchParams" @reset="resetSearchParams" @search="getList">
          <template #formItem>
            <NFormItemGi span="24 s:12 m:6" label="用户名称" class="pr-24px">
              <NInput v-model:value="searchParams.userName" placeholder="请输入用户名称" />
            </NFormItemGi>
            <NFormItemGi span="24 s:12 m:6" label="手机号" class="pr-24px">
              <NInput v-model:value="searchParams.phonenumber" placeholder="请输入手机号" />
            </NFormItemGi>
          </template>
        </SearchForm>
      </NSpace>
      <NSpace wrap justify="end" class="mb-20px lt-sm:w-200px">
        <NButton v-hasPermission="['system:role:add']" size="small" ghost type="primary" @click="addUser">
          <template #icon>
            <icon-ic-round-plus class="text-icon" />
          </template>
          添加用户
        </NButton>
        <div v-hasPermission="['system:role:remove']">
          <NPopconfirm @positive-click="batchCancel">
            <template #trigger>
              <NButton size="small" ghost type="error" :disabled="checkedRowKeys.length === 0">
                <template #icon>
                  <icon-ic-round-delete class="text-icon" />
                </template>
                取消授权
              </NButton>
            </template>
            确认取消授权吗？
          </NPopconfirm>
        </div>
        <NButton size="small" @click="getList">
          <template #icon>
            <icon-mdi-refresh class="text-icon" :class="{ 'animate-spin': loading }" />
          </template>
          {{ $t('common.refresh') }}
        </NButton>
      </NSpace>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="userList"
        size="small"
        :loading="loading"
        remote
        :row-key="row => row.userId"
        :pagination="mobilePagination"
      />
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <!--<NButton @click="closeDrawer">取消</NButton>-->
        <NButton @click="visible = false">关闭</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
