<template>
  <div class="p-4">
    <template v-for="src in imgList" :key="src">
      <img :src="src" v-show="false" />
    </template>
    <DetailModal :info="rowInfo" @register="registerModal" />
    <BasicTable @register="register" class="error-handle-table">
      <template #toolbar>
        <c-button @click="fireVueError" type="primary">
          {{ t('sys.errorLog.fireVueError') }}
        </c-button>
        <c-button @click="fireResourceError" type="primary">
          {{ t('sys.errorLog.fireResourceError') }}
        </c-button>
        <c-button @click="fireAjaxError" type="primary">
          {{ t('sys.errorLog.fireAjaxError') }}
        </c-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: t('sys.errorLog.tableActionDesc'),
              onClick: handleDetail.bind(null, record)
            }
          ]"
        />
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts" setup>
  import { watch, ref, nextTick } from 'vue';
  import DetailModal from './DetailModal.vue';
  import { BasicTable, useTable, TableAction } from '@jdlinker/ui';
  import { useModal } from '@jdlinker/ui';
  import { useI18n } from 'vue-i18n';
  import { useMessage, useErrorLogStore } from '@jdlinker/func';
  import { fireErrorApi } from '../../../../api/demo/error';
  import { getColumns } from './data';
  import { cloneDeep } from 'lodash-es';

  const rowInfo = ref<any>();
  const imgList = ref<string[]>([]);

  const { t } = useI18n();
  const errorLogStore = useErrorLogStore();
  const [register, { setTableData }] = useTable({
    title: t('sys.errorLog.tableTitle'),
    columns: getColumns(),
    // @ts-ignore
    actionColumn: {
      width: 80,
      title: 'Action',
      dataIndex: 'action',
      slots: { customRender: 'action' }
    }
  });
  const [registerModal, { openModal }] = useModal();

  watch(
    () => errorLogStore.getErrorLogInfoList,
    (list) => {
      nextTick(() => {
        setTableData(cloneDeep(list));
      });
    },
    {
      immediate: true
    }
  );
  const { createMessage } = useMessage();
  if (import.meta.env.DEV) {
    createMessage.info(t('sys.errorLog.enableMessage'));
  }
  // 查看详情
  function handleDetail(row: ErrorLogInfo) {
    rowInfo.value = row;
    openModal(true);
  }

  function fireVueError() {
    throw new Error('fire vue error!');
  }

  function fireResourceError() {
    imgList.value.push(`${new Date().getTime()}.png`);
  }

  async function fireAjaxError() {
    await fireErrorApi();
  }
</script>
