<template>
	<view class="page">
		<view class="card head-card">
			<view class="title-row">
				<text class="title">{{ currentSceneConfig.title }}</text>
				<text class="bill-no">单据：{{ formData.billNo || '生成中...' }}</text>
			</view>
			<view class="tip-box" :class="formData.flowId ? 'tip-ok' : 'tip-warn'">
				{{ formData.flowId ? currentSceneConfig.tip : '当前未携带流程ID，请从流程中心进入后再提交' }}
			</view>
		</view>

		<view v-if="showSummaryPanel" class="card summary-card">
			<view class="summary-head">
				<text class="summary-title">{{ currentSceneConfig.summaryTitle }}</text>
				<text v-if="quotaLoading" class="summary-loading">计算中...</text>
			</view>
			<view v-if="summaryCards.length" class="summary-grid">
				<view v-for="item in summaryCards" :key="item.key" class="summary-item" :class="item.active ? 'summary-item--active' : ''">
					<text class="summary-label">{{ item.label }}</text>
					<text class="summary-value">{{ item.value }}</text>
					<text v-if="item.desc" class="summary-desc">{{ item.desc }}</text>
				</view>
			</view>
			<view v-if="leaveTypeSummaryText" class="summary-helper">{{ leaveTypeSummaryText }}</view>
			<view v-if="canFillMaxDays" class="summary-action" @tap="fillMaxDays">按可用上限填入天数</view>
		</view>

		<view class="card form-card">
			<view class="form-item">
				<text class="label required">流程标题</text>
				<input class="input" v-model="formData.flowTitle" maxlength="50" placeholder="请输入流程标题" />
			</view>

			<view class="form-item">
				<text class="label required">紧急程度</text>
				<view class="tag-group">
					<view
						v-for="item in urgentOptions"
						:key="item.value"
						class="tag"
						:class="formData.flowUrgent === item.value ? 'tag-active' : ''"
						@tap="formData.flowUrgent = item.value"
					>
						{{ item.label }}
					</view>
				</view>
			</view>

			<view class="form-item readonly-item">
				<text class="label">申请人员</text>
				<text class="readonly-text">{{ formData.applyUser || '无' }}</text>
			</view>

			<view class="form-item readonly-item">
				<text class="label">申请日期</text>
				<text class="readonly-text">{{ applyDateText || '无' }}</text>
			</view>

			<view class="form-item readonly-item">
				<text class="label">申请部门</text>
				<text class="readonly-text">{{ formData.applyDept || '无' }}</text>
			</view>

			<view class="form-item readonly-item">
				<text class="label">申请职位</text>
				<text class="readonly-text">{{ formData.applyPost || '无' }}</text>
			</view>

			<view class="form-item">
				<text class="label required">{{ currentSceneConfig.leaveTypeLabel }}</text>
				<view class="tag-group">
					<view
						v-for="item in leaveTypeOptions"
						:key="item.value"
						class="tag"
						:class="formData.leaveType === item.value ? 'tag-active' : ''"
						@tap="handleLeaveTypeChange(item.value)"
					>
						{{ item.label }}
					</view>
				</view>
			</view>

			<view v-if="isPaidScene && formData.leaveType === '丧假'" class="form-item">
				<text class="label required">丧假关系</text>
				<view class="tag-group">
					<view class="tag" :class="Number(formData.funeralRelationType) === 1 ? 'tag-active' : ''" @tap="formData.funeralRelationType = 1">直系亲属</view>
					<view class="tag" :class="Number(formData.funeralRelationType) === 2 ? 'tag-active' : ''" @tap="formData.funeralRelationType = 2">非直系亲属</view>
				</view>
			</view>

			<view class="form-item">
				<text class="label required">请假原因</text>
				<textarea class="textarea" v-model="formData.leaveReason" maxlength="300" :placeholder="currentSceneConfig.reasonPlaceholder"></textarea>
			</view>

			<view class="form-item">
				<text class="label required">开始时间</text>
				<view class="datetime-row">
					<picker mode="date" :value="startDate" @change="handleDateChange('start', $event)">
						<view class="picker-box">{{ startDate || '选择日期' }}</view>
					</picker>
					<picker mode="time" :value="startTime" @change="handleTimeChange('start', $event)">
						<view class="picker-box">{{ startTime || '选择时间' }}</view>
					</picker>
				</view>
			</view>

			<view class="form-item">
				<text class="label required">结束时间</text>
				<view class="datetime-row">
					<picker mode="date" :value="endDate" @change="handleDateChange('end', $event)">
						<view class="picker-box">{{ endDate || '选择日期' }}</view>
					</picker>
					<picker mode="time" :value="endTime" @change="handleTimeChange('end', $event)">
						<view class="picker-box">{{ endTime || '选择时间' }}</view>
					</picker>
				</view>
				<text class="helper-text">填写开始/结束时间后会自动计算时长，也可手动调整</text>
			</view>

			<view class="inline-row">
				<view class="form-item inline-item">
					<text class="label required">请假天数</text>
					<input class="input" v-model="formData.leaveDayCount" type="digit" placeholder="请输入请假天数" />
				</view>
				<view class="form-item inline-item">
					<text class="label required">请假小时</text>
					<input class="input" v-model="formData.leaveHour" type="digit" placeholder="请输入请假小时" />
				</view>
			</view>

			<view class="form-item">
				<view class="upload-head">
					<text class="label">相关附件</text>
					<text class="upload-btn" @tap="chooseFiles">上传图片</text>
				</view>
				<view v-if="fileList.length" class="file-list">
					<view v-for="(item, index) in fileList" :key="item.fileId || index" class="file-item">
						<view class="file-main" @tap="previewImage(item, index)">
							<text class="file-name">{{ item.name || ('附件' + (index + 1)) }}</text>
						</view>
						<text class="file-remove" @tap="removeFile(index)">删除</text>
					</view>
				</view>
				<view v-else class="empty-files">暂未上传附件</view>
			</view>
		</view>

		<view class="safe-area"></view>

		<view class="action-bar">
			<button class="action-btn draft-btn" :disabled="submitting" @tap="handleSubmit(1)">
				{{ submitting && submitStatus === 1 ? '保存中...' : '保存草稿' }}
			</button>
			<button class="action-btn submit-btn" :disabled="submitting" @tap="handleSubmit(0)">
				{{ submitting && submitStatus === 0 ? '提交中...' : '提交申请' }}
			</button>
		</view>
	</view>
