<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { AddUserInfo, UpDateUserInfo, fetchGetAllRoles } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';

defineOptions({
  name: 'UserOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.User | 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, passwordRules } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.user.addUser'),
    edit: $t('page.manage.user.editUser')
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.SystemManage.User,
  'USER_CODE' | 'USER_NAME' | 'USER_PASSWORD' | 'USER_REMARK' | 'userRoles' | 'status'
>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    USER_NAME: '',
    USER_CODE: '',
    USER_PASSWORD: '',
    USER_REMARK: '',
    userRoles: [],
    status: null
  };
}

type RuleKey = Extract<keyof Model, 'USER_NAME' | 'USER_CODE' | 'USER_PASSWORD' | 'userRoles' | 'status'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  USER_NAME: defaultRequiredRule,
  USER_CODE: defaultRequiredRule,
  USER_PASSWORD: passwordRules,
  userRoles: defaultRequiredRule,
  status: defaultRequiredRule
};

/** the enabled role options */
const roleOptions = ref<CommonType.Option<string>[]>([]);

async function getRoleOptions() {
  const { error, data } = await fetchGetAllRoles();
  if (!error) {
    const options = data.data.map(item => ({
      label: item.roleName,
      value: item.roleCode
    }));

    // // the mock data does not have the roleCode, so fill it
    // // if the real request, remove the following code
    // const userRoleOptions = model.userRoles.map(item => ({
    //   label: item,
    //   value: item
    // }));
    // // end

    roleOptions.value = [...options];
    // roleOptions.value = [...userRoleOptions, ...options];
  }
}

function handleInitModel() {
  Object.assign(model, createDefaultModel());

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

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

async function handleSubmit() {
  await validate();
  if (props.operateType === 'edit') {
    // 修改信息
    const delinfo = await UpDateUserInfo(model);

    if (delinfo.response !== undefined) {
      if (delinfo.response.data.code === '0000') {
        window.$message?.success(delinfo.response.data.msg as string);
        closeDrawer();
        emit('submitted');
      }
    }
  } else {
    // 新增账户
    const delinfo = await AddUserInfo(model);

    if (delinfo.response !== undefined) {
      if (delinfo.response.data.code === '0000') {
        window.$message?.success(delinfo.response.data.msg as string);
        closeDrawer();
        emit('submitted');
      }
    }
  }
  // // request
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
</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="用户名称" path="USER_NAME">
          <NInput v-model:value="model.USER_NAME" :placeholder="$t('page.manage.user.form.userName')" />
        </NFormItem>
        <NFormItem label="账号" path="USER_CODE">
          <NInput v-model:value="model.USER_CODE" placeholder="请输入账号" />
        </NFormItem>
        <NFormItem label="密码" path="USER_PASSWORD">
          <NInput v-model:value="model.USER_PASSWORD" placeholder="请输入密码" />
        </NFormItem>
        <NFormItem label="备注" path="USER_REMARK">
          <NInput v-model:value="model.USER_REMARK" placeholder="请输入备注信息" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.user.userStatus')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
        <!--
 <NFormItem :label="$t('page.manage.user.userRole')" path="userRoles">
          <NSelect
            v-model:value="model.userRoles"
            multiple
            :options="roleOptions"
            :placeholder="$t('page.manage.user.form.userRole')"
          />
        </NFormItem>
-->
      </NForm>
      <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>
