leave-apply-scene.vue 31.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
<template>
	<view class="page">
		<view class="card head-card">
			<view class="title-row">
				<view>
					<text class="title">{{ currentSceneConfig.title }}</text>
					<text class="title-sub">{{ currentSceneConfig.subTitle }}</text>
				</view>
				<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="mini-info-grid">
				<view class="mini-info-item">
					<text class="mini-label">申请人员</text>
					<text class="mini-value">{{ formData.applyUser || '无' }}</text>
				</view>
				<view class="mini-info-item">
					<text class="mini-label">申请日期</text>
					<text class="mini-value">{{ applyDateText || '无' }}</text>
				</view>
				<view class="mini-info-item">
					<text class="mini-label">申请部门</text>
					<text class="mini-value">{{ formData.applyDept || '无' }}</text>
				</view>
				<view class="mini-info-item">
					<text class="mini-label">申请职位</text>
					<text class="mini-value">{{ formData.applyPost || '无' }}</text>
				</view>
			</view>

			<view v-if="showLeaveTypeSelector" 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>
				<view class="datetime-row">
					<picker mode="date" :value="startDate" @change="handleDateChange($event)">
						<view class="picker-box">{{ startDate || '选择日期' }}</view>
					</picker>
					<picker mode="time" :value="startTime" @change="handleTimeChange($event)">
						<view class="picker-box">{{ startTime || '选择时间' }}</view>
					</picker>
				</view>
			</view>

			<view class="form-item">
				<text class="label required">请假天数</text>
				<input class="input" v-model="formData.leaveDayCount" type="digit" placeholder="请输入请假天数"
					@input="handleLeaveDaysInput($event)" />
				<text class="helper-text">支持整数或 0.5 天,填写后会自动计算结束时间和请假小时。</text>
			</view>

			<view class="auto-grid">
				<view class="auto-card">
					<text class="auto-label">结束时间</text>
					<text class="auto-value">{{ endTimeText || '待自动计算' }}</text>
				</view>
				<view class="auto-card">
					<text class="auto-label">请假小时</text>
					<text class="auto-value">{{ formData.leaveHour || '待自动计算' }}</text>
				</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>
