<template>
	<div class="operation-menu-wrapper" :class="'file-type-' + fileType" ref="operationMenuRef">
		<a-space
			class="create-operate-group"
			v-if="
				(!selectedFiles.length || !isBatchOperation) &&
				fileType !== 8 &&
				fileType !== 6 &&
				fileType !== 12 &&
				fileType !== 13
			"
		>
			<a-dropdown class="upload-drop">
				<a-button type="primary" id="uploadFileId" class="btnsy"> <UploadOutlined />上传<DownOutlined /> </a-button>
				<template #overlay>
					<a-menu class="scwj">
						<a-menu-item @click="handleUploadFileBtnClick(1)">上传文件</a-menu-item>
						<a-menu-item @click="handleUploadFileBtnClick(2)" v-if="isandiord">上传文件夹</a-menu-item>
						<a-menu-item @click="handleUploadFileBtnClick(3)" title="截图粘贴或拖拽上传" :disabled="screenWidth <= 520"
							>拖拽上传</a-menu-item
						>
					</a-menu>
				</template>
			</a-dropdown>

			<a-dropdown class="create-drop">
				<a-button type="primary" id="uploadFileId" class="btnsy"> <PlusOutlined />新建<DownOutlined /> </a-button>
				<template #overlay>
					<a-menu>
						<a-menu-item @click="handleClickAddFolderBtn">
							<div class="img-text-wrapper"><img :src="dirImg" /> 新建文件夹</div>
						</a-menu-item>
					</a-menu>
				</template>
			</a-dropdown>
		</a-space>
		<div class="batch-operate-group">
			<a-space v-if="isBatchOperation">
				<a-button type="primary" v-if="selectedFiles.length" @click="handleBatchDeleteBtnClick">
					<DeleteOutlined />批量删除
				</a-button>
				<a-button
					type="primary"
					v-if="selectedFiles.length && !fileType && fileType !== 6"
					@click="handleBatchMoveBtnClick"
				>
					批量移动
				</a-button>
				<a-button type="primary" v-if="selectedFiles.length && fileType !== 6" @click="handleBatchDownloadBtnClick">
					<DownloadOutlined />批量下载
				</a-button>
				<a-button
					type="primary"
					v-if="selectedFiles.length && fileType !== 6 && $route.name !== 'Share'"
					@click="handleBatchShareBtnClick"
				>
					<ShareAltOutlined />批量分享
				</a-button>
			</a-space>
		</div>

		<!-- 全局搜索文件 -->
		<a-input-search
			v-if="fileType === 0"
			class="select-file-input"
			v-model:value="searchFile.fileName"
			placeholder="搜索您的文件"
			allow-clear
			@change="handleSearchInputChange"
			@clear="$emit('getTableDataByType')"
			@search="handleSearchInputChange"
		>
		</a-input-search>

		<!-- 批量操作 -->
		<CheckCircleOutlined
			class="batch-icon"
			:class="isBatchOperation ? 'active' : ''"
			:title="isBatchOperation ? '取消批量操作' : '批量操作'"
			v-if="fileModel === 1 && fileType !== 8"
			@click="handleBatchOperationChange()"
		/>
		<ReloadOutlined class="refresh-icon" title="刷新文件列表" @click="$emit('getTableDataByType')" />
		<a-divider type="vertical"></a-divider>
		<template v-if="screenWidth > 768">
			<!-- 文件展示模式 -->
			<UnorderedListOutlined
				class="model-icon"
				:class="{ active: fileGroupLable === 0 }"
				title="列表模式"
				@click="handleFileDisplayModelChange(0)"
			/>
			<AppstoreOutlined
				class="model-icon"
				:class="{ active: fileGroupLable === 1 }"
				title="网格模式"
				@click="handleFileDisplayModelChange(1)"
			/>
			<CalendarOutlined
				class="model-icon"
				title="时间线模式"
				v-if="fileType === 1"
				@click="handleFileDisplayModelChange(2)"
			/>
			<a-divider type="vertical"></a-divider>
		</template>

		<!-- 操作栏收纳 -->
		<a-popover
			v-model:open="operatePopoverVisible"
			placement="bottom"
			:trigger="screenWidth <= 768 ? 'click' : 'hover'"
		>
			<template #content>
				<!-- 选择表格列 -->
				<SelectColumn></SelectColumn>
				<!-- 文件展示模式 -->
				<div class="change-file-model" v-if="screenWidth <= 768">
					<div class="title">查看模式</div>
					<a-radio-group v-model:value="fileGroupLable" button-style="solid" @change="handleFileDisplayModelChange">
						<a-radio-button :value="0" class="btn1"> <UnorderedListOutlined /> 列表 </a-radio-button>
						<a-radio-button :value="1"> <AppstoreOutlined /> 网格 </a-radio-button>
						<a-radio-button :value="2" v-if="fileType === 1"> <CalendarOutlined /> 时间线 </a-radio-button>
					</a-radio-group>
				</div>
				<template v-if="fileGroupLable === 1 || fileGroupLable === 2">
					<a-divider class="split-line"></a-divider>
					<!-- 图标大小调整 -->
					<div class="change-grid-size">
						<div class="title">调整图标大小</div>
						<a-slider
							v-model:value="gridSize"
							:min="20"
							:max="150"
							:step="10"
							:tip-formatter="formatTooltip"
						></a-slider>
					</div>
				</template>
			</template>
			<SettingOutlined class="setting-icon" @click="operatePopoverVisible = !operatePopoverVisible" />
		</a-popover>

		<!-- 多选文件下载，页面隐藏 -->
		<a target="_blank" :href="batchDownloadLink" ref="batchDownloadRef"></a>
	</div>
