<script setup lang="ts">
import { ref, watch } from 'vue';
import type { DataTableColumn } from 'naive-ui';
import { getAuthRole, updateAuthRole } from '@/service/api/system/user';
import { usePagination } from '@/hooks/common/pagination';

defineOptions({
  name: 'UserAuthRoleOperateModal'
});

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

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

// 角色信息
const roles = ref<Api.SystemManage.Role[]>([]);
// 用户信息
const form = ref<Pick<Api.SystemManage.User, 'nickName' | 'phonenumber'>>({
  nickName: '',
  phonenumber: '0'
});
// 选择的值
const checkedRowKeys = ref<Api.SystemManage.Role['roleId'][]>([]);

const { loading, startLoading, endLoading, mobilePagination, updatePagination } = usePagination();

const columns: Array<DataTableColumn> = [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    title: '角色名称',
    key: 'roleName',
    width: 200
  },
  {
    title: '权限字符',
    key: 'roleKey',
    width: 200
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 100
  }
];

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

watch(visible, val => {
  if (val) {
    getAuthRoleDetail();
  }
});

// 因为请求的是全部的数据，需要的是前端分页，不适用useTable
function getAuthRoleDetail() {
  startLoading();
  getAuthRole(userId)
    .then(res => {
      if (!res.error) {
        roles.value = res.data.roles;
        form.value = res.data.user;
        updatePagination({ itemCount: roles.value.length });
        checkedRowKeys.value = roles.value.filter(item => item.flag).map(item => item.roleId);
      }
    })
    .finally(() => {
      endLoading();
    });
}

function handleSubmit() {
  const roleIds = checkedRowKeys.value.join(',');
  updateAuthRole(userId, roleIds).then(() => {
    if (!res.error) {
      window.$message?.success('授权成功');
      closeDrawer();
    }
  });
}
</script>

<template>
  <NModal v-model:show="visible" title="分配角色" preset="card" class="w-1000px">
    <NScrollbar class="max-h-500px pr-20px">
      <NCollapse arrow-placement="right" :default-expanded-names="['user', 'role']">
        <NCollapseItem title="基本信息" name="user">
          <NForm :model="form" label-placement="left" :label-width="80" :show-feedback="false">
            <NGrid responsive="screen" item-responsive>
              <NFormItemGi span="24 m:8" label="用户昵称">
                <NInput v-model:value="form.nickName" :disabled="true" />
              </NFormItemGi>
              <NFormItemGi span="24 m:8" offset="0 m:2" label="手机号码">
                <NInput v-model:value="form.phonenumber" :disabled="true" />
              </NFormItemGi>
            </NGrid>
          </NForm>
        </NCollapseItem>
        <NCollapseItem title="角色信息" name="role">
          <NDataTable
            v-model:checked-row-keys="checkedRowKeys"
            :columns="columns"
            :data="roles"
            size="small"
            :loading="loading"
            remote
            :row-key="row => row.roleId"
            :pagination="mobilePagination"
          />
        </NCollapseItem>
      </NCollapse>
    </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>
