<script lang="ts" setup>
import type { VxeGridProps, VxeGridListeners } from '#/adapter/vxe-table';
import { Button } from 'ant-design-vue';
import { Page } from '@vben/common-ui';
import { getLanguageList, exportLanguageFile, saveLanguageList } from '#/api/core/statistics';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import addLanguage from './addLanguage.vue';
import type { VbenFormProps } from '#/adapter/form';
import type { languageType, languageRecord } from '#/model/type';
import type { languageParam } from '#/api/core/statistics';
import { useVbenModal } from '@vben/common-ui';
import dayjs from 'dayjs';
const [AddLanguageModal, AddLanguageModalApi] = useVbenModal({
  connectedComponent: addLanguage,
});
let oldData: languageType[] = [];
let newData: languageType[] = [];
let op: languageRecord[] = [];
let lastOp: languageRecord[] = [];
let lastUpdate: string = '';
const startDate = dayjs().subtract(7, 'day').startOf('day');
const endDate = dayjs().endOf('day');
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Select',
      componentProps: {
        filterOption: true,
        options: [
          { label: '键值', value: 'key' },
          { label: '英文', value: 'English' },
          { label: '简体中文', value: 'ChineseSimplified' },
          { label: '葡萄牙语', value: 'Portuguese' },
        ],
        placeholder: 'key',
        showSearch: true,
      },
      fieldName: 'SearchField',
      label: '搜索列：',
    },
    {
      component: 'Input',
      componentProps: {
        filterOption: true,
        placeholder: 'Merge',
        showSearch: true,
      },
      fieldName: 'SearchValue',
      label: '值：',
    },
    {
      component: 'DatePicker',
      defaultValue: startDate,
      componentProps: {
        format: 'YYYY-MM-DD',
      },
      fieldName: 'StartTime',
      label: '开始时间',
      formItemClass: 'col-start-1',
    },
    {
      component: 'TimePicker',
      componentProps: {
        placeholder: '时间',
      },
      fieldName: 'StartTime',
      label: '--',

    },
    {
      component: 'DatePicker',
      defaultValue: endDate,
      componentProps: {
        format: 'YYYY-MM-DD',
      },
      fieldName: 'EndTime',
      label: '结束时间',

    },
    {
      component: 'TimePicker',
      componentProps: {
        placeholder: '时间',
      },
      fieldName: 'EndTime',
      label: '--',
    }
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-5',
  // 是否在字段值改变时提交表单
  submitOnChange: true,
  // 按下回车时是否提交表单
  submitOnEnter: false,
}
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: '葡萄牙语' },
  ],
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  rowClassName: ({ rowIndex }: { rowIndex: number }) => {
    const i = oldData[rowIndex];
    if (!i) {
      return 'row-yellow';
    }
    const info = lastOp.find((item) => String(item.LanguageId) == String(i.Id) && item.Type === 'Add');
    if (info) {
      return 'row-yellow';
    }
  },
  cellClassName: ({ row, column }) => {
    const info = oldData.find((item) => item.Id === row.Id);
    if (info) {
      const prop = (column.field || column.field) as keyof languageType;
      const oldValue = info[prop];
      const newValue = row[prop];
      if (oldValue != newValue) {
        console.log('Cell changed2:', prop, 'from', oldValue, 'to', newValue);
        return 'row-green';
      }
      if (lastOp.find(opItem => opItem.LanguageId === row.Id && opItem.Field === prop && opItem.Type === 'Edit')) {
        return 'row-green';
      }
    }
  },
  proxyConfig: {
    response: {
      total: "total",
      result: "data"
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const response = await getLanguageList({
          PageSize: page.pageSize,
          CurrentPage: page.currentPage,
          StartTime: formValues.StartTime ? Math.floor(new Date(formValues.StartTime).getTime() / 1000) : undefined,
          EndTime: formValues.EndTime ? Math.floor(new Date(formValues.EndTime).getTime() / 1000) : undefined,
          SearchField: formValues.SearchField,
          SearchValue: formValues.SearchValue,
        } as languageParam);
        newData = response.data || [];
        oldData = newData.map(item => ({ ...item }));
        console.log('API response:', response);
        lastOp = response.op || [];
        // 设置 lastUpdate 为 lastOp 最后一条记录的 update 字段（格式：YYYY - MM - DD HH: mm: ss）
        if (lastOp && lastOp.length > 0) {
          const last = lastOp[lastOp.length - 1];
          const raw = last?.Update;
          if (raw != null) {
            let ts: any = raw;
            // 如果是数字字符串，转为数字
            if (typeof ts === 'string' && /^\d+$/.test(ts)) ts = Number(ts);
            // 如果是 10 位时间戳（秒），转换为毫秒
            if (typeof ts === 'number' && String(ts).length === 10) ts = ts * 1000;
            lastUpdate = dayjs(ts).format('YYYY-MM-DD HH:mm:ss');
          } else {
            lastUpdate = '';
          }
        } else {
          lastUpdate = '';
        }
        return {
          data: response.data || [],
          total: response.total || 0,
        };
      }
    }
  },
  editConfig: {
    mode: 'cell',
    trigger: 'dblclick',
  },
  pagerConfig: {
    enabled: true,
    pageSize: 80,
  },
  height: 'auto',
  showOverflow: true,
};
const gridEvents: VxeGridListeners<languageType> = {
  editClosed: ({ row, column }) => {
    const info = oldData.find((item) => item.Id === row.Id);
    if (info) {
      const prop = (column.field || column.field) as keyof languageType;
      const oldValue = info[prop];
      const newValue = row[prop];

      if (oldValue !== newValue) {
        console.log('Cell changed:', prop, 'from', oldValue, 'to', newValue);
        // 更新 newData 中的记录（若存在则替换，否则新增）
        const newItem = newData.find((item) => item.Id === row.Id);
        if (newItem) {
          op.push({
            LanguageId: row.Id,
            Field: String(prop),
            OldValue: oldValue,
            NewValue: newValue,
            Type: 'Edit',
          } as languageRecord);
          Object.assign(newItem, row);
        } else {
          newData.push({ ...(row as languageType) });
        }
      } else {
        console.log('Cell not changed:', prop);
      }
    }
    //console.log('editClosed:', row, column);
  },
};
const [Grid, GridApi] = useVbenVxeGrid({ formOptions, gridOptions, gridEvents });

