<script lang="ts" setup>
import { ref, useTemplateRef } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { client, safeClient } from '@/service/api';

defineOptions({ name: 'AddBank' });

type Body = CommonType.TreatyBody<typeof client.api.admin.bank_account.banks.post>;

const emit = defineEmits<{
  (e: 'close'): void;
}>();

const formRef = useTemplateRef<FormInst | null>('formRef');

const form = ref<Body>({
  bankCode: '',
  nameCn: '',
  isActive: true,
  sortOrder: 0
});

const rules: FormRules = {
  bankCode: [
    {
      required: true,
      message: '请输入银行代码',
      trigger: ['blur', 'input']
    },
    {
      pattern: /^[A-Z0-9_]+$/,
      message: '银行代码只能包含大写字母、数字和下划线',
      trigger: ['blur', 'input']
    }
  ],
  nameCn: [
    {
      required: true,
      message: '请输入银行中文名称',
      trigger: ['blur', 'input']
    },
    {
      min: 2,
      max: 100,
      message: '银行名称长度应在2-100个字符之间',
      trigger: ['blur', 'input']
    }
  ],
  sortOrder: [
    {
      required: true,
      type: 'number',
      message: '请输入排序顺序',
      trigger: ['blur', 'change']
    }
  ]
};

async function handleSubmit() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      const { data } = await safeClient(() =>
        client.api.admin.bank_account.banks.post({
          ...form.value
        })
      );
      if (data) {
        window.$message?.success('银行创建成功');
        emit('close');
      }
    }
  });
}
</script>

<template>
  <NForm
    ref="formRef"
    :model="form"
    :rules="rules"
    label-width="100px"
    label-placement="left"
    require-mark-placement="left"
  >
    <NFormItem label="银行代码" path="bankCode">
      <NInput
        v-model:value="form.bankCode"
        placeholder="请输入银行代码（如：ICBC）"
        maxlength="50"
        :input-props="{ style: 'text-transform: uppercase' }"
      />
    </NFormItem>

    <NFormItem label="银行名称" path="nameCn">
      <NInput v-model:value="form.nameCn" placeholder="请输入银行中文名称" maxlength="100" show-count />
    </NFormItem>

    <NFormItem label="排序顺序" path="sortOrder">
      <NInputNumber v-model:value="form.sortOrder" :min="0" :step="1" placeholder="请输入排序顺序" class="w-full">
        <template #suffix>
          <span class="text-12px text-gray-400">数字越小越靠前</span>
        </template>
      </NInputNumber>
    </NFormItem>

    <NFormItem label="是否启用" path="isActive">
      <NSwitch v-model:value="form.isActive">
        <template #checked>启用</template>
        <template #unchecked>禁用</template>
      </NSwitch>
    </NFormItem>

    <NSpace justify="end" class="mt-4">
      <NButton @click="$emit('close')">取消</NButton>
      <NButton type="primary" @click="handleSubmit">创建银行</NButton>
    </NSpace>
  </NForm>
</template>

<style lang="css" scoped></style>