</template>

<script>
const REST_SCENE = 'rest'
const PERSONAL_SCENE = 'personal'
const PAID_SCENE = 'paid'
const createDefaultFormData = () => ({
	flowId: '',
	billNo: '',
	flowTitle: '',
	flowUrgent: 1,
	leaveType: '',
	leaveReason: '',
	funeralRelationType: 1,
	leaveStartTime: '',
	leaveEndTime: '',
	leaveDayCount: '',
	leaveHour: '',
	applyDate: '',
	applyDept: '',
	applyPost: '',
	applyUser: '',
	fileJson: ''
})

export default {
	name: 'LeaveApplyScene',
	props: {
		scene: {
			type: String,
			default: REST_SCENE
		},
		pageOptions: {
			type: Object,
			default: () => ({})
		}
	},
	data() {
		return {
			initializedKey: '',
			submitting: false,
			submitStatus: null,
			quotaLoading: false,
			quotaSummary: null,
			startDate: '',
			startTime: '',
			endDate: '',
			endTime: '',
			fileList: [],
			userInfo: {},
			newuserInfo: {},
			applicantName: '',
			urgentOptions: [
				{ value: 1, label: '普通' },
				{ value: 2, label: '重要' },
				{ value: 3, label: '紧急' }
			],
			sceneConfigMap: {
				[REST_SCENE]: {
					title: '休假申请',
					tip: '当前页用于发起每月应休天数的休假申请',
					summaryTitle: '本月休假额度',
					leaveTypeLabel: '休假类别',
					reasonPlaceholder: '请输入休假原因',
					defaultLeaveType: '休假',
					leaveTypeOptions: [{ value: '休假', label: '休假' }]
				},
				[PERSONAL_SCENE]: {
					title: '事假/病假申请',
					tip: '当前页用于发起事假、病假申请',
					summaryTitle: '请假说明',
					leaveTypeLabel: '请假类别',
					reasonPlaceholder: '请输入事假/病假原因',
					defaultLeaveType: '事假',
					leaveTypeOptions: [
						{ value: '事假', label: '事假' },
						{ value: '病假', label: '病假' }
					]
				},
				[PAID_SCENE]: {
					title: '带薪休假申请',
					tip: '当前页用于发起婚假、丧假、年假、产假申请',
					summaryTitle: '带薪休假额度',
					leaveTypeLabel: '带薪休假类别',
					reasonPlaceholder: '请输入带薪休假原因',
					defaultLeaveType: '婚假',
					leaveTypeOptions: [
						{ value: '婚假', label: '婚假' },
						{ value: '丧假', label: '丧假' },
						{ value: '年假', label: '年假' },
						{ value: '产假', label: '产假' }
					]
				}
			},
			formData: createDefaultFormData()
		}
	},
	computed: {
		currentSceneConfig() {
			return this.sceneConfigMap[this.scene] || this.sceneConfigMap[REST_SCENE]
		},
		isRestScene() {
			return this.scene === REST_SCENE
		},
		isPaidScene() {
			return this.scene === PAID_SCENE
		},
		applyDateText() {
			if (!this.formData.applyDate) return ''
			return String(this.formData.applyDate).slice(0, 10)
		},
		leaveTypeOptions() {
			return this.currentSceneConfig.leaveTypeOptions || []
		},
		restQuota() {
			return (this.quotaSummary && this.quotaSummary.rest) || {}
		},
		paidQuota() {
			return (this.quotaSummary && this.quotaSummary.paid) || {}
		},
		showSummaryPanel() {
			return this.isRestScene || this.scene === PERSONAL_SCENE || this.isPaidScene
		},
		summaryCards() {
			if (this.isRestScene) {
				return [
					{ key: 'total', label: '本月应休', value: this.formatNumber(this.restQuota.monthlyRestDays || 0), desc: '天' },
					{ key: 'used', label: '已申请', value: this.formatNumber(this.restQuota.usedRestDays || 0), desc: '天' },
					{ key: 'remain', label: '剩余可休', value: this.formatNumber(this.restQuota.remainingRestDays || 0), desc: '天', active: true },
					{ key: 'split', label: '半天额度', value: this.formatNumber(this.restQuota.remainingHalfDaySplitDays || 0), desc: `还能拆 ${this.restQuota.remainingHalfDaySelections || 0} 次半天` }
				]
			}
			if (this.scene === PERSONAL_SCENE) {
				return [
					{ key: 'personal', label: '可申请类型', value: '事假 / 病假', desc: '按实际请假时长填写' }
				]
			}
			return [
				{ key: 'marriage', label: '婚假', value: `${this.formatNumber((this.paidQuota.marriage || {}).maxDays || 0)} 天`, active: this.formData.leaveType === '婚假' },
				{ key: 'funeral', label: '丧假', value: `${this.formatNumber((this.paidQuota.funeral || {}).directRelativeDays || 0)} / ${this.formatNumber((this.paidQuota.funeral || {}).indirectRelativeDays || 0)} 天`, desc: '直系 / 非直系', active: this.formData.leaveType === '丧假' },
				{ key: 'annual', label: '年假剩余', value: `${this.formatNumber((this.paidQuota.annual || {}).remainingDays || 0)} 天`, desc: `总额 ${this.formatNumber((this.paidQuota.annual || {}).totalDays || 0)} 天`, active: this.formData.leaveType === '年假' },
				{ key: 'maternity', label: '产假', value: `${this.formatNumber((this.paidQuota.maternity || {}).maxDays || 0)} 天`, desc: '按后台规则', active: this.formData.leaveType === '产假' }
			]
		},
		leaveTypeSummaryText() {
			if (this.isRestScene) {
				if (!this.restQuota.attendanceGroupBound) {
					return '当前用户还未绑定考勤分组，暂时无法计算本月休假额度。'
				}
				return `当前分组【${this.restQuota.attendanceGroupName || '未命名分组'}】本月还可休 ${this.formatNumber(this.restQuota.remainingRestDays || 0)} 天；其中还能拆分半天 ${this.formatNumber(this.restQuota.remainingHalfDaySplitDays || 0)} 天。`
			}
			if (this.scene === PERSONAL_SCENE) {
				return '事假、病假页面不限制后台额度，按实际时长填写并走审批。'
			}
			if (this.formData.leaveType === '婚假') {
				const maxDays = Number((this.paidQuota.marriage || {}).maxDays || 0)
				return maxDays > 0 ? `按当前司龄规则，本次婚假最多可请 ${this.formatNumber(maxDays)} 天。` : '当前未匹配到婚假规则，请先联系管理员维护规则。'
			}
			if (this.formData.leaveType === '丧假') {
				const funeral = this.paidQuota.funeral || {}
				const currentDays = Number(this.formData.funeralRelationType) === 1 ? funeral.directRelativeDays : funeral.indirectRelativeDays
				return `当前丧假规则：直系亲属 ${this.formatNumber(funeral.directRelativeDays || 0)} 天，非直系亲属 ${this.formatNumber(funeral.indirectRelativeDays || 0)} 天；当前选择最多可请 ${this.formatNumber(currentDays || 0)} 天。`
			}
			if (this.formData.leaveType === '年假') {
				const annual = this.paidQuota.annual || {}
				return `本年年假总额 ${this.formatNumber(annual.totalDays || 0)} 天，已申请 ${this.formatNumber(annual.usedDays || 0)} 天，剩余 ${this.formatNumber(annual.remainingDays || 0)} 天。`
			}
			if (this.formData.leaveType === '产假') {
				const maternity = this.paidQuota.maternity || {}
				return Number(maternity.maxDays || 0) > 0
					? `按当前司龄规则，本次产假最多可请 ${this.formatNumber(maternity.maxDays || 0)} 天。`
					: '当前未匹配到产假规则，请先联系管理员维护规则。'
			}
			return ''
		},
		selectedLeaveMaxDays() {
			if (this.isRestScene) {
				return Number(this.restQuota.remainingRestDays || 0)
			}
			if (!this.isPaidScene) {
				return null
			}
			if (this.formData.leaveType === '婚假') {
				return Number((this.paidQuota.marriage || {}).maxDays || 0)
			}
			if (this.formData.leaveType === '丧假') {
				return Number(Number(this.formData.funeralRelationType) === 1
					? (this.paidQuota.funeral || {}).directRelativeDays || 0
					: (this.paidQuota.funeral || {}).indirectRelativeDays || 0)
			}
			if (this.formData.leaveType === '年假') {
				return Number((this.paidQuota.annual || {}).remainingDays || 0)
			}
			if (this.formData.leaveType === '产假') {
				return Number((this.paidQuota.maternity || {}).maxDays || 0)
			}
			return null
		},
		canFillMaxDays() {
			return this.selectedLeaveMaxDays !== null && this.selectedLeaveMaxDays > 0
		}
	},
	watch: {
		pageOptions: {
			handler() {
				this.initializePage()
			},
			deep: true,
			immediate: true
		}
	},
	methods: {
		createDefaultFormData() {
			return createDefaultFormData()
		},
		async initializePage() {
			const options = this.pageOptions || {}
			const initKey = `${this.scene}-${options.id || ''}-${options.flowId || ''}`
			if (this.initializedKey === initKey) return
			this.initializedKey = initKey
			this.userInfo = uni.getStorageSync('userInfo') || {}
			this.newuserInfo = uni.getStorageSync('newuserInfo') || {}
			this.quotaSummary = null
			this.startDate = ''
			this.startTime = ''
			this.endDate = ''
			this.endTime = ''
			this.fileList = []
			this.formData = this.createDefaultFormData()
			this.formData.flowId = options.id || options.flowId || ''
			this.formData.leaveType = this.currentSceneConfig.defaultLeaveType
			await this.initForm()
		},
		async initForm() {
			if (!this.userInfo || !this.userInfo.userId) {
				uni.showToast({ title: '请先登录', icon: 'none' })
				setTimeout(() => {
					uni.reLaunch({ url: '/pages/login/login' })
				}, 1200)
				return
			}
			this.fillApplicantInfo()
			await Promise.all([this.loadBillNo(), this.loadQuotaSummary()])
		},
		fillApplicantInfo() {
			const today = this.formatDate(new Date())
			const name = this.userInfo.realName || this.userInfo.userName || this.userInfo.name || '当前用户'
			const account = this.userInfo.userAccount || this.userInfo.account || ''
			const applyUser = account ? `${name}/${account}` : name
			const dept = this.newuserInfo.organizeName || this.userInfo.organizeName || this.newuserInfo.departmentName || ''
			const post = this.newuserInfo.positionName || this.userInfo.positionName || this.getPositionText() || ''
			this.applicantName = name
			this.formData.applyUser = applyUser
			this.formData.applyDept = dept
			this.formData.applyPost = post
			this.formData.applyDate = `${today} 00:00:00`
			this.refreshFlowTitle()
		},
		refreshFlowTitle() {
			if (!this.applicantName) return
			const leaveType = this.formData.leaveType || this.currentSceneConfig.title
			this.formData.flowTitle = `${this.applicantName}的${leaveType}申请`
		},
		getPositionText() {
			const list = this.userInfo.positionIds
			if (!Array.isArray(list) || !list.length) return ''
			return list.map(item => item && item.name).filter(Boolean).join('、')
		},
		async loadBillNo() {
			try {
				const res = await this.API.getWorkflowBillNumber('WF_LeaveApplyNo')
				if (res && Number(res.code) === 200) {
					this.formData.billNo = res.data || ''
				}
			} catch (e) {
				console.error('获取请假单号失败', e)
			}
		},
		async loadQuotaSummary() {
			this.quotaLoading = true
			try {
				const res = await this.API.getWorkflowLeaveQuotaSummary()
				if (res && Number(res.code) === 200) {
					this.quotaSummary = res.data || {}
				} else if (res && res.data) {
					this.quotaSummary = res.data
				}
			} catch (e) {
				console.error('获取请假额度失败', e)
			} finally {
				this.quotaLoading = false
			}
		},
		handleLeaveTypeChange(value) {
			this.formData.leaveType = value
			if (value === '丧假' && ![1, 2].includes(Number(this.formData.funeralRelationType))) {
				this.formData.funeralRelationType = 1
			}
			this.refreshFlowTitle()
		},
		handleDateChange(type, e) {
			if (type === 'start') {
				this.startDate = e.detail.value
			} else {
				this.endDate = e.detail.value
			}
			this.syncDateTime(type)
		},
		handleTimeChange(type, e) {
			if (type === 'start') {
				this.startTime = e.detail.value
			} else {
				this.endTime = e.detail.value
			}
			this.syncDateTime(type)
		},
		syncDateTime(type) {
			if (type === 'start') {
				this.formData.leaveStartTime = this.startDate && this.startTime ? `${this.startDate} ${this.startTime}:00` : ''
			} else {
				this.formData.leaveEndTime = this.endDate && this.endTime ? `${this.endDate} ${this.endTime}:00` : ''
			}
			this.computeDuration()
		},
		computeDuration() {
			if (!this.formData.leaveStartTime || !this.formData.leaveEndTime) return
			const start = new Date(this.formData.leaveStartTime.replace(/-/g, '/'))
			const end = new Date(this.formData.leaveEndTime.replace(/-/g, '/'))
			if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime()) || end <= start) return
			const diffHours = (end.getTime() - start.getTime()) / (1000 * 60 * 60)
			const leaveHour = this.roundHalf(diffHours)
			const leaveDayCount = this.roundHalf(diffHours / 8)
			this.formData.leaveHour = this.formatNumber(leaveHour)
			this.formData.leaveDayCount = this.formatNumber(leaveDayCount)
		},
		roundHalf(value) {
			return Math.round(Number(value || 0) * 2) / 2
		},
		formatNumber(value) {
			const num = Number(value || 0)
			return Number.isInteger(num) ? String(num) : num.toFixed(1)
		},
		fillMaxDays() {
			if (!this.canFillMaxDays) return
			const maxDays = Number(this.selectedLeaveMaxDays || 0)
			this.formData.leaveDayCount = this.formatNumber(maxDays)
			this.formData.leaveHour = this.formatNumber(maxDays * 8)
		},
		getHalfDaySplitDays(days) {
			const value = Number(days || 0)
			return value - Math.floor(value)
		},
		getRequestDays() {
			return Number(this.formData.leaveDayCount || 0)
		},
		buildSubmitReason() {
			return (this.formData.leaveReason || '').trim()
		},
		validatePaidLeave(requestDays) {
			if (this.formData.leaveType === '婚假') {
				const maxDays = Number((this.paidQuota.marriage || {}).maxDays || 0)
				if (maxDays <= 0) return '当前未匹配到婚假规则，暂不能提交婚假申请'
				if (requestDays > maxDays) return `婚假最多可请 ${this.formatNumber(maxDays)} 天`
			}
			if (this.formData.leaveType === '丧假') {
				const funeral = this.paidQuota.funeral || {}
				const maxDays = Number(Number(this.formData.funeralRelationType) === 1 ? funeral.directRelativeDays || 0 : funeral.indirectRelativeDays || 0)
				if (maxDays <= 0) return '当前未匹配到丧假规则，暂不能提交丧假申请'
				if (requestDays > maxDays) return `当前选择的丧假最多可请 ${this.formatNumber(maxDays)} 天`
			}
			if (this.formData.leaveType === '年假') {
				const remainDays = Number((this.paidQuota.annual || {}).remainingDays || 0)
				if (remainDays <= 0) return '当前年假剩余天数为 0，暂不能提交年假申请'
				if (requestDays > remainDays) return `当前年假剩余 ${this.formatNumber(remainDays)} 天`
			}
			if (this.formData.leaveType === '产假') {
				const maxDays = Number((this.paidQuota.maternity || {}).maxDays || 0)
				if (maxDays <= 0) return '当前未匹配到产假规则，暂不能提交产假申请'
				if (requestDays > maxDays) return `产假最多可请 ${this.formatNumber(maxDays)} 天`
			}
			return ''
		},
		validateForm() {
			if (!this.formData.flowId) return '请从流程中心进入后再提交'
			if (!this.formData.flowTitle) return '请输入流程标题'
			if (!this.formData.leaveType) return '请选择请假类别'
			if (!this.formData.leaveReason) return '请输入请假原因'
			if (this.isPaidScene && this.formData.leaveType === '丧假' && ![1, 2].includes(Number(this.formData.funeralRelationType))) {
				return '请选择丧假关系'
			}
			if (!this.formData.leaveStartTime) return '请选择开始时间'
			if (!this.formData.leaveEndTime) return '请选择结束时间'
			const start = new Date(this.formData.leaveStartTime.replace(/-/g, '/'))
			const end = new Date(this.formData.leaveEndTime.replace(/-/g, '/'))
			if (end <= start) return '结束时间必须晚于开始时间'
			if (!this.formData.leaveDayCount) return '请输入请假天数'
			if (!this.formData.leaveHour) return '请输入请假小时'
			const requestDays = this.getRequestDays()
			if (!requestDays || requestDays <= 0) return '请假天数必须大于0'
			if (requestDays * 2 !== Math.round(requestDays * 2)) return '请假天数必须是整数或0.5的倍数'

			if (this.isRestScene) {
				if (!this.restQuota.attendanceGroupBound) return '当前用户未绑定考勤分组，无法提交休假申请'
				const remainDays = Number(this.restQuota.remainingRestDays || 0)
				if (requestDays > remainDays) return `本月剩余可休 ${this.formatNumber(remainDays)} 天`
				const splitDays = this.getHalfDaySplitDays(requestDays)
				const remainSplitDays = Number(this.restQuota.remainingHalfDaySplitDays || 0)
				if (splitDays > remainSplitDays) {
					return `本月可拆分半天额度剩余 ${this.formatNumber(remainSplitDays)} 天`
				}
			}

			if (this.isPaidScene) {
				return this.validatePaidLeave(requestDays)
			}

			return ''
		},
		async chooseFiles() {
			const remain = 9 - this.fileList.length
			if (remain <= 0) {
				uni.showToast({ title: '最多上传9张图片', icon: 'none' })
				return
			}
			uni.chooseImage({
				count: remain,
				success: async (res) => {
					const files = res.tempFiles || []
					for (let i = 0; i < files.length; i++) {
						await this.uploadSingleFile(files[i])
					}
				}
			})
		},
		async uploadSingleFile(file) {
			try {
				uni.showLoading({ title: '上传中...' })
				const res = await this.API.uploadFile(file)
				if (res && Number(res.code) === 200 && res.data) {
					this.fileList.push({
						name: file.name || `附件${this.fileList.length + 1}`,
						fileId: res.data.name,
						url: res.data.url || res.data.name
					})
				} else {
					uni.showToast({ title: (res && (res.msg || res.message)) || '上传失败', icon: 'none' })
				}
			} catch (e) {
				console.error('上传附件失败', e)
				uni.showToast({ title: '上传失败', icon: 'none' })
			} finally {
				uni.hideLoading()
			}
		},
		removeFile(index) {
			this.fileList.splice(index, 1)
		},
		previewImage(item, index) {
			const urls = this.fileList.map(file => file.url).filter(Boolean)
			if (!urls.length) return
			uni.previewImage({ current: item.url || urls[index], urls })
		},
		async handleSubmit(status) {
			const errorMsg = this.validateForm()
			if (errorMsg) {
				uni.showToast({ title: errorMsg, icon: 'none' })
				return
			}
			this.submitting = true
			this.submitStatus = status
			try {
				uni.showLoading({ title: status === 1 ? '保存中...' : '提交中...' })
				const submitData = {
					...this.formData,
					leaveReason: this.buildSubmitReason(),
					funeralRelationType: this.formData.leaveType === '丧假' ? Number(this.formData.funeralRelationType || 0) : null,
					status,
					flowUrgent: Number(this.formData.flowUrgent || 1),
					fileJson: this.fileList.length ? JSON.stringify(this.fileList) : ''
				}
				const res = await this.API.createWorkflowLeaveApply(submitData)
				if (res && Number(res.code) === 200) {
					uni.showToast({
						title: status === 1 ? '草稿已保存' : '请假申请已提交',
						icon: 'success'
					})
					setTimeout(() => {
						uni.navigateBack({ delta: 1 })
					}, 1200)
				} else {
					uni.showToast({ title: (res && (res.msg || res.message)) || '提交失败', icon: 'none' })
				}
			} catch (e) {
				console.error('提交请假申请失败', e)
				uni.showToast({ title: '提交失败，请稍后重试', icon: 'none' })
			} finally {
				this.submitting = false
				this.submitStatus = null
				uni.hideLoading()
			}
		},
		formatDate(date) {
			const year = date.getFullYear()
			const month = `${date.getMonth() + 1}`.padStart(2, '0')
			const day = `${date.getDate()}`.padStart(2, '0')
			return `${year}-${month}-${day}`
		}
	}
}
</script>

