<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';
defineOptions({
  name: 'AddLanguageModal',
});
let ld = [] as languageType[];
const gridOptions: VxeGridProps<languageType> = {
  border: true,
  columns: [
    { title: '序号', field: 'Id', width: 50 },
    { editRender: { name: 'input' }, field: 'key', title: '键值' },
    { editRender: { name: 'input' }, field: 'English', title: '英文' },
    {
      editRender: { name: 'input' },
      field: 'ChineseSimplified',
      title: '简体中文',
    },
    { editRender: { name: 'input' }, field: 'Portuguese', title: '葡萄牙语' },
  ],
  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) => {
    console.log('Submitting form with values:', formValues);
    console.log('Language data to add:', ld);
    // 调用添加语言接口
    try {
      await addLanguageList(ld);
      modalApi.close();
    } catch (error) {
      console.error('Error adding languages:', error);
    }
  },
  // 水平布局，label和input在同一行
  schema: [
    {
      component: 'Textarea',
      fieldName: 'ToUids',
      label: '新增翻译',
      componentProps: {
        disabled: false,
        placeholder: 'key | English | 简体中文| 葡萄牙语，一行一条记录',
        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] || '',
              English: parts[1] || '',
              ChineseSimplified: parts[2] || '',
              Portuguese: parts[3] || '',
            };
          });
          ld = ld.concat(newData);
          GridApi.setGridOptions({
            data: newData,
          });
        },
      },
    },
  ],
});
const [Modal, modalApi] = useVbenModal({
  confirmText: '提交',
  showConfirmButton: false,
  fullscreen: true,

});
</script>
<template>
  <Modal width="100%" title="添加翻译">
    <Form />
    <Grid />
  </Modal>
</template>