</template>

<script setup>
	import { ref, computed, watch, onMounted } from 'vue'
	import { useRoute } from 'vue-router'
	import { message } from 'ant-design-vue'
	import config from '@/config/reSource'
	import { storeToRefs } from 'pinia'
	const { proxy } = getCurrentInstance()

	// 定义组件可以触发的事件
	const emit = defineEmits(['getTableDataByType', 'getSearchFileList'])

	import {
		UploadOutlined,
		PlusOutlined,
		DeleteOutlined,
		DownloadOutlined,
		ShareAltOutlined,
		CheckCircleOutlined,
		ReloadOutlined,
		UnorderedListOutlined,
		AppstoreOutlined,
		CalendarOutlined,
		SettingOutlined,
		DownOutlined
	} from '@ant-design/icons-vue'
	import SelectColumn from './SelectColumn.vue'
	import { useMyResourceStore } from '@/store/myResource'

	const route = useRoute()
	const myResourceStore = useMyResourceStore()

	const props = defineProps({
		// 文件类型
		fileType: {
			required: true,
			type: Number
		},
		// 文件路径
		filePath: {
			required: true,
			type: String
		}
	})

	// 文件搜索数据
	const searchFile = ref({
		fileName: ''
	})
	const operatePopoverVisible = ref(false) //  收纳栏是否显示
	const fileGroupLable = ref(0) //  文件展示模式
	const dirImg = ref(new URL('@/assets/images/myResource/file/dir.png', import.meta.url).href)
	// const wordImg = ref(require('@/assets/images/file/file_word.svg'))
	// const excelImg = ref(require('@/assets/images/file/file_excel.svg'))
	// const pptImg = ref(require('@/assets/images/file/file_ppt.svg'))
	const isandiord = ref(true)
	const batchDownloadRef = ref(null)

	// 上传文件组件参数
	const uploadFileParams = computed(() => {
		return {
			filePath: props.filePath,
			isDir: 0
		}
	})

	// 文件查看模式 0 列表模式 1 网格模式 2 时间线模式
	const { getFileModel } = storeToRefs(myResourceStore)
	const fileModel = computed({
		get: () => getFileModel.value
	})
	// 图标大小
	const gridSize = computed({
		get: () => myResourceStore.gridSize,
		set: (val) => myResourceStore.changeGridSize(val)
	})

	// 被选中的文件列表
	const selectedFiles = computed(() => myResourceStore.selectedFiles)

	// 是否批量操作
	const isBatchOperation = computed(() => myResourceStore.isBatchOperation)

	// 屏幕宽度
	const screenWidth = computed(() => myResourceStore.screenWidth)

	// 批量下载文件链接
	const batchDownloadLink = computed(() => {
		return `${config.baseContext}/filetransfer/batchDownloadFile?userFileIds=${selectedFiles.value
			.map((item) => item.userFileId)
			.join(',')}`
	})

	// 显示拖拽上传文件遮罩
	watch(
		() => myResourceStore.showUploadMask,
		() => {
			handleUploadFileBtnClick(3)
		}
	)
	watch(
		() => props.fileType,
		(newValue, oldValue) => {
			if (oldValue === 1 && fileModel.value === 2) {
				myResourceStore.changeFileModel(0)
				fileGroupLable.value = 0
			}
		}
	)

	/**
	 * 监听收纳栏状态
	 * @description 打开时，body 添加点击事件的监听
	 */
	watch(operatePopoverVisible, (newValue) => {
		if (newValue === true) {
			document.body.addEventListener('click', closeOperatePopover)
		} else {
			document.body.removeEventListener('click', closeOperatePopover)
		}
	})

	onMounted(() => {
		fileGroupLable.value = fileModel.value
		getisshow()
	})

	const getisshow = () => {
		let isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('ios') > -1
		if (isAndroid) {
			isandiord.value = false
		}
	}

	/**
	 * 新建文件夹按钮点击事件
	 * @description 调用新建文件夹服务，并在弹窗确认回调事件中刷新文件列表
	 */
	const handleClickAddFolderBtn = () => {
		proxy.$openDialog
			.addFolder({
				// filePath: route.query.filePath || '/'
				filePath: myResourceStore.getQuery.filePath || '/'
			})
			.then((res) => {
				if (res === 'confirm') {
					emit('getTableDataByType')
				}
			})
	}

	/**
	 * 新建 office 文件
	 * @description 调用新建 office 文件服务，并在弹窗确认回调事件中刷新文件列表
	 * @param {string} 文件扩展名 docx xlsx pptx
	 */
	const handleCreateFile = (extendName) => {
		proxy.$openDialog
			.addFile({
				extendName: extendName
			})
			.then((res) => {
				if (res === 'confirm') {
					emit('getTableDataByType')
				}
			})
	}

	/**
	 * 上传文件按钮点击事件
	 * @description 通过Bus通信，开启全局上传文件流程
	 * @param {boolean} uploadWay 上传方式 0-文件上传 1-文件夹上传 2-粘贴图片或拖拽上传
	 */
	const handleUploadFileBtnClick = async (uploadWay) => {
		proxy.$openDialog.authWeChat().then((res) => {
			switch (res) {
				case 'confirm': {
					// window.$common.goAccount('/settings/account')
					break
				}
				case 'go': {
					proxy.$openBox.uploadFile({
						params: uploadFileParams.value,
						uploadWay,
						serviceEl: proxy, // 使用proxy替代this
						callType: 1 //  callType 调用此服务的方式：1 - 顶部栏，2 - 右键菜单
					})
					break
				}
			}
		})
	}

	/**
	 * 批量删除按钮点击事件
	 * @description 区分 删除到回收站中 | 在回收站中彻底删除，调用相应的删除文件接口
	 */
	const handleBatchDeleteBtnClick = () => {
		console.log('要去删除', selectedFiles.value)
		proxy.$openDialog
			.deleteFile({
				isBatchOperation: true,
				fileInfo: selectedFiles.value,
				deleteMode: props.fileType === 6 ? 2 : 1 //  删除模式：1-删除到回收站 2-彻底删除
			})
			.then((res) => {
				if (res === 'confirm') {
					emit('getTableDataByType')
					myResourceStore.showStorage()
				}
			})
	}

	/**
	 * 批量移动按钮点击事件
	 */
	const handleBatchMoveBtnClick = () => {
		if (selectedFiles.value.length > 0) {
			proxy.$openDialog
				.moveFile({
					isBatchOperation: true,
					fileInfo: selectedFiles.value
				})
				.then((res) => {
					if (res === 'confirm') {
						emit('getTableDataByType')
					}
				})
		} else {
			message.warning('请先勾选文件')
		}
	}

	/**
	 * 批量分享按钮点击事件
	 */
	const handleBatchShareBtnClick = () => {
		proxy.$openDialog.shareFile({
			fileInfo: selectedFiles.value.map((item) => {
				return {
					userFileId: item.userFileId
				}
			})
		})
	}

	/**
	 * 打包批量下载按钮点击事件
	 */
	const handleBatchDownloadBtnClick = () => {
		// var cookies = window.$common.getCookies(window.config.tokenKeyName)
		var url = `${
			'http://' + window.location.host + config.baseContext
		}/filetransfer/batchDownloadFile?userFileIds=${selectedFiles.value.map((item) => item.userFileId).join(',')}`
		var newname1 = '.zip'
		let isios = navigator.userAgent.indexOf('iPhone') > -1
		let isAndroid = navigator.userAgent.indexOf('Android') > -1
		if (isios) {
			window.webkit.messageHandlers.Download.postMessage({
				params: {
					url,
					cookies,
					newname1
				}
			})
		} else if (isAndroid) {
			window.Download.downList(url, cookies, newname1)
		}
		batchDownloadRef.value.click()
	}

	/**
	 * 搜索输入框搜索事件
	 * @param {string} value 搜索内容
	 */
	const handleSearchInputChange = (value) => {
		if (value === '') {
			emit('getTableDataByType')
		} else {
			emit('getSearchFileList', value)
		}
	}

	/**
	 * 网格模式下，批量操作状态切换
	 */
	const handleBatchOperationChange = () => {
		myResourceStore.changeIsBatchOperation(!isBatchOperation.value)
	}

	/**
	 * 文件查看模式切换
	 * @param {number} label 0 列表 1 网格 2 时间线
	 */
	const handleFileDisplayModelChange = (label) => {
		fileGroupLable.value = label
		// 关闭右键菜单事件
		proxy.$openBox.contextMenu.close()
		myResourceStore.changeFileModel(label)
		handleSearchInputChange(searchFile.value.fileName)
		// 关闭收纳栏
		operatePopoverVisible.value = false
	}

	/**
	 * 格式化图标大小显示
	 * @param {number} val 改变后的数值
	 */
	const formatTooltip = (val) => {
		return `${val}px`
	}

	/**
	 * 关闭收纳栏
	 */
	const closeOperatePopover = (event) => {
		// 检查点击事件是否发生在设置图标上，如果是，则不关闭 Popover
		if (!event.target.closest('.setting-icon')) {
			operatePopoverVisible.value = false
		}
	}