import { extractQuotaSummaryPayload, normalizePaidQuota, normalizeRestQuota } from '@/service/quota-summary.js'

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: '',
			fileList: [],
			userInfo: {},
			newuserInfo: {},
			applicantName: '',
			sceneConfigMap: {
				[REST_SCENE]: {
					title: '应休申请',
					subTitle: '仅需选择开始时间和请假天数,系统会自动计算结束时间。',
					tip: '当前页用于发起每月应休天数的休假申请。',
					summaryTitle: '本月应休额度',
					leaveTypeLabel: '假期类型',
					defaultLeaveType: '休假',
					leaveTypeOptions: [{ value: '休假', label: '应休假期' }]
				},
				[PERSONAL_SCENE]: {
					title: '事假病假申请',
					subTitle: '选择假期类型、开始时间和请假天数即可提交。',
					tip: '当前页用于发起事假、病假申请。',
					summaryTitle: '',
					leaveTypeLabel: '假期类型',
					defaultLeaveType: '事假',
					leaveTypeOptions: [
						{ value: '事假', label: '事假' },
						{ value: '病假', label: '病假' }
					]
				},
				[PAID_SCENE]: {
					title: '带薪休假',
					subTitle: '选择带薪假类型、开始时间和请假天数即可提交。',
					tip: '当前页用于发起婚假、丧假、年假、产假申请。',
					summaryTitle: '带薪休假额度',
					leaveTypeLabel: '带薪假类型',
					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
		},
		isPersonalScene() {
			return this.scene === PERSONAL_SCENE
		},
		isPaidScene() {
			return this.scene === PAID_SCENE
		},
		showLeaveTypeSelector() {
			return this.leaveTypeOptions.length > 1
		},
		applyDateText() {
			if (!this.formData.applyDate) return ''
			return String(this.formData.applyDate).slice(0, 10)
		},
		endTimeText() {
			if (!this.formData.leaveEndTime) return ''
			return String(this.formData.leaveEndTime).slice(0, 16)
		},
		leaveTypeOptions() {
			const baseOptions = this.currentSceneConfig.leaveTypeOptions || []
			if (!this.isPaidScene || !this.extraLeaveList.length) return baseOptions
			const extraOptions = this.extraLeaveList.map(item => {
				const nm = String(item.leaveName || '').trim()
				const gy = item.grantYear
				const label = nm && gy != null && gy !== '' ? `${nm}(${gy}年)` : nm
				return { value: nm, label }
			})
			return [...baseOptions, ...extraOptions]
		},
		restQuota() {
			return normalizeRestQuota(this.quotaSummary)
		},
		paidQuota() {
			return normalizePaidQuota(this.quotaSummary)
		},
		extraLeaveList() {
			const list = Array.isArray(this.paidQuota.extraLeaves) ? this.paidQuota.extraLeaves : []
			return list.filter(x => x && String(x.leaveName || '').trim())
		},
		showSummaryPanel() {
			return this.isRestScene || this.isPaidScene
		},
		summaryCards() {
			if (this.isRestScene) {
				const rest = this.restQuota
				const unlockEnabled = rest.restUnlockCycle > 0
				const remainValue = unlockEnabled ? (rest.availableRestDays || 0) : (rest.remainingRestDays || 0)
				const remainDesc = unlockEnabled ? `已解锁 ${rest.unlockedRestDays || 0} 天` : '天'
				const cards = [
					{ key: 'total', label: '本月应休', value: this.formatNumber(rest.monthlyRestDays || 0), desc: '天' },
					{ key: 'used', label: '已申请', value: this.formatNumber(rest.usedRestDays || 0), desc: '天' },
					{ key: 'remain', label: '剩余可休', value: this.formatNumber(remainValue), desc: remainDesc, active: true },
					{ key: 'split', label: '半天额度', value: this.formatNumber(rest.remainingHalfDaySplitDays || 0), desc: `还能拆 ${rest.remainingHalfDaySelections || 0} 次半天` }
				]
				if (unlockEnabled) {
					cards.push({
						key: 'worked',
						label: '本月已上班',
						value: `${rest.workedDaysThisMonth || 0} 天`,
						desc: `每${rest.restUnlockCycle}天解锁1天`
					})
				}
				return cards
			}
			const extraTotalDays = this.extraLeaveList.reduce((sum, item) => sum + Number(item.extraDays || 0), 0)
			const sel = String(this.formData.leaveType || '').trim()
			const extraTypeSelected = this.extraLeaveList.some(
				item => String(item.leaveName || '').trim() === sel
			)
			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 === '产假' },
				{ key: 'extra', label: '额外假期总额', value: `${this.formatNumber(extraTotalDays)} 天`, active: extraTypeSelected }
			]
		},
		leaveTypeSummaryText() {
			if (this.isRestScene) {
				const rest = this.restQuota
				if (!rest.attendanceGroupBound) {
					return '当前用户还未绑定考勤分组,暂时无法计算本月应休额度。'
				}
				if (rest.restUnlockCycle > 0) {
					const worked = rest.workedDaysThisMonth || 0
					const cycle = rest.restUnlockCycle
					const unlocked = rest.unlockedRestDays || 0
					const available = rest.availableRestDays || 0
					const daysInCurrentCycle = worked % cycle
					const nextNeed = daysInCurrentCycle === 0 ? cycle : cycle - daysInCurrentCycle
					const canUnlockMore = unlocked < (rest.monthlyRestDays || 0)
					let text = `本月已上班 ${worked} 天,已解锁 ${unlocked} 天应休,当前可申请 ${available} 天。`
					if (canUnlockMore && nextNeed > 0) {
						text += `再上满 ${nextNeed} 天可再解锁 1 天。`
					}
					return text
				}
				return `当前分组【${rest.attendanceGroupName || '未命名分组'}】本月还可休 ${this.formatNumber(rest.remainingRestDays || 0)} 天;其中还能拆分半天 ${this.formatNumber(rest.remainingHalfDaySplitDays || 0)} 天。`
			}
			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)} 天。`
					: '当前未匹配到产假规则,请先联系管理员维护规则。'
			}
			const matchedExtraLeave = this.extraLeaveList.find(item => item.leaveName === this.formData.leaveType)
			if (matchedExtraLeave) {
				return `当前额外假期【${matchedExtraLeave.leaveName}】最多可请 ${this.formatNumber(matchedExtraLeave.extraDays || 0)} 天。`
			}
			return ''
		},
		selectedLeaveMaxDays() {
			if (this.isRestScene) {
				const rest = this.restQuota
				return rest.restUnlockCycle > 0
					? Number(rest.availableRestDays || 0)
					: Number(rest.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)
			}
			const matchedExtraLeave = this.extraLeaveList.find(item => item.leaveName === this.formData.leaveType)
			if (matchedExtraLeave) {
				return Number(matchedExtraLeave.extraDays || 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.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.formData.flowUrgent = 1
			this.refreshAutoTextFields()
		},
		refreshAutoTextFields() {
			const titleText = this.isRestScene ? this.currentSceneConfig.title : (this.formData.leaveType || this.currentSceneConfig.title)
			this.formData.flowTitle = `${this.applicantName}的${titleText}`
			if (this.isRestScene) {
				this.formData.leaveReason = '应休假期申请'
				return
			}
			this.formData.leaveReason = `${this.formData.leaveType || this.currentSceneConfig.title}申请`
		},
		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()
				const code = res != null ? Number(res.code ?? res.Code) : NaN
				const payload = extractQuotaSummaryPayload(res) || {}
				if (res && !Number.isNaN(code) && code !== 200) {
					const errMsg = res.msg || res.message || res.Msg || '获取请假额度失败'
					console.error('QuotaSummary 异常', code, errMsg)
					uni.showToast({ title: String(errMsg).slice(0, 40), icon: 'none', duration: 3500 })
				}
				this.quotaSummary = payload
			} catch (e) {
				console.error('获取请假额度失败', e)
				this.quotaSummary = {}
				uni.showToast({ title: '获取请假额度失败', icon: 'none' })
			} finally {
				this.quotaLoading = false
			}
		},
		handleLeaveTypeChange(value) {
			this.formData.leaveType = value
			if (value === '丧假' && ![1, 2].includes(Number(this.formData.funeralRelationType))) {
				this.formData.funeralRelationType = 1
			}
			this.refreshAutoTextFields()
		},
		handleDateChange(e) {
			this.startDate = e.detail.value
			this.syncStartDateTime()
		},
		handleTimeChange(e) {
			this.startTime = e.detail.value
			this.syncStartDateTime()
		},
		handleLeaveDaysInput(e) {
			const value = e && e.detail ? e.detail.value : this.formData.leaveDayCount
			this.formData.leaveDayCount = value
			this.computeEndByStartAndDays()
		},
		syncStartDateTime() {
			this.formData.leaveStartTime = this.startDate && this.startTime ? `${this.startDate} ${this.startTime}:00` : ''
			this.computeEndByStartAndDays()
		},
		computeEndByStartAndDays() {
			const days = Number(this.formData.leaveDayCount || 0)
			if (!this.formData.leaveStartTime || !days || days <= 0) {
				this.formData.leaveEndTime = ''
				this.formData.leaveHour = ''
				return
			}
			if (days * 2 !== Math.round(days * 2)) {
				this.formData.leaveEndTime = ''
				this.formData.leaveHour = ''
				return
			}
			const start = new Date(this.formData.leaveStartTime.replace(/-/g, '/'))
			if (Number.isNaN(start.getTime())) {
				this.formData.leaveEndTime = ''
				this.formData.leaveHour = ''
				return
			}
			const leaveHour = this.roundHalf(days * 8)
			const end = new Date(start.getTime() + leaveHour * 60 * 60 * 1000)
			this.formData.leaveHour = this.formatNumber(leaveHour)
			this.formData.leaveEndTime = `${this.formatDate(end)} ${String(end.getHours()).padStart(2, '0')}:${String(end.getMinutes()).padStart(2, '0')}:00`
		},
		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.computeEndByStartAndDays()
		},
		getHalfDaySplitDays(days) {
			const value = Number(days || 0)
			return value - Math.floor(value)
		},
		getRequestDays() {
			return Number(this.formData.leaveDayCount || 0)
		},
		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)} 天`
			}
			const matchedExtraLeave = this.extraLeaveList.find(item => item.leaveName === this.formData.leaveType)
			if (matchedExtraLeave) {
				const maxDays = Number(matchedExtraLeave.extraDays || 0)
				if (maxDays <= 0) return `当前额外假期【${matchedExtraLeave.leaveName}】可用天数为 0`
				if (requestDays > maxDays) return `额外假期【${matchedExtraLeave.leaveName}】最多可请 ${this.formatNumber(maxDays)} 天`
			}
			return ''
		},
		validateForm() {
			if (!this.formData.flowId) return '请从流程中心进入后再提交'
			if (!this.formData.leaveType) return '请选择请假类别'
			if (this.isPaidScene && this.formData.leaveType === '丧假' && ![1, 2].includes(Number(this.formData.funeralRelationType))) {
				return '请选择丧假关系'
			}
			if (!this.formData.leaveStartTime) return '请选择开始时间'
			if (!this.formData.leaveDayCount) return '请输入请假天数'
			const requestDays = this.getRequestDays()
			if (!requestDays || requestDays <= 0) return '请假天数必须大于0'
			if (requestDays * 2 !== Math.round(requestDays * 2)) return '请假天数必须是整数或0.5的倍数'
			if (!this.formData.leaveEndTime) return '请先选择开始时间并填写正确的请假天数'
			if (!this.formData.leaveHour) return '请假小时计算失败,请重新填写'

			if (this.isRestScene) {
				const rest = this.restQuota
				if (!rest.attendanceGroupBound) return '当前用户未绑定考勤分组,无法提交应休申请'
				const maxDays = rest.restUnlockCycle > 0
					? Number(rest.availableRestDays || 0)
					: Number(rest.remainingRestDays || 0)
				if (requestDays > maxDays) return `当前可申请 ${this.formatNumber(maxDays)} 天`
				const splitDays = this.getHalfDaySplitDays(requestDays)
				const remainSplitDays = Number(rest.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 ? '保存中...' : '提交中...' })
				this.refreshAutoTextFields()
				const submitData = {
					...this.formData,
					funeralRelationType: this.formData.leaveType === '丧假' ? Number(this.formData.funeralRelationType || 0) : null,
					status,
					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;
	display: block;
}

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

.title-sub {
	display: block;
	margin-top: 10rpx;
	line-height: 1.6;
}

.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,
.auto-card,
.mini-info-item {
	border-radius: 18rpx;
	background: #f7fbf7;
	border: 2rpx solid #e0efe0;
}

.summary-item {
	padding: 22rpx;
}

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

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

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

.summary-value,
.auto-value,
.mini-value {
	display: block;
	margin-top: 10rpx;
	font-size: 30rpx;
	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;
}

.mini-info-grid,
.auto-grid {
	display: grid;
	grid-template-columns: repeat(2, minmax(0, 1fr));
	gap: 20rpx;
}

.mini-info-grid {
	margin-bottom: 28rpx;
}

.mini-info-item,
.auto-card {
	padding: 20rpx 22rpx;
}

.mini-value {
	font-size: 26rpx;
	font-weight: 600;
	line-height: 1.5;
	word-break: break-all;
}

.auto-grid {
	margin-bottom: 28rpx;
}

.auto-value {
	font-size: 28rpx;
}

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

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

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

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

.input,
.picker-box {
	width: 100%;
	background: #f8fbf8;
	border: 2rpx solid #dcefdc;
	border-radius: 16rpx;
	box-sizing: border-box;
	font-size: 28rpx;
	color: #303133;
	min-height: 88rpx;
	padding: 0 24rpx;
	display: flex;
	align-items: center;
}

.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: #2f3a2f;
	word-break: break-all;
}

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

.safe-area {
	height: 140rpx;
}

.action-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 20rpx 24rpx calc(env(safe-area-inset-bottom) + 20rpx);
	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: 999rpx;
	font-size: 28rpx;
	font-weight: 600;
	border: none;
}

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

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