<template>
  <BasicModal
    v-bind="$attrs"
    width="720px"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './ringtone.data';
  import { addPushRingtone, editPushRingtone, getPushRingtone } from '/@/api/platform/common/controller/pushRingtone';
  import { BasicModal, ModalProps, useModalInner } from '/@/components/Modal';

  /** 通用变量统一声明区域 */
  const tag = ref<Nullable<string>>('');
  /** https://v3.cn.vuejs.org/api/options-data.html#emits */
  const emit = defineEmits(['success', 'register']);
  const [registerForm, { resetFields, setFieldsValue, validate, clearValidate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 }
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: WindowInnerData = { _tag: '' }) => {
    // 处理清除脏数据
    await resetFields();
    await clearValidate();
    // 处理设置数据
    tag.value = data._tag;
    const refId = data.record?.id;
    const props: Partial<ModalProps> = { confirmLoading: false };
    // 采用tag标签区分操作
    switch (unref(tag)) {
      case 'add':
        props.title = '新增铃声';
        break;
      case 'edit':
        props.title = '编辑铃声';
        let ringtone = await getPushRingtone(refId);
        ringtone.ringtone = String(ringtone.ringtone).split(',');
        await setFieldsValue(ringtone);
        break;
    }
    // 尾部:设置处理后的最终配置数据
    setModalProps(props);
  });

  /** 处理弹出框提交 */
  async function handleSubmit() {
    try {
      // 提取验证数据
      const formData = await validate();
      formData.ringtone = Array(formData.ringtone).join(',');
      // 处理提交之前逻辑
      setModalProps({ confirmLoading: true });
      // 采用tag标签区分操作
      switch (unref(tag)) {
        case 'add':
          await addPushRingtone(formData);
          break;
        case 'edit':
          await editPushRingtone(formData);
          break;
      }
      // 处理提交完成之后逻辑
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