function addRow() {
  AddLanguageModalApi.open();
}
function saveAll() {
  saveLanguageList(op).then((response) => {
    console.log('Save response:', response);
    op = [];
    GridApi.reload();
  });
}

function downloadCSV(data: languageType[]) {
  const headers = ['Id', 'key', 'English', 'ChineseSimplified'];
  const csvRows = [];
  csvRows.push(headers.join(','));
  for (const row of data) {
    const values = headers.map(header => {
      const escaped = (row as any)[header]?.toString().replace(/"/g, '""') || '';
      return `"${escaped}"`;
    });
    csvRows.push(values.join(','));
  }
  const csvContent = csvRows.join('\n');
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  link.setAttribute('href', url);
  link.setAttribute('download', 'language_export.csv');
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

function exportLang() {
  exportLanguageFile().then((response) => {
    // downloadCSV(response.data);
  });
}
</script>

<style lang="css">
.row-green {
  background-color: #1ecf0d;
}

.row-yellow {
  background-color: #f2ff00;
}
</style>
<template>


  <Page auto-content-height>
    <AddLanguageModal width="1200px" title="添加翻译"></AddLanguageModal />
    <Grid>
      <template #toolbar-tools>
        <span class="mr-4 font-bold">最后修改日期：{{ lastUpdate }}</span>
        <Button class="mr-2" type="primary" @click="addRow">
          新增行
        </Button>
        <Button type="primary" @click="saveAll" class="mr-2"> 保存 </Button>
        <Button type="primary" @click="exportLang"> git提交 </Button>
      </template>
    </Grid>
  </Page>
</template>