</script>

<style lang="less" scoped>
	@import '@/style/myResource/varibles.less';

	.operation-menu-wrapper.file-type-6 {
		margin: 8px 0;
		justify-content: flex-end;
	}
	.ant-btn-primary {
		background-color: #29175b;
		border-color: #29175b;
	}
	.btnsy {
		background-color: #29175b;
		border-color: #29175b;
	}
	.operation-menu-wrapper {
		padding: 16px 0 0 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		.create-operate-group {
			.upload-drop {
				float: left;
				.ant-btn {
					border-radius: 4px 0 0 4px;
				}
			}
			.create-drop {
				float: left;
			}
		}
		.batch-operate-group {
			flex: 1;
		}
		.select-file-input {
			margin-right: 8px;
			width: 250px;
			.anticon-search {
				cursor: pointer;
				font-size: 16px;
				&:hover {
					color: @primary-color;
				}
			}
		}
		.batch-icon,
		.model-icon {
			margin-right: 8px;
			&:last-of-type {
				margin-right: 0;
			}
		}
		.model-icon.active {
			color: @primary-color;
		}
		.refresh-icon,
		.batch-icon,
		.model-icon,
		.setting-icon {
			font-size: 20px;
			cursor: pointer;
			color: @secondary-text-color;
			&:hover {
				color: @primary-color;
			}
		}
		.batch-icon.active {
			color: @primary-color;
		}
	}
	.split-line {
		margin: 8px 0;
	}
	.img-text-wrapper {
		display: flex;
		align-items: center;
		img {
			margin-right: 4px;
			height: 24px;
		}
	}
	.operation-menu-wrapper .refresh-icon:hover,
	.operation-menu-wrapper .batch-icon:hover,
	.operation-menu-wrapper .model-icon:hover,
	.operation-menu-wrapper .setting-icon:hover {
		color: #29175b;
	}
	.ant-dropdown-menu-item:focus,
	.ant-dropdown-menu-item:not(.ant-dropdown-menu-item-disabled):hover {
		background-color: #ecf5ff;
		color: #29175b;
	}
	.operation-menu-wrapper .model-icon.active {
		color: #29175b;
	}
	.ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled) {
		color: #fff;
		background-color: #29175b;
		border-color: #29175b;
	}
</style>
