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

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

import { useVbenForm } from '#/adapter/form';
import {
  getCommonGetSelectList,
  postDataDictionaryCreateDetail,
  postDataDictionaryUpdateDetail,
} from '#/api-client/index';
import { $t } from '#/locales';

defineOptions({
  name: 'DataDictionaryDetailModal',
});

const emit = defineEmits(['reload']);
const data = ref<Record<string, any>>({});

const formSchema = computed(() => [
  {
    component: 'Input',
    componentProps: {
      disabled: true,
    },
    fieldName: 'typeDisplayText',
    label: $t('abp.dataDictionary.type'),
  },
  {
    component: 'Input',
    componentProps: {
      placeholder: $t('common.pleaseInput'),
    },
    fieldName: 'code',
    label: $t('abp.dataDictionary.code'),
    rules: 'required',
  },
  {
    component: 'Input',
    componentProps: {
      placeholder: $t('common.pleaseInput'),
    },
    fieldName: 'displayText',
    label: $t('abp.dataDictionary.name'),
    rules: 'required',
  },
  {
    component: 'Input',
    componentProps: {
      placeholder: $t('common.pleaseInput'),
    },
    fieldName: 'order',
    label: $t('abp.dataDictionary.order'),
    rules: 'required',
  },
  {
    component: 'ApiSelect',
    componentProps: {
      api: getCommonGetSelectList,
      params: {
        query: {
          typeName: 'StandardThingModelDataTypeEnum',
        },
      },
      labelField: 'value',
      valueField: 'secondValue',
      optionsPropName: 'options',
      immediate: true,
      allowClear: true,
      placeholder:
        $t('common.pleaseSelect') +
        $t('abp.dataDictionary.extendedAttribute'),
      afterFetch: (res: any) => {
        if (Array.isArray(res)) {
          return res;
        }
        if (res && Array.isArray(res.items)) {
          return res.items;
        }
        if (res && Array.isArray(res.data)) {
          return res.data;
        }
        return [];
      },
    },
    fieldName: 'extendedAttribute',
    label: $t('abp.dataDictionary.extendedAttribute'),
    rules: 'required',
  },
  {
    component: 'Textarea',
    componentProps: {
      placeholder: '{"InputData":[],"OutputData":[]}',
      rows: 6,
    },
    fieldName: 'extendedAttributeValue',
    label: $t('abp.dataDictionary.extendedAttributeValue'),
    defaultValue: '',
  },
  {
    component: 'Textarea',
    componentProps: {
      placeholder: $t('common.pleaseInput'),
    },
    fieldName: 'description',
    label: $t('abp.dataDictionary.description'),
  },
]);

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  showDefaultActions: false,
  layout: 'horizontal',
  schema: formSchema.value,
  wrapperClass: 'grid-cols-1',
});

function formatExtendedAttributeValue(value: any): string {
  if (!value) return '';
  if (typeof value === 'string') {
    try {
      JSON.parse(value);
      return value;
    } catch {
      return JSON.stringify(value, null, 2);
    }
  }
  return JSON.stringify(value, null, 2);
}

function parseExtendedAttributeValue(value: string): any {
  if (!value || value.trim() === '') return undefined;
  try {
    return JSON.parse(value);
  } catch {
    return undefined;
  }
}

const [Modal, modalApi] = useVbenModal({
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      data.value = modalApi.getData<Record<string, any>>();
      if (data.value.isEdit) {
        const row = data.value.row;
        formApi.setValues({
          ...row,
          typeDisplayText: data.value.type,
          extendedAttributeValue: formatExtendedAttributeValue(
            row.extendedAttributeValue,
          ),
        });
      } else {
        formApi.setValues({ typeDisplayText: data.value.type });
      }
    }
  },
  onConfirm: async () => {
    try {
      modalApi.setState({ loading: true, confirmLoading: true });
      const { valid } = await formApi.validate();
      if (!valid) return;
      const values = await formApi.getValues();

      const submitData: Record<string, any> = {
        ...values,
        extendedAttributeValue: parseExtendedAttributeValue(
          values.extendedAttributeValue,
        ),
      };

      await (data.value.isEdit
        ? postDataDictionaryUpdateDetail({
            body: {
              ...submitData,
              id: data.value.row.id,
              dataDictionaryId: data.value.id,
            },
          })
        : postDataDictionaryCreateDetail({
            body: { ...submitData, id: data.value.id },
          }));
      emit('reload');
      modalApi.close();
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
});
</script>
<template>
  <Modal :title="data.isEdit ? $t('common.edit') : $t('common.add')">
    <Form />
  </Modal>
</template>
