<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { fetchAddRoleMenu, fetchEditRoleMenu, fetchGetMenuList, fetchGetRoleMenuList } from '@/service/api';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { buildMenuTree } from '@/utils/zt';
import { $t } from '@/locales';
defineOptions({
  name: 'RoleOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.Role | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

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

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.role.addRole'),
    edit: $t('page.manage.role.editRole')
  };
  return titles[props.operateType];
});
const tree = ref([]);
const checks = ref<number[]>([]);
type Model = Pick<Api.SystemManage.RoleMenuList, 'roleName' | 'remark'>;

const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    roleName: '',
    remark: ''
  };
}

type RuleKey = Exclude<keyof Model, 'remark'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  roleName: defaultRequiredRule
};

const roleId = computed(() => props.rowData?.roleId || -1);

async function handleEdit() {
  const { data } = await fetchGetRoleMenuList(roleId.value);
  checks.value = data?.menuIdList as number[];
}

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
    handleEdit();
  }
}

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

async function handleSubmit() {
  await validate();
  // request

  if (props.operateType == 'add') {
    await fetchAddRoleMenu({ ...model.value, menuIdList: checks.value });
  } else {
    await fetchEditRoleMenu({ ...model.value, menuIdList: checks.value, roleId: roleId.value });
  }
  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}
async function getTree() {
  const { data } = await fetchGetMenuList();
  const menuData = buildMenuTree(data);
  if (menuData) {
    tree.value = menuData;
  }
}
getTree();
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.manage.role.roleName')" path="roleName">
          <NInput v-model:value="model.roleName" :placeholder="$t('page.manage.role.form.roleName')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.role.roleDesc')" path="remark">
          <NInput v-model:value="model.remark" :placeholder="$t('page.manage.role.form.roleDesc')" />
        </NFormItem>
      </NForm>
      <!--
 <NSpace>
        <NButton @click="openMenuAuthModal">{{ $t('page.manage.role.menuAuth') }}</NButton>
        <MenuAuthModal v-model:visible="menuAuthVisible" :role-id="roleId" />

 <NButton @click="openButtonAuthModal">{{ $t('page.manage.role.buttonAuth') }}</NButton>
        <ButtonAuthModal v-model:visible="buttonAuthVisible" :role-id="roleId" />

      </NSpace>
-->
      <NTree
        v-model:checked-keys="checks"
        :data="tree"
        checkable
        expand-on-click
        virtual-scroll
        block-line
        class="h-280px"
        label-field="name"
        key-field="menuId"
      />
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
