<script setup lang="ts" name="Oss">
import apis from "@a"
import Rs from "@@/services/RequestService"
import Config from "./_config.vue"
import appStore from "@s"

const serviceOptions = ref<any>([])

const tableRef = ref()
const modalRef = ref()
const officePreviewRef = ref()
const opts = reactive({
	columns: [
		{ field: "ossId", name: "主键", width: 100, isSort: true, visible: false },
		{ field: "originalName", name: "原名", visible: true, isSort: false, width: "auto" },
		{ field: "fileSuffix", name: "文件后缀名", visible: true, isSort: false, width: 100 },
		{ field: "url", name: "文件展示", visible: true, isSort: false, width: "auto" },
		{ field: "service", name: "服务商", visible: true, isSort: false, width: 200 },
		{ field: "createTime", name: "上传时间", visible: true, isSort: true, width: 185 },
		{ field: "actions", name: `操作`, width: 150 }
	] as any,
	queryParams: {
		fileName: undefined,
		originalName: undefined,
		service: undefined
	},
	searchFormItems: [
		{
			field: "fileName",
			label: "文件名",
			class: "w-100",
			required: false,
			placeholder: "请输入文件名",
			component: "I",
			listeners: {
				keyup: (e: KeyboardEvent) => {
					if (e.code == "Enter") {
						handleQuery()
					}
				}
			}
		},
		{
			field: "originalName",
			label: "原名",
			class: "w-100",
			required: false,
			placeholder: "请输入原名",
			component: "I",
			listeners: {
				keyup: (e: KeyboardEvent) => {
					if (e.code == "Enter") {
						handleQuery()
					}
				}
			}
		},
		{
			field: "service",
			label: "服务商",
			class: "w-100",
			required: false,
			component: "VS",
			placeholder: "请选择服务商",
			data: () => serviceOptions.value,
			props: {
				valueIsNumber: false,
				type: "select"
			}
		}
	] as any,
	permission: "system:oss",
	handleBtns: [],
	handleFuns: {
		handleUpload,
		handleDelete,
		handleConfig
	},
	customBtns: [],
	tableListFun: apis.system.ossApi.list,
	getEntityFun: apis.system.ossApi.get,
	deleteEntityFun: apis.system.ossApi.del,
	exportUrl: apis.system.ossApi.exportUrl,
	exportName: "Oss",
	modalTitle: "文件上传",
	formItems: [
		{
			field: "uploadType",
			label: "上传类型",
			class: "w-100",
			required: true,
			placeholder: "请输入文件名",
			component: "VS",
			props: {
				type: "radio",
				data: [
					{ label: "图片", value: "image" },
					{ label: "文件", value: "file" }
				]
			}
		},
		{
			show: () => {
				return form.value.uploadType == "file"
			},
			field: "s",
			label: "上传文件",
			class: "w-100",
			component: "VU",
			props: {
				uploadType: "file",
				uploadUrl: "",
				limit: 1,
				fileType: ["doc", "xls", "ppt", "txt", "pdf"]
			}
		},
		{
			show: () => {
				return form.value.uploadType == "image"
			},
			field: "s",
			label: "上传图片",
			class: "w-100",
			component: "VU",
			props: {
				prefixUrl: "/resource/oss/",
				uploadType: "image"
			},
			listeners: {
				delete: onDeleteFile
			}
		}
	] as any,
	resetForm: () => {
		form.value = emptyFormData.value
	},
	labelWidth: "80px",
	emptyFormData: {
		uploadType: "image"
	}
})
const { queryParams, emptyFormData } = toRefs(opts)
const form = ref<any>(emptyFormData.value)

/** 搜索按钮操作 */
function handleQuery(query?: any) {
	query = query || tableRef.value?.getQueryParams() || queryParams.value
	addDateRange(query, query.dateRangeCreateTime)
	addDateRange(query, query.dateRangeUpdateTime, "UpdateTime")
	tableRef.value?.query(query)
}

/** 重置按钮操作 */
function resetQuery(query?: any) {
	query = query || tableRef.value?.getQueryParams() || queryParams.value
	query.dateRangeCreateTime = [] as any
	addDateRange(query, query.dateRangeCreateTime)
	query.dateRangeUpdateTime = [] as any
	addDateRange(query, query.dateRangeUpdateTime, "UpdateTime")
	//
}

/** 上传按钮操作 */
function handleUpload() {
	opts.resetForm()
	modalRef.value.show()
}
/** 下载按钮操作 */
function handleDownload(row: any) {
	Rs.download("/resource/oss/download/" + row.ossId, row.originalName)
}