<style scoped lang="scss">
.page {
	min-height: 100vh;
	background: linear-gradient(180deg, #e8f5e9 0%, #f6fff7 100%);
	padding: 24rpx;
	box-sizing: border-box;
}

.card {
	background: #ffffff;
	border-radius: 24rpx;
	box-shadow: 0 8rpx 24rpx rgba(67, 160, 71, 0.08);
	padding: 28rpx;
	margin-bottom: 24rpx;
}

.title-row,
.summary-head,
.upload-head {
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 16rpx;
	flex-wrap: wrap;
}

.title,
.summary-title {
	font-size: 36rpx;
	font-weight: 700;
	color: #2e7d32;
}

.bill-no,
.summary-loading {
	font-size: 24rpx;
	color: #6a9c6a;
}

.tip-box {
	margin-top: 20rpx;
	padding: 18rpx 20rpx;
	border-radius: 16rpx;
	font-size: 24rpx;
	line-height: 1.6;
}

.tip-ok {
	background: #edf9ee;
	color: #2e7d32;
}

.tip-warn {
	background: #fff7e8;
	color: #c57b00;
}

.summary-grid {
	display: grid;
	grid-template-columns: repeat(2, minmax(0, 1fr));
	gap: 20rpx;
	margin-top: 20rpx;
}

.summary-item {
	padding: 22rpx;
	border-radius: 18rpx;
	background: #f7fbf7;
	border: 2rpx solid #e0efe0;
}

.summary-item--active {
	border-color: #7bc67f;
	background: #eef8ee;
}

.summary-label,
.summary-desc,
.summary-helper,
.helper-text,
.empty-files,
.upload-btn {
	font-size: 24rpx;
}

.summary-label,
.summary-desc,
.helper-text,
.empty-files {
	color: #8c9b8d;
}

.summary-value {
	display: block;
	margin-top: 10rpx;
	font-size: 32rpx;
	font-weight: 700;
	color: #2f3a2f;
}

.summary-desc {
	display: block;
	margin-top: 8rpx;
	line-height: 1.5;
}

.summary-helper {
	margin-top: 20rpx;
	line-height: 1.7;
	color: #4f7d52;
}

.summary-action {
	margin-top: 18rpx;
	display: inline-flex;
	padding: 14rpx 24rpx;
	border-radius: 999rpx;
	background: #eff8ef;
	color: #2e7d32;
	font-size: 24rpx;
	font-weight: 600;
}

.form-item {
	margin-bottom: 28rpx;
}

.form-item:last-child {
	margin-bottom: 0;
}

.inline-row {
	display: flex;
	gap: 20rpx;
}

.inline-item {
	flex: 1;
}

.label {
	display: block;
	font-size: 28rpx;
	font-weight: 600;
	color: #2f3a2f;
	margin-bottom: 16rpx;
}

.required::before {
	content: '*';
	color: #f56c6c;
	margin-right: 8rpx;
}

.input,
.textarea,
.picker-box,
.readonly-text {
	width: 100%;
	background: #f8fbf8;
	border: 2rpx solid #dcefdc;
	border-radius: 16rpx;
	box-sizing: border-box;
	font-size: 28rpx;
	color: #303133;
}

.input,
.picker-box,
.readonly-text {
	min-height: 88rpx;
	padding: 0 24rpx;
	display: flex;
	align-items: center;
}

.textarea {
	min-height: 200rpx;
	padding: 24rpx;
}

.readonly-item .readonly-text {
	color: #606266;
}

.tag-group {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
}

.tag {
	padding: 16rpx 26rpx;
	border-radius: 999rpx;
	font-size: 26rpx;
	color: #4f7d52;
	background: #f3faf4;
	border: 2rpx solid #d5ead7;
}

.tag-active {
	color: #ffffff;
	background: linear-gradient(135deg, #43a047 0%, #66bb6a 100%);
	border-color: transparent;
}

.datetime-row {
	display: flex;
	gap: 20rpx;
}

.datetime-row picker {
	flex: 1;
}

.helper-text {
	display: block;
	margin-top: 12rpx;
	line-height: 1.6;
}

.upload-btn {
	color: #43a047;
	font-weight: 600;
}

.file-list {
	display: flex;
	flex-direction: column;
	gap: 16rpx;
}

.file-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 24rpx;
	border-radius: 16rpx;
	background: #f8fbf8;
	border: 2rpx solid #dcefdc;
	gap: 20rpx;
}

.file-main {
	flex: 1;
	min-width: 0;
}

.file-name {
	font-size: 26rpx;
	color: #303133;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.file-remove {
	flex-shrink: 0;
	font-size: 24rpx;
	color: #f56c6c;
}

.empty-files {
	padding: 24rpx;
	border-radius: 16rpx;
	background: #fafafa;
	text-align: center;
}

.safe-area {
	height: 140rpx;
}

.action-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom));
	background: rgba(255, 255, 255, 0.96);
	display: flex;
	gap: 20rpx;
	box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.06);
}

.action-btn {
	flex: 1;
	height: 88rpx;
	line-height: 88rpx;
	border-radius: 44rpx;
	font-size: 30rpx;
	font-weight: 600;
	border: none;
}

.draft-btn {
	background: #eef7ef;
	color: #2e7d32;
}

.submit-btn {
	background: linear-gradient(135deg, #43a047 0%, #66bb6a 100%);
	color: #ffffff;
}
</style>
