<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { OssFile } from '#/api/system/oss';

import { onMounted, ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { useAppConfig } from '@vben/hooks';
import { stringify } from '@vben/request';
import { useAccessStore } from '@vben/stores';
import { getVxePopupContainer } from '@vben/utils';

import {
  Button,
  Image,
  message,
  Popconfirm,
  Space,
  Spin,
  Switch,
  Tooltip,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { checkLoginBeforeDownload, ossList, ossRemove } from '#/api/system/oss';
import { configInfoByKey } from '#/api/system/sysConfig';
import { GhostButton } from '#/components/global/button';
import { downloadByUrl } from '#/utils/file/download';

import { supportImageList } from './constant';
import { querySchema, useColumns } from './data';
import fallbackImageBase64 from './fallback-image.txt?raw';
import fileUploadModal from './file-upload-modal.vue';
import imageUploadModal from './image-upload-modal.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginCreateTime]', 'params[endCreateTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

// const [FormDrawer, formDrawerApi] = useVbenDrawer({
//   connectedComponent: Form,
// });

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: {
    columns: useColumns(),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues = {}) => {
          return await ossList({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    headerCellConfig: {
      height: 44,
    },
    cellConfig: {
      height: 65,
    },
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: true,
    },
  } as VxeTableGridOptions,
});

const { apiURL, clientId } = useAppConfig(
  import.meta.env,
  import.meta.env.PROD,
);
const accessStore = useAccessStore();

/**
 * 浏览器直接接管下载 相较于axios请求 不会阻塞
 * @param row oss信息
 */
async function handleDownload(row: OssFile) {
  await checkLoginBeforeDownload();

  const params = {
    clientid: clientId,
    Authorization: `Bearer ${accessStore.accessToken}`,
  };

  const downloadLink = `${apiURL}/resource/oss/download/${row.id}?${stringify(params)}`;
  // fileName不设置也行 默认会取header里的名称
  downloadByUrl({ fileName: row.fileName, url: downloadLink });
}

const preview = ref(false);
onMounted(async () => {
  const previewStr = await configInfoByKey('sys.oss.previewListResource');
  preview.value = previewStr === 'true';
});

/**
 * 根据拓展名判断是否是图片
 * @param ext 拓展名
 */
function isImageFile(ext: string) {
  return supportImageList.some((item) =>
    ext.toLocaleLowerCase().includes(item),
  );
}

/**
 * 判断是否是pdf文件
 * @param ext 扩展名
 */
function isPdfFile(ext: string) {
  return ext.toLocaleLowerCase().includes('pdf');
}

/**
 * pdf预览 使用浏览器接管
 * @param url 文件地址
 */
function pdfPreview(url: string) {
  window.open(url);
}

const [ImageUploadModal, imageUploadApi] = useVbenModal({
  connectedComponent: imageUploadModal,
});

const [FileUploadModal, fileUploadApi] = useVbenModal({
  connectedComponent: fileUploadModal,
});

// function onActionClick({ code, row }: OnActionClickParams<OssApi.Oss>) {
//   switch (code) {
//     case 'delete': {
//       onDelete(row);
//       break;
//     }
//     case 'edit': {
//       onEdit(row);
//       break;
//     }
//     default: {
//       break;
//     }
//   }
// }

function onRefresh() {
  gridApi.query();
}
// function onEdit(row: OssFile) {
//   formDrawerApi.setData(row).open();
// }
// function onCreate() {
//   formDrawerApi.setData({}).open();
// }
function onDelete(row: OssFile) {
  const hideLoading = message.loading({
    content: `正在删除${row.fileName}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  ossRemove(row.id || 0)
    .then(() => {
      message.success({
        content: `${row.fileName}删除成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}
// function handleDownloadExcel() {
//   commonDownloadExcel(apiExport, 'OSS对象存储', gridApi.formApi.form.values);
// }
</script>
<template>
  <Page auto-content-height>
    <Grid table-title="文件列表">
      <template #toolbar-tools>
        <Space>
          <Tooltip title="预览图片">
            <Switch v-model:checked="preview" />
          </Tooltip>
          <!-- <Button
            v-access:code="['system:ossConfig:list']"
            @click="handleToSettings"
          >
            配置管理
          </Button> -->
          <!-- <Button
            :disabled="!vxeCheckboxChecked(gridApi)"
            danger
            type="primary"
            v-access:code="['system:oss:remove']"
            @click="handleMultiDelete"
          >
            删除
          </Button> -->
          <Button
            v-access:code="['system:oss:upload']"
            @click="fileUploadApi.open"
          >
            文件上传
          </Button>
          <Button
            v-access:code="['system:oss:upload']"
            @click="imageUploadApi.open"
          >
            图片上传
          </Button>
        </Space>
      </template>
      <template #url="{ row }">
        <!-- placeholder为图片未加载时显示的占位图 -->
        <!-- fallback为图片加载失败时显示 -->
        <!-- 需要设置key属性 否则切换翻页会有延迟 -->
        <Image
          :key="row.ossId"
          v-if="preview && isImageFile(row.url)"
          :src="row.url"
          height="50px"
          :fallback="fallbackImageBase64"
        >
          <template #placeholder>
            <div class="flex size-full items-center justify-center">
              <Spin />
            </div>
          </template>
        </Image>
        <!-- pdf预览 使用浏览器开新窗口 -->
        <span
          v-else-if="preview && isPdfFile(row.url)"
          class="icon-[vscode-icons--file-type-pdf2] size-10 cursor-pointer"
          @click.stop="pdfPreview(row.url)"
        ></span>
        <span v-else>{{ row.url }}</span>
      </template>
      <template #action="{ row }">
        <Space>
          <GhostButton
            v-access:code="['system:oss:download']"
            @click="handleDownload(row)"
          >
            下载
          </GhostButton>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="onDelete(row)"
          >
            <GhostButton
              danger
              v-access:code="['system:oss:remove']"
              @click.stop=""
            >
              删除
            </GhostButton>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
    <ImageUploadModal @reload="gridApi.query" />
    <FileUploadModal @reload="gridApi.query" />
  </Page>
</template>