/** 删除按钮操作 */
function handleDelete(rows: any[]) {
	message.confirm("确认删除文件吗？删除后可能会影响部分页面的显示！", "删除文件").then(() => {
		const ids = rows.map((v: any) => v.ossId)
		apis.system.ossApi.del(ids).then(() => {
			handleQuery()
		})
	})
}

function handlePreviewOffice(row: any) {
	officePreviewRef.value.open({
		fileId: row.objectId,
		fileName: row.originalName
	})
}

function onDeleteFile(file: any) {
	console.log("delete", file)
	if (file.id) {
		apis.system.ossApi.del(file.id).then(() => {})
	}
}
function checkFileType(fileName: any) {
	if (!appStore.appConfigStore.isOssPreview()) {
		return false
	}
	const arr = fileName.split(".")
	const ext = arr[arr.length - 1]
	if (["png", "jpg", "jpeg"].some((item) => item === ext)) {
		return true
	}
	return false
}

const configModalRef = ref()
const configViewRef = ref()

function handleConfig() {
	configModalRef.value?.show()
	configViewRef.value?.query()
}
function getServiceOptions() {
	apis.system.ossConfigApi.list({ pageSize: 1000 }).then((res: any) => {
		serviceOptions.value = res.rows.map((item: any) => {
			return {
				label: item.configKey,
				value: item.configKey
			}
		})
	})
}
getServiceOptions()
</script>
<template>
	<div class="app-container">
		<VbTable
			ref="tableRef"
			keyField="ossId"
			:columns="opts.columns"
			:handle-perm="opts.permission"
			:handle-btns="opts.handleBtns"
			:handle-funs="opts.handleFuns"
			:search-form-items="opts.searchFormItems"
			:custom-btns="opts.customBtns"
			:remote-fun="opts.tableListFun"
			:get-entity-fun="opts.getEntityFun"
			:delete-entity-fun="opts.deleteEntityFun"
			:export-url="opts.exportUrl"
			:export-name="opts.exportName"
			:page-size="appStore.appConfigStore.isOssPreview() ? 10 : 15"
			:page-size-array="[appStore.appConfigStore.isOssPreview() ? 10 : 15, 25, 50]"
			:modal="modalRef"
			:reset-form-fun="opts.resetForm"
			v-model:form-data="form"
			v-model:query-params="queryParams"
			:check-multiple="true"
			:reset-search-form-fun="resetQuery"
			:custom-search-fun="handleQuery">
			<template #url="{ row }">
				<template v-if="checkFileType(row.originalName)">
					<VbImagePreview
						:src="row.objectId"
						:image-style="{ marginTop: '6px', marginBottom: '' }"></VbImagePreview>
				</template>
				<span v-else>
					<el-button size="small" type="primary" @click="handlePreviewOffice(row)">预览</el-button>
				</span>
			</template>
			<template #service="{ row }">
				<VbTag :data="serviceOptions" :value-is-number="false" :value="row.service"></VbTag>
			</template>
			<template #actions="{ row }">
				<vb-tooltip content="下载" placement="top">
					<el-button
						link
						type="primary"
						@click="handleDownload(row)"
						v-hasPermission="'system:oss:download'">
						<template #icon>
							<VbIcon icon-name="file-down" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
				<vb-tooltip content="删除" placement="top">
					<el-button
						link
						type="primary"
						@click="handleDelete([row])"
						v-hasPermission="'system:oss:remove'">
						<template #icon>
							<VbIcon icon-name="trash-square" icon-type="duotone" class="fs-3"></VbIcon>
						</template>
					</el-button>
				</vb-tooltip>
			</template>
		</VbTable>
		<VbOfficePreview ref="officePreviewRef" />
		<VbModal
			v-model:modal="modalRef"
			:title="opts.modalTitle"
			:form-data="form"
			:form-items="opts.formItems"
			:form-label-width="opts.labelWidth"
			:close-btn="false"
			confirm-btn-text="关闭"
			append-to-body
			@confirm="handleQuery"></VbModal>

		<VbModal
			v-model:modal="configModalRef"
			title="文件服务器配置"
			modal-dialog-style="width:1600px;max-width:1600px;"
			modal-body-class="pt-0"
			append-to-body>
			<template #body>
				<Config ref="configViewRef"></Config>
			</template>
		</VbModal>
	</div>
</template>
