<script setup lang="tsx">
import { ref, withDirectives } from 'vue';
import { NButton, NImage, NPopconfirm } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useDownLoadFile } from '@/hooks/common/download';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { changePreviewListResource, delOss, listOss } from '@/service/api/system/oss';
import { getConfigKey } from '@/service/api/system/config';
import OssSearch from '@/views/system/oss/modules/oss-search.vue';
import OssUploadModal from '@/views/system/oss/modules/oss-upload-modal.vue';
import OssConfig from '@/views/system/oss/modules/oss-config.vue';
import hasPermission from '@/directive/permission/hasPermission';

const appStore = useAppStore();
const { downLoadOss } = useDownLoadFile();

export type ModelData = {
  visible: boolean;
  type: number;
  file: string;
};
const modelData = ref<ModelData>({
  visible: false,
  type: 0,
  file: ''
});
const previewListResource = ref<boolean>(true);

getConfigKey('sys.oss.previewListResource').then(response => {
  if (response.error) return;
  previewListResource.value = response.response.data.msg === undefined ? true : response.response.data.msg === 'true';
});

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: listOss,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    fileName: null,
    originalName: null,
    fileSuffix: null,
    createBy: null,
    service: null,
    params: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'ossId',
      title: '云存储主键',
      align: 'center'
    },
    {
      key: 'fileName',
      title: '文件名称',
      align: 'center'
    },
    {
      key: 'originalName',
      title: '原名',
      align: 'center'
    },
    {
      key: 'fileSuffix',
      title: '文件后缀',
      align: 'center'
    },
    {
      key: 'url',
      title: '文件展示',
      align: 'center',
      render: row => {
        if (previewListResource.value && checkFileSuffix(row.fileSuffix)) {
          return <NImage src={row.url} alt="图片" width={100} height={100} />;
        }
        return <span>{row.url}</span>;
      }
    },
    {
      key: 'createTime',
      title: '上传时间',
      align: 'center',
      sorter: true
    },
    {
      key: 'createBy',
      title: '上传用户',
      align: 'center'
    },
    {
      key: 'service',
      title: '服务商',
      align: 'center'
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          {withDirectives(
            <NButton type="primary" ghost size="small" onClick={() => handleDownload(row.ossId)}>
              下载
            </NButton>,
            [[hasPermission, ['system:oss:download']]]
          )}
          {withDirectives(
            <div>
              <NPopconfirm onPositiveClick={() => handleDelete(row.ossId)}>
                {{
                  default: () => $t('common.confirmDelete'),
                  trigger: () => (
                    <NButton type="error" ghost size="small">
                      {$t('common.delete')}
                    </NButton>
                  )
                }}
              </NPopconfirm>
            </div>,
            [[hasPermission, ['system:oss:remove']]]
          )}
        </div>
      )
    }
  ]
});

const { checkedRowKeys, onDeleted, onBatchDeleted } = useTableOperate(data, getData);

// 单个删除
function handleDelete(id: Api.SystemManage.Oss['ossId']) {
  delOss([id]).then(res => {
    if (res.error) return;
    onDeleted();
  });
}

// 批量删除
function handleBatchDelete() {
  delOss(checkedRowKeys.value as Api.SystemManage.Oss['ossId'][]).then(res => {
    if (res.error) return;
    onBatchDeleted();
  });
}

// 导出
function handleDownload(id: Api.SystemManage.Oss['ossId']) {
  downLoadOss(id);
}

function checkFileSuffix(fileSuffix: Api.SystemManage.Oss['fileSuffix']) {
  const arr = ['png', 'jpg', 'jpeg'];
  return arr.some(type => {
    return fileSuffix.includes(type);
  });
}

function handleOpen(type: 0 | 1) {
  modelData.value = {
    visible: true,
    type,
    file: ''
  };
}

function handlePreviewListResource(value: boolean) {
  const text = value ? '启用' : '停用';
  changePreviewListResource(value).then(res => {
    if (res.error) {
      previewListResource.value = value !== true;
      return;
    }
    window.$message?.success(`${text}成功`);
    getDataByPage();
  });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <OssSearch v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <NCard title="文件管理" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add-btn="false"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #prefix>
            <NButton v-hasPermission="['system:oss:upload']" type="primary" ghost size="small" @click="handleOpen(0)">
              <template #icon>
                <SvgIcon icon="ep:plus"></SvgIcon>
              </template>
              上传文件
            </NButton>
            <NButton v-hasPermission="['system:oss:upload']" type="primary" ghost size="small" @click="handleOpen(1)">
              <template #icon>
                <SvgIcon icon="ep:plus"></SvgIcon>
              </template>
              上传图片
            </NButton>
          </template>
          <template #middle>
            <div v-hasPermission="['system:oss:edit']">
              <NPopconfirm @positive-click="handlePreviewListResource(!previewListResource)">
                <template #trigger>
                  <NButton type="error" ghost size="small">
                    预览开关 : {{ previewListResource ? '禁用' : '启用' }}
                  </NButton>
                </template>
                确认要{{ previewListResource ? '禁用' : '启用' }}预览列表图片配置吗?'
              </NPopconfirm>
            </div>
            <OssConfig />
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="({ ossId }) => ossId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <OssUploadModal v-model:model-data="modelData" @get-data="getDataByPage" />
    </NCard>
  </div>
</template>

<style scoped></style>
