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

defineOptions({
  name: 'RoleAddUserOperateModal'
});

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
  }
];

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

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

function closeDrawer() {
  visible.value = false;
}

const emit = defineEmits<{
  (e: 'ok'): void;
}>();
function handleSubmit() {
  authUserSelectAll({ roleId, userIds: checkedRowKeys.value.join(',') }).then(res => {
    if (!res.error) {
      window.$message?.success('授权成功');
      closeDrawer();
      emit('ok');
    }
  });
}
</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>
      <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 type="primary" @click="handleSubmit">确认</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
