<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createTransferQuestion, updateTransferQuestion } from '../api';
import { modalFormProps } from '../config/form';

const isUpdate = ref(false);
const gridApi = ref();

const [Form, formApi] = useVbenForm(modalFormProps);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    formApi.validate().then(async (e: any) => {
      if (e.valid) {
        const values = await formApi.getValues();
        
        // 处理answers字段：将换行分隔的字符串转换为数组
        if (values.answers) {
          if (typeof values.answers === 'string') {
            // 按换行符分割，过滤空行，去除首尾空格
            values.answers = values.answers
              .split('\n')
              .map((item: string) => item.trim())
              .filter((item: string) => item.length > 0);
          }
          // 如果转换后为空数组，设置默认值
          if (!Array.isArray(values.answers) || values.answers.length === 0) {
            values.answers = ['是', '否'];
          }
        } else {
          // 如果没有提供，设置默认值
          values.answers = ['是', '否'];
        }
        
        modalApi.setState({ loading: true, confirmLoading: true });
        const submitApi = isUpdate.value ? updateTransferQuestion : createTransferQuestion;
        submitApi(values)
          .then(() => {
            message.success('保存成功');
            gridApi.value?.reload();
            modalApi.close();
          })
          .finally(() => {
            modalApi.setState({ loading: false, confirmLoading: false });
          });
      }
    });
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    gridApi.value = isOpen ? modalApi.getData()?.gridApi : null;
    if (isOpen) {
      const { values, update } = modalApi.getData<Record<string, any>>();
      if (values) {
        isUpdate.value = update;
        
        // 处理answers字段：如果是数组或JSON字符串，转换为换行分隔的字符串
        if (values.answers) {
          if (Array.isArray(values.answers)) {
            values.answers = values.answers.join('\n');
          } else if (typeof values.answers === 'string' && values.answers.trim().startsWith('[')) {
            try {
              const parsed = JSON.parse(values.answers);
              if (Array.isArray(parsed)) {
                values.answers = parsed.join('\n');
              }
            } catch (e) {
              // 解析失败，保持原值
            }
          }
        } else {
          // 如果没有值，设置默认值
          values.answers = '是\n否';
        }
        
        formApi.setValues(values);
      }
    }
  },
});
</script>
<template>
  <Modal
    :title="`${isUpdate === true ? '编辑' : '新增'}转诊问题`"
    class="w-[60%]"
  >
    <Form />
  </Modal>
</template>
