<script lang="ts" setup>
import { type PropType, reactive, ref, watch } from 'vue';

import { Fallback } from '@vben/common-ui';
import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import { TableApi } from '#/api';

defineOptions({
  name: 'TablePage',
});
const props = defineProps({
  tableQueryCode: {
    type: String,
    default: '',
  },
  multiple: {
    type: Boolean as PropType<boolean>,
    default: false,
  },
  mode: {
    type: String as PropType<'page' | 'popup' | 'view'>,
    default: 'view',
  },
});
const emit = defineEmits(['success']);

const modelRef = ref<Record<string, any>>({});
const state = reactive({
  error: false,
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    toolbarConfig: {
      refresh: true,
      print: false,
      export: false,
      zoom: false,
      custom: false,
    },
    columns: [],
    height: 'auto',
    keepSource: true,
    pagerConfig: {},
    exportConfig: {},
    proxyConfig: {
      autoLoad: false,
    },
  },
});

const loadPage = async (code: string) => {
  const entity: TableApi.RecordItem = await TableApi.getInfo(code);
  modelRef.value = { ...entity };

  const columns: any[] = [{ title: '序号', type: 'seq', width: 50 }];

  let firstCol: any = {};

  entity.config.columns.forEach((item: any, index: number) => {
    const col: any = {
      align: item.align,
      field: item.field,
      title: item.title,
    };

    if (!item.autoWidth) {
      col.width = item.width;
    }

    if (index === 0) {
      firstCol = { ...col };
      if (props.mode === 'popup') {
        col.type = props.multiple ? 'checkbox' : 'radio';
      }
    }

    columns.push(col);
  });

  if (columns.length > 0) {
    const buttons = entity.config?.buttons.filter(
      (btn: any) => btn.position === 'item',
    ).length;

    if (buttons > 0) {
      const col: any = {
        field: 'action',
        fixed: 'right',
        slots: { default: 'action' },
        title: '操作',
        width: buttons > 2 ? 150 : 120,
      };
      columns.push(col);
    }

    const gridState: any = {
      gridOptions: {
        rowConfig: {
          isCurrent: true,
          isHover: true,
        },
        columns,
        proxyConfig: {
          autoLoad: true,
          ajax: {
            query: async ({ page }: any, formValues: any) => {
              return await TableApi.postExecute({
                code: entity.code,
                pageIndex: page.currentPage,
                pageSize: page.pageSize,
                formData: { ...formValues },
              });
            },
          },
        },
      },
    };

    if (props.mode === 'popup') {
      if (props.multiple) {
        gridState.gridOptions.checkboxConfig = {
          highlight: true,
          labelField: firstCol.field,
        };
      } else {
        gridState.gridOptions.radioConfig = {
          highlight: true,
          labelField: firstCol.field,
        };
      }
    }

    const formSchema: any[] = [];
    entity.config.search.forEach((item: any) => {
      const row = {
        ...item.schema,
      };
      formSchema.push(row);
    });

    if (formSchema.length > 0) {
      gridState.formOptions = {
        showCollapseButton: false,
        schema: formSchema,
      };
    }

    gridApi.setState(gridState);

    setTimeout(() => {
      gridApi.reload();
      emit('success');
    }, 500);
  }
};

watch(
  () => props.tableQueryCode,
  async (value) => {
    if (value && value.length > 0) {
      try {
        await loadPage(value);
      } catch {
        state.error = true;
      }
    } else {
      state.error = true;
    }
  },
  { immediate: true },
);

const getSelectRow = () => {
  return props.multiple
    ? gridApi.grid.getCheckboxRecords()
    : gridApi.grid.getRadioRecord();
};

defineExpose({ getSelectRow });
</script>
<template>
  <div class="h-full">
    <template v-if="!state.error">
      <Grid>
        <template #toolbar-tools></template>
      </Grid>
    </template>
    <template v-else>
      <Fallback status="404">
        <template #action></template>
      </Fallback>
    </template>
  </div>
</template>
