<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" class="!pt-4">
      <template #whiteList="{ model }">
        <a-textarea v-model:value="model.whiteList" placeholder="请填写白名单" />
        <span style="color: #bfbfbf">
          此处为填写IP白名单，如果存在多个IP，则使用","隔开，例如：192.168.0.1,192.168.0.155
        </span>
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="tsx" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    addDeveloper,
    getDeveloperInfo,
    updateDeveloper,
    generatedSign,
  } from '/@/api/system/developer';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const accountFormSchema: FormSchema[] = [
    {
      field: 'code',
      label: '开发者编码',
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请填写开发者编码',
      },
      colProps: { span: 12 },
    },
    {
      field: 'name',
      label: '开发者名称',
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请填写开发者名称',
      },
      colProps: { span: 12 },
    },
    {
      field: 'appId',
      label: 'appId',
      component: 'Input',
      required: true,
      componentProps: ({ formModel }) => {
        return {
          placeholder: '请填写appId',
          onBlur: async () => {
            if (formModel.appId === '' || formModel.appSecret === '') {
              return;
            }
            const res = await generatedSign({
              appId: formModel.appId,
              appSecret: formModel.appSecret,
              expireDate: formModel.expireDate,
            });
            formModel.sign = res;
          },
        };
      },
      colProps: { span: 12 },
    },
    {
      field: 'appSecret',
      label: 'appSecret',
      component: 'Input',
      required: true,
      componentProps: ({ formModel }) => {
        return {
          placeholder: '请填写appSecret',
          onBlur: async () => {
            if (formModel.appId === '' || formModel.appSecret === '') {
              return;
            }
            const res = await generatedSign({
              appId: formModel.appId,
              appSecret: formModel.appSecret,
              expireDate: formModel.expireDate,
            });
            formModel.sign = res;
          },
        };
      },
      colProps: { span: 12 },
    },
    {
      field: 'appName',
      label: '应用名称',
      component: 'Input',
      required: true,
      componentProps: {
        placeholder: '请填写应用名称',
      },
      colProps: { span: 12 },
    },
    {
      field: 'validateSign',
      label: '验证签名',
      component: 'Switch',
      defaultValue: 1,
      colProps: { span: 12 },
    },
    {
      field: 'expireDate',
      label: '使用期限',
      component: 'DatePicker',
      colProps: { span: 12 },
      componentProps: ({ formModel }) => {
        return {
          placeholder: '请选择到期时间',
          format: 'YYYY-MM-DD HH:mm:ss',
          style: { width: '100%' },
          getPopupContainer: () => document.body,
          onBlur: async () => {
            if (formModel.appId === '' || formModel.appSecret === '') {
              return;
            }
            const res = await generatedSign({
              appId: formModel.appId,
              appSecret: formModel.appSecret,
              expireDate: formModel.expireDate,
            });
            formModel.sign = res;
          },
        };
      },
    },
    {
      field: 'enabledMark',
      label: '状态',
      component: 'Switch',
      defaultValue: 1,
      colProps: { span: 12 },
    },
    {
      field: 'sign',
      label: '签名',
      component: 'Input',
      colProps: { span: 24 },
      componentProps: {
        placeholder: '修改appid 以及 appSecret 后需要重新生成签名',
        readonly: true,
      },
    },
    {
      field: 'whiteList',
      label: '白名单',
      component: 'InputTextArea',
      slot: 'whiteList',
      colProps: { span: 24 },
    },
    {
      field: 'remark',
      label: '备注',
      component: 'InputTextArea',
      componentProps: {
        placeholder: t('请填写备注'),
      },
      colProps: { span: 24 },
    },
  ];

  const emit = defineEmits(['success', 'register']);

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    layout: 'vertical',
    rowProps: { gutter: 32 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, width: 900 });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getDeveloperInfo(data.id);

      setFieldsValue({
        ...record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增开发者' : '编辑开发者'));

  async function handleSubmit() {
    try {
      const values = await validate();

      setModalProps({ confirmLoading: true });
      if (!unref(isUpdate)) {
        await addDeveloper(values);
        notification.success({
          message: t('提示'),
          description: '新增开发者成功！',
        });
      } else {
        values.id = unref(rowId);
        await updateDeveloper(values);
        notification.success({
          message: t('提示'),
          description: '编辑开发者成功！',
        });
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
