leave-apply-page.vue 35 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
<template>
  <div class="leave-apply-page" v-loading="loading || quotaLoading">
    <div v-if="!flowBoxMode" class="page-head">
      <div>
        <div class="page-title">{{ currentSceneConfig.title }}</div>
        <div class="page-tip">{{ currentSceneConfig.tip }}</div>
      </div>
      <div class="page-actions">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="warning" :loading="submitLoading && submitType === 'save'"
          @click="handleSubmit('save')">保存草稿</el-button>
        <el-button type="primary" :loading="submitLoading && submitType === 'submit'"
          @click="handleSubmit('submit')">提交申请</el-button>
      </div>
    </div>

    <el-alert v-if="!flowBoxMode && !dataForm.flowId" class="head-alert" type="warning" :closable="false"
      title="当前页面未携带 flowId,请从流程入口进入,或在地址后追加 ?flowId=流程ID 再提交。" show-icon />

    <div v-if="showSummaryPanel" class="summary-panel">
      <div class="summary-head">
        <div class="summary-title">{{ currentSceneConfig.summaryTitle }}</div>
        <el-button v-if="canFillMaxDays" type="text" @click="fillMaxDays">按可用上限填入天数</el-button>
      </div>
      <el-row :gutter="16">
        <el-col v-for="item in summaryCards" :key="item.key" :xs="24" :sm="12" :md="6">
          <div class="summary-card" :class="{ active: item.active }">
            <div class="summary-label">{{ item.label }}</div>
            <div class="summary-value">{{ item.value }}</div>
            <div v-if="item.desc" class="summary-desc">{{ item.desc }}</div>
          </div>
        </el-col>
      </el-row>
      <div v-if="leaveTypeSummaryText" class="summary-helper">{{ leaveTypeSummaryText }}</div>
    </div>

    <el-card shadow="never" class="form-card">
      <div slot="header" class="card-head">
        <span>申请信息</span>
        <span class="bill-no">单据号:{{ dataForm.billNo || '生成中...' }}</span>
      </div>
      <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="100px" :disabled="setting.readonly">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="流程标题" prop="flowTitle">
              <el-input v-model.trim="dataForm.flowTitle" maxlength="50" placeholder="请输入流程标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="flowUrgent">
              <el-select v-model="dataForm.flowUrgent" placeholder="请选择紧急程度">
                <el-option v-for="item in flowUrgentOptions" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人员">
              <el-input :value="dataForm.applyUser || '无'" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期">
              <el-date-picker v-model="dataForm.applyDate" type="date" value-format="timestamp" format="yyyy-MM-dd"
                readonly :editable="false" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请部门">
              <el-input :value="dataForm.applyDept || '无'" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请职位">
              <el-input :value="dataForm.applyPost || '无'" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="currentSceneConfig.leaveTypeLabel" prop="leaveType">
              <el-radio-group v-model="dataForm.leaveType" @change="handleLeaveTypeChange">
                <el-radio v-for="item in leaveTypeOptions" :key="item.value" :label="item.value">{{ item.label
                }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="isPaidScene && dataForm.leaveType === '丧假'" :span="24">
            <el-form-item label="丧假关系" prop="funeralRelationType">
              <el-radio-group v-model="dataForm.funeralRelationType">
                <el-radio :label="1">直系亲属</el-radio>
                <el-radio :label="2">非直系亲属</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请假原因" prop="leaveReason">
              <el-input v-model.trim="dataForm.leaveReason" type="textarea" :rows="3" maxlength="300" show-word-limit
                :placeholder="currentSceneConfig.reasonPlaceholder" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="leaveStartTime">
              <el-date-picker v-model="dataForm.leaveStartTime" type="datetime" value-format="timestamp"
                format="yyyy-MM-dd HH:mm" :editable="false" placeholder="请选择开始时间" @change="computeDuration" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="leaveEndTime">
              <el-date-picker v-model="dataForm.leaveEndTime" type="datetime" value-format="timestamp"
                format="yyyy-MM-dd HH:mm" :editable="false" placeholder="请选择结束时间" @change="computeDuration" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="form-helper">填写开始/结束时间后会自动计算时长,也可手动调整。</div>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假天数" prop="leaveDayCount">
              <el-input v-model.trim="dataForm.leaveDayCount" placeholder="请输入请假天数">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假小时" prop="leaveHour">
              <el-input v-model.trim="dataForm.leaveHour" placeholder="请输入请假小时">
                <template slot="append">小时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="相关附件" prop="fileJson">
              <NCC-UploadFz v-model="fileList" type="workFlow" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { BillNumber } from '@/api/system/billRule'
import { Info, Create, Update, QuotaSummary } from '@/api/workFlow/workFlowForm'

const REST_SCENE = 'rest'
const PERSONAL_SCENE = 'personal'
const PAID_SCENE = 'paid'

const createDefaultForm = () => ({
  id: '',
  flowId: '',
  billNo: '',
  flowTitle: '',
  flowUrgent: 1,
  applyUser: '',
  applyDate: '',
  applyDept: '',
  applyPost: '',
  leaveType: '',
  leaveReason: '',
  funeralRelationType: 1,
  leaveStartTime: '',
  leaveEndTime: '',
  leaveDayCount: '',
  leaveHour: '',
  fileJson: ''
})

export default {
  name: 'LeaveApplyPage',
  props: {
    scene: {
      type: String,
      default: REST_SCENE
    }
  },
  data() {
    const checkStartTime = (rule, value, callback) => {
      if (!value || !this.dataForm.leaveEndTime) return callback()
      if (Number(value) > Number(this.dataForm.leaveEndTime)) return callback(new Error('开始时间不能晚于结束时间'))
      callback()
    }
    const checkEndTime = (rule, value, callback) => {
      if (!value || !this.dataForm.leaveStartTime) return callback()
      if (Number(value) < Number(this.dataForm.leaveStartTime)) return callback(new Error('结束时间必须晚于开始时间'))
      callback()
    }
    const checkHalfNumber = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) return callback(new Error(rule.message))
      const num = Number(value)
      if (!num || num <= 0) return callback(new Error('请假时长必须大于 0'))
      if (Math.round(num * 2) !== num * 2) return callback(new Error('请假时长必须是整数或 0.5 的倍数'))
      callback()
    }
    const checkFuneralRelationType = (rule, value, callback) => {
      if (!this.isPaidScene || this.dataForm.leaveType !== '丧假') return callback()
      if (![1, 2].includes(Number(value))) return callback(new Error('请选择丧假关系'))
      callback()
    }
    return {
      loading: false,
      quotaLoading: false,
      submitLoading: false,
      submitType: '',
      applicantName: '',
      fileList: [],
      quotaSummary: null,
      flowBoxMode: false,
      setting: {},
      flowUrgentOptions: [
        { 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: '产假' }
          ]
        }
      },
      dataForm: createDefaultForm(),
      dataRule: {
        flowTitle: [{ required: true, message: '请输入流程标题', trigger: 'blur' }],
        flowUrgent: [{ required: true, message: '请选择紧急程度', trigger: 'change' }],
        leaveType: [{ required: true, message: '请选择请假类别', trigger: 'change' }],
        leaveReason: [{ required: true, message: '请输入请假原因', trigger: 'blur' }],
        funeralRelationType: [{ validator: checkFuneralRelationType, trigger: 'change' }],
        leaveStartTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' },
          { validator: checkStartTime, trigger: 'change' }
        ],
        leaveEndTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
          { validator: checkEndTime, trigger: 'change' }
        ],
        leaveDayCount: [{ validator: checkHalfNumber, message: '请输入请假天数', trigger: 'blur' }],
        leaveHour: [{ validator: checkHalfNumber, message: '请输入请假小时', trigger: 'blur' }]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    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
    },
    showSummaryPanel() {
      return this.isRestScene || this.isPaidScene
    },
    restQuota() {
      var q = this.quotaSummary || {}
      var r = q.rest || q.Rest
      if (!r || typeof r !== 'object') return {}
      return {
        ...r,
        workedDaysThisMonth: r.workedDaysThisMonth != null ? r.workedDaysThisMonth : (r.WorkedDaysThisMonth != null ? r.WorkedDaysThisMonth : 0),
        restUnlockCycle: r.restUnlockCycle != null ? r.restUnlockCycle : (r.RestUnlockCycle != null ? r.RestUnlockCycle : 0),
        unlockedRestDays: r.unlockedRestDays != null ? r.unlockedRestDays : (r.UnlockedRestDays != null ? r.UnlockedRestDays : 0),
        availableRestDays: r.availableRestDays != null ? r.availableRestDays : (r.AvailableRestDays != null ? r.AvailableRestDays : 0)
      }
    },
    paidQuota() {
      const q = this.quotaSummary || {}
      const paid = q.paid || q.Paid
      if (!paid || typeof paid !== 'object') {
        return { marriage: {}, funeral: {}, annual: {}, maternity: {}, extraLeaves: [] }
      }
      const m = paid.marriage || paid.Marriage || {}
      const f = paid.funeral || paid.Funeral || {}
      const a = paid.annual || paid.Annual || {}
      const mat = paid.maternity || paid.Maternity || {}
      const exRaw = paid.extraLeaves || paid.ExtraLeaves
      let exArr = []
      if (Array.isArray(exRaw)) exArr = exRaw
      else if (exRaw && typeof exRaw === 'object') exArr = Object.values(exRaw)
      var extraLeaves = exArr.map(function (x, idx) {
        return {
          id: x.id || x.Id || ('extra-' + idx),
          leaveName: String(x.leaveName || x.LeaveName || '').trim(),
          grantYear: x.grantYear != null ? x.grantYear : x.GrantYear,
          extraDays: Number(x.extraDays != null ? x.extraDays : (x.ExtraDays != null ? x.ExtraDays : 0))
        }
      }).filter(function (x) { return x.leaveName })
      return {
        marriage: {
          matched: m.matched != null ? m.matched : m.Matched,
          maxDays: Number(m.maxDays != null ? m.maxDays : (m.MaxDays != null ? m.MaxDays : 0))
        },
        funeral: {
          matched: f.matched != null ? f.matched : f.Matched,
          directRelativeDays: Number(f.directRelativeDays != null ? f.directRelativeDays : (f.DirectRelativeDays != null ? f.DirectRelativeDays : 0)),
          indirectRelativeDays: Number(f.indirectRelativeDays != null ? f.indirectRelativeDays : (f.IndirectRelativeDays != null ? f.IndirectRelativeDays : 0))
        },
        annual: {
          matched: a.matched != null ? a.matched : a.Matched,
          totalDays: Number(a.totalDays != null ? a.totalDays : (a.TotalDays != null ? a.TotalDays : 0)),
          usedDays: Number(a.usedDays != null ? a.usedDays : (a.UsedDays != null ? a.UsedDays : 0)),
          remainingDays: Number(a.remainingDays != null ? a.remainingDays : (a.RemainingDays != null ? a.RemainingDays : 0))
        },
        maternity: {
          matched: mat.matched != null ? mat.matched : mat.Matched,
          maxDays: Number(mat.maxDays != null ? mat.maxDays : (mat.MaxDays != null ? mat.MaxDays : 0))
        },
        extraLeaves: extraLeaves
      }
    },
    extraLeaveList() {
      return Array.isArray(this.paidQuota.extraLeaves) ? this.paidQuota.extraLeaves : []
    },
    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]
    },
    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
      }
      if (this.isPersonalScene) {
        return [
          { key: 'personal', label: '可申请类型', value: '事假 / 病假', desc: '按实际请假时长填写', active: true }
        ]
      }
      const extraTotalDays = this.extraLeaveList.reduce((sum, item) => sum + Number(item.extraDays || 0), 0)
      const sel = String(this.dataForm.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.dataForm.leaveType === '婚假' },
        { key: 'funeral', label: '丧假', value: `${this.formatNumber((this.paidQuota.funeral || {}).directRelativeDays || 0)} / ${this.formatNumber((this.paidQuota.funeral || {}).indirectRelativeDays || 0)} 天`, desc: '直系 / 非直系', active: this.dataForm.leaveType === '丧假' },
        { key: 'annual', label: '年假剩余', value: `${this.formatNumber((this.paidQuota.annual || {}).remainingDays || 0)} 天`, desc: `总额 ${this.formatNumber((this.paidQuota.annual || {}).totalDays || 0)} 天`, active: this.dataForm.leaveType === '年假' },
        { key: 'maternity', label: '产假', value: `${this.formatNumber((this.paidQuota.maternity || {}).maxDays || 0)} 天`, desc: '按后台规则', active: this.dataForm.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.isPersonalScene) return '事假、病假页面不限制后台额度,按实际时长填写并走审批。'
      if (this.dataForm.leaveType === '婚假') {
        const maxDays = Number((this.paidQuota.marriage || {}).maxDays || 0)
        return maxDays > 0 ? `按当前司龄规则,本次婚假最多可请 ${this.formatNumber(maxDays)} 天。` : '当前未匹配到婚假规则,请先联系管理员维护规则。'
      }
      if (this.dataForm.leaveType === '丧假') {
        const funeral = this.paidQuota.funeral || {}
        const currentDays = Number(Number(this.dataForm.funeralRelationType) === 1 ? funeral.directRelativeDays : funeral.indirectRelativeDays) || 0
        return `当前丧假规则:直系亲属 ${this.formatNumber(funeral.directRelativeDays || 0)} 天,非直系亲属 ${this.formatNumber(funeral.indirectRelativeDays || 0)} 天;当前选择最多可请 ${this.formatNumber(currentDays)} 天。`
      }
      if (this.dataForm.leaveType === '年假') {
        const annual = this.paidQuota.annual || {}
        return `本年年假总额 ${this.formatNumber(annual.totalDays || 0)} 天,已申请 ${this.formatNumber(annual.usedDays || 0)} 天,剩余 ${this.formatNumber(annual.remainingDays || 0)} 天。`
      }
      if (this.dataForm.leaveType === '产假') {
        const maternity = this.paidQuota.maternity || {}
        return Number(maternity.maxDays || 0) > 0 ? `按当前司龄规则,本次产假最多可请 ${this.formatNumber(maternity.maxDays || 0)} 天。` : '当前未匹配到产假规则,请先联系管理员维护规则。'
      }
      const matchedExtraLeave = this.extraLeaveList.find(item => String(item.leaveName || '').trim() === String(this.dataForm.leaveType || '').trim())
      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.dataForm.leaveType === '婚假') return Number((this.paidQuota.marriage || {}).maxDays || 0)
      if (this.dataForm.leaveType === '丧假') return Number(Number(this.dataForm.funeralRelationType) === 1 ? (this.paidQuota.funeral || {}).directRelativeDays || 0 : (this.paidQuota.funeral || {}).indirectRelativeDays || 0)
      if (this.dataForm.leaveType === '年假') return Number((this.paidQuota.annual || {}).remainingDays || 0)
      if (this.dataForm.leaveType === '产假') return Number((this.paidQuota.maternity || {}).maxDays || 0)
      const matchedExtraLeave = this.extraLeaveList.find(item => String(item.leaveName || '').trim() === String(this.dataForm.leaveType || '').trim())
      if (matchedExtraLeave) return Number(matchedExtraLeave.extraDays || 0)
      return null
    },
    canFillMaxDays() {
      return this.selectedLeaveMaxDays !== null && this.selectedLeaveMaxDays > 0
    }
  },
  created() {
    if (!this.flowBoxMode) this.initializePage()
  },
  watch: {
    '$route.query': {
      deep: true,
      handler() {
        if (!this.flowBoxMode) this.initializePage()
      }
    },
    'dataForm.leaveType'(value) {
      if (value === '丧假' && ![1, 2].includes(Number(this.dataForm.funeralRelationType))) {
        this.dataForm.funeralRelationType = 1
      }
      if (value !== '丧假') this.dataForm.funeralRelationType = 1
      this.refreshFlowTitle()
    }
  },
  methods: {
    init(data) {
      this.flowBoxMode = true
      this.setting = data || {}
      this.dataForm = createDefaultForm()
      this.dataForm.id = data.id || ''
      this.dataForm.flowId = data.flowId || ''
      this.dataForm.leaveType = this.currentSceneConfig.defaultLeaveType
      this.$nextTick(() => {
        if (this.$refs.dataForm) this.$refs.dataForm.resetFields()
        this.fileList = []
        this.quotaSummary = null
        this.fillApplicantInfo()
        var done = () => {
          this.loadQuotaSummary().then(() => {
            this.$emit('setPageLoad')
          })
        }
        if (data.id) {
          Info('leaveApply', data.id).then((res) => {
            this.dataForm = Object.assign(createDefaultForm(), res.data || {})
            if (!this.dataForm.flowId && data.flowId) this.dataForm.flowId = data.flowId
            if (this.dataForm.fileJson) {
              try { this.fileList = JSON.parse(this.dataForm.fileJson) } catch (e) { this.fileList = [] }
            }
            done()
          }).catch(() => { done() })
        } else {
          BillNumber('WF_LeaveApplyNo').then((res) => {
            this.dataForm.billNo = (res && res.data) || ''
            done()
          }).catch(() => { done() })
        }
      })
    },
    dataFormSubmit(eventType) {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) return
        var error = this.validateBusinessRule()
        if (error) {
          this.$message.error(error)
          return
        }
        var payload = Object.assign({}, this.dataForm, {
          flowUrgent: Number(this.dataForm.flowUrgent || 1),
          funeralRelationType: this.dataForm.leaveType === '丧假' ? Number(this.dataForm.funeralRelationType || 0) : null,
          leaveReason: (this.dataForm.leaveReason || '').trim(),
          fileJson: this.fileList && this.fileList.length ? JSON.stringify(this.fileList) : ''
        })
        this.$emit('eventReciver', payload, eventType)
      })
    },
    async initializePage() {
      const { id = '', flowId = '' } = this.$route.query || {}
      const currentKey = `${this.scene}_${id}_${flowId}`
      if (this._pageInitKey === currentKey) return
      this._pageInitKey = currentKey
      this.loading = true
      this.fileList = []
      this.quotaSummary = null
      this.dataForm = createDefaultForm()
      this.dataForm.flowId = flowId || ''
      this.dataForm.leaveType = this.currentSceneConfig.defaultLeaveType
      this.fillApplicantInfo()
      try {
        await Promise.all([this.loadQuotaSummary(), id ? this.loadInfo(id) : this.loadBillNo()])
      } finally {
        this.loading = false
      }
    },
    fillApplicantInfo() {
      const name = this.userInfo.userName || this.userInfo.realName || '当前用户'
      const account = this.userInfo.userAccount || ''
      this.applicantName = name
      this.dataForm.applyUser = account ? `${name}/${account}` : name
      this.dataForm.applyDate = new Date().getTime()
      this.dataForm.applyDept = this.userInfo.organizeName || ''
      this.dataForm.applyPost = this.getPositionText()
      this.refreshFlowTitle()
    },
    getPositionText() {
      const positions = this.userInfo.positionIds
      if (!Array.isArray(positions) || !positions.length) return this.userInfo.positionName || ''
      return positions.map(item => item && item.name).filter(Boolean).join('、')
    },
    refreshFlowTitle() {
      if (!this.applicantName || this.dataForm.id) return
      const leaveType = this.dataForm.leaveType || this.currentSceneConfig.title
      this.dataForm.flowTitle = `${this.applicantName}的${leaveType}申请`
    },
    async loadBillNo() {
      const res = await BillNumber('WF_LeaveApplyNo')
      this.dataForm.billNo = (res && res.data) || ''
    },
    async loadInfo(id) {
      const res = await Info('leaveApply', id)
      this.dataForm = Object.assign(createDefaultForm(), res.data || {})
      if (!this.dataForm.flowId && this.$route.query.flowId) this.dataForm.flowId = this.$route.query.flowId
      if (this.dataForm.fileJson) {
        try {
          this.fileList = JSON.parse(this.dataForm.fileJson)
        } catch (e) {
          this.fileList = []
        }
      }
    },
    async loadQuotaSummary() {
      this.quotaLoading = true
      try {
        const res = await QuotaSummary()
        this.quotaSummary = (res && res.data) || {}
      } finally {
        this.quotaLoading = false
      }
    },
    handleLeaveTypeChange(value) {
      this.dataForm.leaveType = value
      this.$nextTick(() => {
        this.$refs.dataForm && this.$refs.dataForm.clearValidate('funeralRelationType')
      })
    },
    computeDuration() {
      if (!this.dataForm.leaveStartTime || !this.dataForm.leaveEndTime) return
      const start = Number(this.dataForm.leaveStartTime)
      const end = Number(this.dataForm.leaveEndTime)
      if (!start || !end || end <= start) return
      const diffHours = (end - start) / (1000 * 60 * 60)
      const leaveHour = this.roundHalf(diffHours)
      const leaveDayCount = this.roundHalf(diffHours / 8)
      this.dataForm.leaveHour = this.formatNumber(leaveHour)
      this.dataForm.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() {
      const maxDays = Number(this.selectedLeaveMaxDays || 0)
      if (maxDays <= 0) return
      this.dataForm.leaveDayCount = this.formatNumber(maxDays)
      this.dataForm.leaveHour = this.formatNumber(maxDays * 8)
    },
    getRequestDays() {
      return Number(this.dataForm.leaveDayCount || 0)
    },
    getHalfDaySplitDays(days) {
      const value = Number(days || 0)
      return value - Math.floor(value)
    },
    validateRestScene(requestDays) {
      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)} 天`
      return ''
    },
    validatePaidScene(requestDays) {
      if (this.dataForm.leaveType === '婚假') {
        const maxDays = Number((this.paidQuota.marriage || {}).maxDays || 0)
        if (maxDays <= 0) return '当前未匹配到婚假规则,暂不能提交婚假申请'
        if (requestDays > maxDays) return `婚假最多可请 ${this.formatNumber(maxDays)} 天`
      }
      if (this.dataForm.leaveType === '丧假') {
        const funeral = this.paidQuota.funeral || {}
        const maxDays = Number(Number(this.dataForm.funeralRelationType) === 1 ? funeral.directRelativeDays || 0 : funeral.indirectRelativeDays || 0)
        if (maxDays <= 0) return '当前未匹配到丧假规则,暂不能提交丧假申请'
        if (requestDays > maxDays) return `当前选择的丧假最多可请 ${this.formatNumber(maxDays)} 天`
      }
      if (this.dataForm.leaveType === '年假') {
        const remainDays = Number((this.paidQuota.annual || {}).remainingDays || 0)
        if (remainDays <= 0) return '当前年假剩余天数为 0,暂不能提交年假申请'
        if (requestDays > remainDays) return `当前年假剩余 ${this.formatNumber(remainDays)} 天`
      }
      if (this.dataForm.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 => String(item.leaveName || '').trim() === String(this.dataForm.leaveType || '').trim())
      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 ''
    },
    validateBusinessRule() {
      if (!this.dataForm.flowId) return '缺少流程ID,无法提交,请从流程入口进入页面'
      const requestDays = this.getRequestDays()
      if (!requestDays || requestDays <= 0) return '请假天数必须大于 0'
      if (Math.round(requestDays * 2) !== requestDays * 2) return '请假天数必须是整数或 0.5 的倍数'
      if (this.isRestScene) return this.validateRestScene(requestDays)
      if (this.isPaidScene) return this.validatePaidScene(requestDays)
      return ''
    },
    handleSubmit(type) {
      this.submitType = type
      this.$refs.dataForm.validate(valid => {
        if (!valid) return
        const error = this.validateBusinessRule()
        if (error) {
          this.$message.error(error)
          return
        }
        if (type === 'submit') {
          this.$confirm('确认提交当前申请吗?', '提示', { type: 'warning' })
            .then(() => this.handleRequest(type))
            .catch(() => { })
          return
        }
        this.handleRequest(type)
      })
    },
    async handleRequest(type) {
      this.submitLoading = true
      try {
        const payload = Object.assign({}, this.dataForm, {
          flowUrgent: Number(this.dataForm.flowUrgent || 1),
          funeralRelationType: this.dataForm.leaveType === '丧假' ? Number(this.dataForm.funeralRelationType || 0) : null,
          leaveReason: (this.dataForm.leaveReason || '').trim(),
          fileJson: this.fileList && this.fileList.length ? JSON.stringify(this.fileList) : '',
          status: type === 'submit' ? 0 : 1
        })
        if (!payload.id) delete payload.id
        const requestMethod = payload.id ? Update : Create
        const res = await requestMethod('leaveApply', payload)
        this.$message.success((res && res.msg) || (type === 'submit' ? '提交成功' : '保存成功'))
        this.goAfterSuccess()
      } finally {
        this.submitLoading = false
      }
    },
    goAfterSuccess() {
      this.$router.push({ path: '/workFlow/flowLaunch' })
    },
    handleBack() {
      if (window.history.length > 1) {
        this.$router.back()
        return
      }
      this.$router.push({ path: '/workFlow/flowLaunch' })
    }
  }
}
</script>

<style lang="scss" scoped>
.leave-apply-page {
  padding: 20px;
}

.page-head {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 16px;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.page-tip {
  margin-top: 6px;
  color: #606266;
  line-height: 1.6;
}

.page-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.head-alert {
  margin-bottom: 16px;
}

.summary-panel,
.form-card {
  margin-bottom: 16px;
}

.summary-panel {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
}

.summary-head,
.card-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.summary-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.summary-card {
  min-height: 110px;
  margin-bottom: 16px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;
}

.summary-card.active {
  border-color: #67c23a;
  background: #f0f9eb;
}

.summary-label {
  color: #909399;
  font-size: 13px;
}

.summary-value {
  margin-top: 8px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.summary-desc,
.summary-helper,
.form-helper,
.bill-no {
  color: #606266;
  line-height: 1.6;
}

.summary-desc {
  margin-top: 8px;
}

.summary-helper {
  margin-top: 4px;
}

.form-helper {
  margin: -4px 0 16px;
  font-size: 12px;
}

.bill-no {
  font-size: 13px;
}
</style>