<script lang="ts" setup>
import type { OnActionClickParams, VxeTableGridOptions } from '#/adapter';

import { onMounted, reactive, ref, unref } from 'vue';
import { useRoute } from 'vue-router';

import { AccessControl } from '@vben/access';
import { alert, Fallback, Page, useVbenModal } from '@vben/common-ui';

import { Button } from 'ant-design-vue';

import { useTableGridOptions, useVbenVxeGrid } from '#/adapter';
import { CmsArticleApi, CmsSiteChannelApi } from '#/api';

import FormEdit from './components/edit.vue';
import { useColumns, useSearchSchema } from './data.config';

const route = useRoute();

const state = reactive<{
  authCode: string;
  error: boolean;
  siteChannelId: string;
}>({
  error: false,
  siteChannelId: (route.query?.id || '') as string,
  authCode: '',
});

const modelRef = ref<Record<string, any>>({});

const conditionInfo = reactive<Record<string, any>>({});

const [FormEditModal, formEditApi] = useVbenModal({
  connectedComponent: FormEdit,
});

const handelSuccess = () => {
  reload();
};
const handleDelete = async (id: number) => {
  await CmsArticleApi.deleteDetail(id);
  alert('数据删除成功');
  handelSuccess();
};

const handleUpdateStatus = async (record: any) => {
  await CmsArticleApi.updateStatus({
    id: record.id,
    status: record.status === 1 ? 2 : 1,
  });
  handelSuccess();
};

const handleEdit = (record: any, isUpdate: boolean) => {
  formEditApi
    .setData({
      isUpdate,
      baseData: { id: record.id },
      conditionInfo: { ...conditionInfo },
    })
    .open();
};

const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<CmsArticleApi.RecordItem>) => {
  switch (code) {
    case 'delete': {
      await handleDelete(row.id);
      break;
    }
    case 'edit': {
      handleEdit(row, true);
      break;
    }
    case 'setStatus': {
      await handleUpdateStatus(row);
      break;
    }
  }
};

const [Grid, { setState, reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      fieldMappingTime: [['__date', ['startTime', 'endTime']]],
      schema: [],
    },
    gridOptions: {
      columns: [],
      proxyConfig: {
        autoLoad: false,
        ajax: {
          query: async ({ page }, formValues) => {
            return await CmsArticleApi.getPage({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              ...conditionInfo,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);

const loadPage = async () => {
  state.authCode = `${unref(modelRef).code}-content`;

  const schema = useSearchSchema(conditionInfo);
  const columns: VxeTableGridOptions<CmsArticleApi.RecordItem>['columns'] =
    useColumns(handleActionClick, state.authCode);

  setState({ formOptions: { schema }, gridOptions: { columns } });

  setTimeout(() => {
    reload();
  }, 500);
};

onMounted(async () => {
  try {
    modelRef.value = await CmsSiteChannelApi.getDetail(
      Number(state.siteChannelId),
    );
    conditionInfo.siteId = modelRef.value.siteId;
    conditionInfo.siteChannelId = modelRef.value.id;
    loadPage();
  } catch {
    state.error = true;
  }
});
</script>

<template>
  <Page auto-content-height>
    <Fallback status="500" v-if="state.error">
      <template #action></template>
    </Fallback>
    <template v-else>
      <FormEditModal @success="handelSuccess" />
      <Grid>
        <template #toolbar-tools>
          <AccessControl :codes="[`${state.authCode}:add`]" type="code">
            <Button
              class="mr-2"
              type="primary"
              @click="() => handleEdit({}, false)"
            >
              新增内容
            </Button>
          </AccessControl>
        </template>
      </Grid>
    </template>
  </Page>
</template>
