<template>
	<div class="share-wrapper">
		<div class="share-file-wrapper" v-if="shareStep === 3">
			<div class="operation-wrapper">
				<!-- 面包屑导航栏 -->
				<BreadCrumb class="breadcrumb" :fileType="7"></BreadCrumb>
				<a-button type="primary" size="small" v-show="isLogin" @click="handleSaveBtnClick">
					<template #icon><inbox-outlined /></template>
					保存到网盘
				</a-button>
			</div>
			<!-- 文件列表-表格模式 -->
			<FileTable
				ref="fileTableInstance"
				:fileType="7"
				:filePath="filePath"
				:fileList="fileList"
				:loading="loading"
			></FileTable>
		</div>
		<!-- 校验文件分享链接状态和是否需要提取码对话框 -->
		<a-modal
			title="文件分享"
			v-model:visible="dialogShareFile.visible"
			:maskClosable="false"
			:keyboard="false"
			width="500px"
		>
			<div class="end-time" v-if="shareStep === 1">此分享链接已过期</div>
			<a-form
				class="extraction-code-form"
				v-if="shareStep === 2"
				ref="codeFormRef"
				:model="dialogShareFile.codeForm"
				:rules="dialogShareFile.codeFormRules"
			>
				<a-form-item label="提取码" name="extractionCode">
					<a-input v-model:value="dialogShareFile.codeForm.extractionCode"></a-input>
				</a-form-item>
			</a-form>
			<template #footer>
				<a-button v-if="shareStep === 1" @click="handleCloseBtnClick()">关 闭</a-button>
				<a-button v-else type="primary" @click="handleSubmitBtnClick">提 交</a-button>
			</template>
		</a-modal>
	</div>
</template>

<script setup>
	import { ref, computed, onMounted, getCurrentInstance } from 'vue'
	import { useRoute, useRouter } from 'vue-router'
	import { storeToRefs } from 'pinia'
	import { useMyResourceStore } from '@/store/myResource'
	import BreadCrumb from '@/views/myResource/common/BreadCrumb.vue'
	import FileTable from '@/views/myResource/common/FileTable.vue'
	import { InboxOutlined } from '@ant-design/icons-vue'
	import { message } from 'ant-design-vue'
	import {
		checkShareLinkEndtime,
		checkShareLinkType,
		checkShareLinkCode,
		getShareFileList
	} from '@/api/myResource/file.js'

	const { proxy } = getCurrentInstance()
	const route = useRoute()
	const router = useRouter()
	const myResourceStore = useMyResourceStore()
	const { getIsLogin } = storeToRefs(myResourceStore)
	// 文件分享对话框数据
	const dialogShareFile = ref({
		visible: false,
		codeForm: {
			extractionCode: ''
		},
		codeFormRules: {
			extractionCode: [
				{
					required: true,
					message: '请输入提取码',
					trigger: 'blur'
				}
			]
		}
	})

	const shareStep = ref(0)
	const fileList = ref([])
	const loading = ref(false)
	const fileTableInstance = ref(null)
	const codeFormRef = ref(null)

	// 计算属性
	const isLogin = computed(() => getIsLogin.value)
	const shareBatchNum = computed(() => route.params.shareBatchNum)
	const filePath = computed(() => route.query.filePath)
	const shareFilePath = computed(() => route.query.filePath)
	// 被选中的文件列表
	const selectedFiles = computed(() => myResourceStore.selectedFiles)

	// 监听路径变化
	watch(
		() => filePath.value,
		() => {
			getShareList()
		}
	)

	// 生命周期钩子
	onMounted(() => {
		if (!filePath.value) {
			router.replace({
				query: {
					filePath: '/'
				}
			})
		}
		checkEndTime()
	})

	/**
	 * 校验分享链接过期时间
	 */
	const checkEndTime = () => {
		checkShareLinkEndtime({
			shareBatchNum: shareBatchNum.value
		}).then((res) => {
			if (res.success) {
				if (localStorage.getItem(`qiwen_share_${shareBatchNum.value}`) === 'true') {
					checkShareComplete()
				} else {
					dialogShareFile.value.visible = true
					checkShareType()
				}
			} else {
				dialogShareFile.value.visible = true
				shareStep.value = 1 //  链接已过期
			}
		})
	}

	/**
	 * 校验分享类型
	 * @description 校验分享链接是公共还是私密
	 */
	const checkShareType = () => {
		checkShareLinkType({
			shareBatchNum: shareBatchNum.value
		}).then((res) => {
			if (res.success) {
				// 0 公共 1 私密
				if (res.data.shareType === 0) {
					shareStep.value = 3 //  不是私密链接，直接展示文件列表
					getShareList()
					dialogShareFile.value.visible = false
				}
				if (res.data.shareType === 1) {
					shareStep.value = 2 //  是私密链接时，让用户输入提取码
				}
			} else {
				message.error(res.message)
			}
		})
	}

	/**
	 * 分享文件验证对话框 取消按钮
	 */
	const handleCloseBtnClick = () => {
		dialogShareFile.value.visible = false
		myResourceStore.changeQuery({ fileType: 0, filePath: '/' })
		// router.push({ name: 'File', query: { fileType: 0, filePath: '/' } })
	}

	/**
	 * 提交按钮点击事件
	 */
	const handleSubmitBtnClick = () => {
		codeFormRef.value
			.validate()
			.then(() => {
				checkShareLinkCode({
					extractionCode: dialogShareFile.value.codeForm.extractionCode,
					shareBatchNum: shareBatchNum.value
				}).then((res) => {
					if (res.success) {
						localStorage.setItem(`qiwen_share_${shareBatchNum.value}`, true)
						codeFormRef.value.resetFields() //  清空表单
						checkShareComplete()
					} else {
						message.error(res.message)
					}
				})
			})
			.catch(() => {
				// 表单验证失败
			})
	}

	/**
	 * 校验全部通过
	 */
	const checkShareComplete = () => {
		shareStep.value = 3 //  展示文件列表
		dialogShareFile.value.visible = false
		getShareList()
	}

	/**
	 * 获取分享文件列表
	 */
	const getShareList = () => {
		loading.value = true
		getShareFileList({
			shareFilePath: shareFilePath.value,
			shareBatchNum: shareBatchNum.value
		}).then((res) => {
			if (res.success) {
				fileList.value = res.dataList
				loading.value = false
			} else {
				message.error(res.message)
			}
		})
	}

	/**
	 * 保存到网盘按钮点击事件
	 */
	const handleSaveBtnClick = () => {
		console.log('selectedFiles', selectedFiles.value)
		if (selectedFiles.value.length) {
			proxy.$openDialog
				.saveShareFile({
					filePath: '',
					shareBatchNum: shareBatchNum.value,
					userFileIds: selectedFiles.value.map((item) => item.userFileId).join(',')
				})
				.then(() => {
					fileTableInstance.value.clearSelectedTable() //  清空表格已选项
				})
		} else {
			message.warning('请先勾选要保存的文件')
		}
	}
</script>

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

	.share-wrapper {
		.share-file-wrapper {
			width: 100%;

			.operation-wrapper {
				display: flex;
				justify-content: space-between;
				padding: 8px 0;
			}
		}
	}
</style>
