<script lang="ts" setup>
import { useVbenForm, useVbenModal } from '@vben/common-ui';
import type { languageType } from '#/model/type';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { addLanguageList } from '#/api/core/statistics';
import { $t } from '#/locales'
defineOptions({
  name: 'AddLanguageModal',
});
let ld = [] as languageType[];
const gridOptions: VxeGridProps<languageType> = {
  border: true,
  columns: [
    { title: 'Id', field: 'Id', width: 50 },
    { editRender: { name: 'input' }, field: 'key', title: 'key' },
    { editRender: { name: 'input' }, field: 'en_US', title: 'en_US' },
    {
      editRender: { name: 'input' },
      field: 'zh_CN',
      title: 'zh_CN',
    },
    { editRender: { name: 'input' }, field: 'pt_BR', title: 'pt_BR' },
  ],
  data: ld,
  pagerConfig: {
    enabled: false,
  }
};
const [Grid, GridApi] = useVbenVxeGrid({ gridOptions });
const [Form] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full h-full',
    },
  },
  layout: 'horizontal',
  showDefaultActions: true,
  resetButtonOptions: {
    show: false,
  },
  handleSubmit: async (formValues) => {
    // 调用添加语言接口
    try {
      await addLanguageList(ld);
    } catch (error) {
      console.error('Error adding languages:', error);
    }
  },
  // 水平布局，label和input在同一行
  schema: [
    {
      component: 'Textarea',
      fieldName: 'ToUids',
      label: $t('page.language.newLineContent'),
      componentProps: {
        disabled: false,
        placeholder: 'key | en_US | zh_CN| pt_BR record per line',
        type: 'textarea',
        rows: 8,
        onChange: (e: Event) => {
          ld = [] as languageType[];
          const target = e.target as HTMLTextAreaElement;
          const value = target.value;
          const lines = value.split('\n');
          const newData: languageType[] = lines.map((line, index) => {
            const parts = line.split('|').map(part => part.trim());
            return {
              Id: (ld.length + index + 1),
              key: parts[0] || '',
              en_US: parts[1] || '',
              zh_CN: parts[2] || '',
              pt_BR: parts[3] || '',
            };
          });
          ld = ld.concat(newData);
          GridApi.setGridOptions({
            data: newData,
          });
        },
      },
    },
  ],
});
const [Modal, modalApi] = useVbenModal({
  confirmText: '提交',
  showConfirmButton: false,
  fullscreen: true,
  onOpenChange: (open) => {
    if (!open) {
      ld = [] as languageType[];
      GridApi.setGridOptions({
        data: [],
      });
    }
  },

});
</script>
<template>
  <Modal width="80%">
    <Form />
    <Grid />
  </Modal>
</template>
