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

defineOptions({ name: 'RwaEditionAdd' });
const emit = defineEmits<{
  (e: 'close'): void;
}>();
const props = defineProps<{
  productId: string;
}>();

type Body = CommonType.TreatyBody<typeof client.api.admin.rwa.issuance.editions.post>;

const formInst = useTemplateRef<FormInst>('formInst');
const form = ref({
  productId: props.productId,
  editionName: '',
  perUserLimit: '1',
  totalSupply: '1',
  unitPrice: '1',
  dividendRate: '0.01',
  launchDate: dayjs().add(1, 'day').valueOf() as number | null,
  subscriptionStartDate: null as number | null,
  subscriptionEndDate: null as number | null
});

const rules: FormRules = {
  editionName: [{ required: true, message: '请输入发行期名称', trigger: ['blur', 'input'] }],
  perUserLimit: [{ required: true, message: '请输入个人申购上限', trigger: ['blur', 'input'] }],
  totalSupply: [{ required: true, message: '请输入发行总量', trigger: ['blur', 'input'] }],
  unitPrice: [{ required: true, message: '请输入单价', trigger: ['blur', 'input'] }],
  dividendRate: [{ required: true, message: '请输入分红率', trigger: ['blur', 'input'] }],
  launchDate: [{ required: true, type: 'number', message: '请选择预热时间', trigger: ['blur', 'change'] }],
  subscriptionStartDate: [
    { required: true, type: 'number', message: '请选择申购开始时间', trigger: ['blur', 'change'] }
  ],
  subscriptionEndDate: [{ required: true, type: 'number', message: '请选择申购结束时间', trigger: ['blur', 'change'] }]
};

// 手动验证时间逻辑
function validateTimes() {
  const now = dayjs();

  if (form.value.launchDate && dayjs(form.value.launchDate).isBefore(now)) {
    return '预热时间必须在当前时间之后';
  }

  if (form.value.subscriptionStartDate && form.value.launchDate) {
    if (dayjs(form.value.subscriptionStartDate).isBefore(dayjs(form.value.launchDate))) {
      return '申购开始时间必须在预热时间之后';
    }
  }

  if (form.value.subscriptionEndDate && form.value.subscriptionStartDate) {
    if (dayjs(form.value.subscriptionEndDate).isBefore(dayjs(form.value.subscriptionStartDate))) {
      return '申购结束时间必须在开始时间之后';
    }
  }

  return null;
}

function handleCreateDraft() {
  formInst.value?.validate(async errors => {
    if (!errors) {
      const timeError = validateTimes();
      if (timeError) {
        window.$message?.error(timeError);
        return;
      }
      await safeClient(
        client.api.admin.rwa.issuance.editions.post({
          ...form.value,
          launchDate: new Date(form.value.launchDate!),
          subscriptionStartDate: new Date(form.value.subscriptionStartDate!),
          subscriptionEndDate: new Date(form.value.subscriptionEndDate!)
        } as Body)
      );
      emit('close');
    }
  });
}
function handleCreateDraftAndSubmit() {
  formInst.value?.validate(async errors => {
    if (!errors) {
      const timeError = validateTimes();
      if (timeError) {
        window.$message?.error(timeError);
        return;
      }
      await safeClient(
        client.api.admin.rwa.issuance.editions.post({
          ...form.value,
          launchDate: new Date(form.value.launchDate!),
          subscriptionStartDate: new Date(form.value.subscriptionStartDate!),
          subscriptionEndDate: new Date(form.value.subscriptionEndDate!)
        } as Body)
      );
      emit('close');
    }
  });
}
</script>

<template>
  <div class="my-10">
    <NForm
      ref="formInst"
      :model="form"
      label-width="150"
      label-placement="left"
      label-align="left"
      :rules="rules"
      require-mark-placement="left"
    >
      <NFormItem path="editionName" label="发行期名称">
        <NInput v-model:value="form.editionName" />
      </NFormItem>
      <NFormItem path="perUserLimit" label="个人申购上限(份)">
        <NInputNumber
          :min="1"
          :step="10"
          :value="Number(form.perUserLimit)"
          @update:value="val => (form.perUserLimit = String(val))"
        />
      </NFormItem>
      <NFormItem path="totalSupply" label="发行总量(份)">
        <NInputNumber
          :min="1"
          :step="100"
          :value="Number(form.totalSupply)"
          @update:value="val => (form.totalSupply = String(val))"
        />
      </NFormItem>
      <NFormItem path="unitPrice" label="单价($)">
        <NInputNumber :min="0" :value="Number(form.unitPrice)" @update:value="val => (form.unitPrice = String(val))" />
      </NFormItem>
      <NFormItem path="dividendRate" label="分红率(0.01 = 1%)">
        <NInputNumber
          :max="1"
          :min="0"
          :step="0.01"
          :value="Number(form.dividendRate)"
          @update:value="val => (form.dividendRate = String(val))"
        />
      </NFormItem>
      <NFormItem path="launchDate" label="预热时间">
        <NDatePicker
          v-model:value="form.launchDate"
          type="datetime"
          format="yyyy-MM-dd HH:mm"
          :is-date-disabled="(ts: number) => ts < Date.now()"
          value-format="x"
        />
      </NFormItem>
      <NFormItem>
        <NSpace vertical class="w-full">
          <NFormItem path="subscriptionStartDate" label="申购开始时间" label-width="150">
            <NDatePicker
              v-model:value="form.subscriptionStartDate"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              :is-date-disabled="(ts: number) => (form.launchDate ? ts < Number(form.launchDate) : false)"
              value-format="x"
              class="w-full"
            />
          </NFormItem>
          <NFormItem path="subscriptionEndDate" label="申购结束时间" label-width="150">
            <NDatePicker
              v-model:value="form.subscriptionEndDate"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              :is-date-disabled="
                (ts: number) => (form.subscriptionStartDate ? ts < Number(form.subscriptionStartDate) : false)
              "
              value-format="x"
              class="w-full"
            />
          </NFormItem>
        </NSpace>
      </NFormItem>

      <NSpace justify="end" class="mt-5">
        <NButton type="primary" ghost @click="handleCreateDraftAndSubmit">创建并提交审核</NButton>
        <NButton type="primary" @click="handleCreateDraft">创建</NButton>
      </NSpace>
    </NForm>
  </div>
</template>

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