<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { SysClientApi } from '#/api/system/sysClient';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { getVxePopupContainer } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { apiAdd, apiUpdate } from '#/api/system/sysClient';
import { getDictOptions } from '#/utils/dict';
import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import SecretInput from './secret-input.vue';

const emit = defineEmits<{
  success: [];
}>();
const isUpdate = ref(false);

const formSchema: VbenFormSchema[] = [
  {
    component: 'Input',
    dependencies: {
      show: () => false,
      triggerFields: [''],
    },
    fieldName: 'id',
    label: 'id',
  },
  {
    component: 'Input',
    fieldName: 'clientId',
    label: '客户端id',
    disabled: true,
  },
  {
    component: 'Input',
    fieldName: 'clientKey',
    label: '客户端key',
    rules: 'required',
  },
  {
    component: 'Input',
    fieldName: 'clientSecret',
    label: '客户端秘钥',
    rules: 'required',
  },
  {
    component: 'Select',
    componentProps: {
      getVxePopupContainer,
      mode: 'multiple',
      optionFilterProp: 'label',
      options: getDictOptions(DictEnum.SYS_GRANT_TYPE),
    },
    fieldName: 'grantTypeList',
    label: '授权类型',
    rules: 'selectRequired',
  },
  {
    component: 'Select',
    componentProps: {
      allowClear: false,
      getVxePopupContainer,
      options: getDictOptions(DictEnum.SYS_DEVICE_TYPE),
    },
    fieldName: 'deviceType',
    label: '设备类型',
    rules: 'selectRequired',
  },
  {
    component: 'Input',
    componentProps: {
      addonAfter: '秒',
      placeholder: '请输入',
    },
    defaultValue: 1800,
    fieldName: 'activeTimeout',
    formItemClass: 'col-span-2 lg:col-span-1',
    help: '指定时间无操作则过期(单位：秒), 默认30分钟(1800秒)',
    label: 'token活跃超时时间',
    rules: 'required',
  },
  {
    component: 'Input',
    componentProps: {
      addonAfter: '秒',
    },
    defaultValue: 604_800,
    fieldName: 'timeout',
    formItemClass: 'col-span-2 lg:col-span-1 ',
    help: '指定时间必定过期(单位：秒)，默认七天(604800秒)',
    label: 'token固定超时时间',
    rules: 'required',
  },
  {
    component: 'RadioGroup',
    componentProps: {
      buttonStyle: 'solid',
      optionType: 'button',
      options: getDictOptions(DictEnum.SYS_COMMON_STATUS, true),
      // disabled: (row: SysClientApi.Client) => {
      //   return !!(row.id === 1);
      // },
    },
    fieldName: 'status',
    defaultValue: 1,
    label: '状态',
    rules: 'required',
  },
];

const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
  },
  layout: 'vertical',
  schema: formSchema,
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: defaultFormValueGetter(formApi),
    currentGetter: defaultFormValueGetter(formApi),
  },
);

const [Drawer, drawerApi] = useVbenDrawer({
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: onSubmit,
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return null;
    }
    const data = drawerApi.getData<SysClientApi.Client>();
    isUpdate.value = !!data?.id;
    // 初始化
    updateForm(isUpdate.value);
    formApi.updateSchema([
      {
        componentProps: { disabled: isUpdate.value && data.id === 1 },
        fieldName: 'status',
      },
    ]);
    if (isUpdate.value) {
      await formApi.setValues(data);
    } else {
      formApi.resetForm();
    }
    await markInitialized();
  },
});

function updateForm(update: boolean) {
  formApi.updateSchema([
    {
      dependencies: {
        show: () => update,
        triggerFields: [''],
      },
      fieldName: 'clientId',
    },
    {
      componentProps: {
        disabled: update,
      },
      fieldName: 'clientKey',
    },
    {
      componentProps: {
        disabled: update,
      },
      fieldName: 'clientSecret',
    },
  ]);
}

async function onSubmit() {
  const { valid } = await formApi.validate();
  if (valid) {
    drawerApi.lock();
    const data = await formApi.getValues<SysClientApi.Client>();
    try {
      // await apiSave({ id: formData.value.id || 0, ...data });
      await (isUpdate.value ? apiUpdate(data) : apiAdd(data));
      resetInitialized();
      emit('success');
      drawerApi.close();
    } finally {
      drawerApi.unlock();
    }
  }
}

async function handleClosed() {
  await formApi.resetForm();
  resetInitialized();
}

const getDrawerTitle = computed(() =>
  isUpdate.value ? '修改终端信息' : '新增终端信息',
);
</script>
<template>
  <Drawer class="w-[600px]" :title="getDrawerTitle">
    <BasicForm class="mx-4">
      <template #clientSecret="slotProps">
        <SecretInput v-bind="slotProps" :disabled="isUpdate" />
      </template>
    </BasicForm>
  </Drawer>
</template>
