<template>
	<!-- 分享对话框 -->
	<a-modal title="分享文件" v-model:visible="visible" :maskClosable="false" width="550px" @close="handleDialogCancel">
		<a-form
			v-show="!shareIsSuccess"
			class="share-file-form"
			:model="form"
			ref="shareFileForm"
			:label-col="{ span: screenWidth <= 520 ? 24 : 6 }"
			:wrapper-col="{ span: screenWidth <= 520 ? 24 : 18 }"
			:rules="rules"
		>
			<a-form-item label="链接有效期至：" name="endTime">
				<a-date-picker
					v-model:value="form.endTime"
					show-time
					format="YYYY-MM-DD HH:mm:ss"
					value-format="YYYY-MM-DD HH:mm:ss"
					placeholder="选择日期时间"
					:inputReadOnly="true"
					:allowClear="false"
					:locale="locale"
				>
					<template #renderExtraFooter>
						<div>
							<a-button size="small" @click="setEndTime('today')">今天</a-button>
							<a-button size="small" @click="setEndTime('1day')">1天</a-button>
							<a-button size="small" @click="setEndTime('7days')">7天</a-button>
							<a-button size="small" @click="setEndTime('30days')">30天</a-button>
						</div>
					</template>
				</a-date-picker>
			</a-form-item>
			<a-form-item label="是否需要提取码：" name="shareType">
				<a-radio-group v-model:value="form.shareType">
					<a-radio :value="1">是</a-radio>
					<a-radio :value="0">否</a-radio>
				</a-radio-group>
			</a-form-item>
		</a-form>
		<a-form
			v-if="shareIsSuccess"
			class="share-success-form"
			:model="shareData"
			ref="shareSuccessForm"
			:label-col="{ span: screenWidth <= 520 ? 24 : 4 }"
			:wrapper-col="{ span: screenWidth <= 520 ? 24 : 20 }"
		>
			<div class="success-tip">
				<check-circle-outlined />
				<span class="text">成功创建分享链接</span>
			</div>
			<a-form-item label="分享链接：" name="shareBatchNum">
				<a-textarea
					:value="$file.getShareLink(shareData.shareBatchNum)"
					:readonly="true"
					:auto-size="{ minRows: 2, maxRows: 6 }"
				></a-textarea>
			</a-form-item>
			<a-form-item label="提取码：" name="extractionCode">
				<a-input v-model:value="shareData.extractionCode" :readonly="true"></a-input>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button
				v-if="shareIsSuccess"
				type="primary"
				@click="$file.copyShareLink(shareData.shareBatchNum, shareData.extractionCode)"
				>复制链接及提取码</a-button
			>
			<template v-else>
				<a-button @click="handleDialogCancel">取 消</a-button>
				<a-button type="primary" :loading="sureBtnLoading" @click="handleDialogSure('shareFileForm')">确 定</a-button>
			</template>
		</template>
	</a-modal>
</template>

<script setup>
	import { ref, reactive, computed } from 'vue'
	import { shareFile } from '@/api/myResource/file.js'
	import { useMyResourceStore } from '@/store/myResource.js'
	import { message } from 'ant-design-vue'
	import { CheckCircleOutlined } from '@ant-design/icons-vue'
	import zhCN from 'ant-design-vue/es/date-picker/locale/zh_CN'

	const myResourceStore = useMyResourceStore()
	// 设置日期选择器的中文locale
	const locale = zhCN

	// 定义props
	const props = defineProps({
		fileInfo: {
			type: Array,
			default: () => []
		},
		callback: {
			type: Function,
			default: () => {}
		}
	})

	// 响应式状态
	const visible = ref(false) // 对话框是否可见
	const shareIsSuccess = ref(false) // 分享是否成功
	const sureBtnLoading = ref(false) // 确定按钮加载状态
	const shareFileForm = ref(null) // 表单引用

	// 分享文件对话框数据
	const form = reactive({
		endTime: '',
		shareType: 0
	})

	// 表单验证规则
	const rules = {
		endTime: [{ required: true, message: '请选择链接有效期', trigger: 'change' }]
	}

	// 分享成功的数据
	const shareData = reactive({
		shareBatchNum: '',
		extractionCode: ''
	})

	// 计算属性 - 屏幕宽度
	const screenWidth = computed(() => myResourceStore.screenWidth)

	// 设置结束时间的快捷方式
	const setEndTime = (type) => {
		const nowDate = new Date()
		let oneDay, sevenDays, thirtyDays
		let dateStr = ''

		const formatDate = (date) => {
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		}

		switch (type) {
			case 'today': {
				const todayEnd = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 23, 59, 59)
				form.endTime = formatDate(todayEnd)
				break
			}
			case '1day':
				oneDay = new Date()
				oneDay.setTime(oneDay.getTime() + 3600 * 1000 * 24)
				form.endTime = formatDate(oneDay)
				break
			case '7days':
				sevenDays = new Date()
				sevenDays.setTime(sevenDays.getTime() + 3600 * 1000 * 24 * 7)
				form.endTime = formatDate(sevenDays)
				break
			case '30days':
				thirtyDays = new Date()
				thirtyDays.setTime(thirtyDays.getTime() + 3600 * 1000 * 24 * 30)
				form.endTime = formatDate(thirtyDays)
				break
		}
	}

	/**
	 * 分享文件对话框 | 取消按钮点击事件
	 * @description 关闭对话框，重置表单
	 */
	const handleDialogCancel = () => {
		shareFileForm.value?.resetFields()
		visible.value = false
		props.callback('cancel')
	}

	/**
	 * 分享文件对话框 | 确定按钮点击事件
	 * @description 校验表单，校验通过后调用分享文件接口
	 * @param {string} formName 表单ref值
	 */
	const handleDialogSure = async (formName) => {
		sureBtnLoading.value = true
		try {
			await shareFileForm.value.validateFields()
			const params = {
				...form,
				remarks: '',
				userFileIds: props.fileInfo.map((res) => res.userFileId).join(',')
			}
			console.log('params', params)
			try {
				const res = await shareFile(params)
				sureBtnLoading.value = false
				if (res.success) {
					shareData.shareBatchNum = res.data.shareBatchNum
					shareData.extractionCode = res.data.extractionCode
					shareIsSuccess.value = true
					props.callback('confirm')
				} else {
					message.error(res.message)
				}
			} catch (error) {
				sureBtnLoading.value = false
			}
		} catch (error) {
			sureBtnLoading.value = false
		}
	}

	// 暴露方法给父组件
	defineExpose({
		visible
	})
</script>

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

	.success-tip {
		margin-bottom: 16px;
		text-align: center;
		color: @success-color;

		.anticon {
			margin-right: 8px;
			height: 20px;
			line-height: 20px;
		}
	}
</style>
