<template>
  <div class="leave-apply-page" v-loading="loading || quotaLoading">
    <div 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="!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">
        <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,
      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]
    },
    leaveTypeOptions() {
      return this.currentSceneConfig.leaveTypeOptions || []
    },
    isRestScene() {
      return this.scene === REST_SCENE
    },
    isPaidScene() {
      return this.scene === PAID_SCENE
    },
    showSummaryPanel() {
      return true
    },
    restQuota() {
      return (this.quotaSummary && this.quotaSummary.rest) || {}
    },
    paidQuota() {
      return (this.quotaSummary && this.quotaSummary.paid) || {}
    },
    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: '按实际请假时长填写', active: true }
        ]
      }
      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 === '产假' }
      ]
    },
    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.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 maxDays = Number(Number(this.dataForm.funeralRelationType) === 1 ? funeral.directRelativeDays || 0 : funeral.indirectRelativeDays || 0)
        return `当前丧假规则：直系亲属 ${this.formatNumber(funeral.directRelativeDays || 0)} 天，非直系亲属 ${this.formatNumber(funeral.indirectRelativeDays || 0)} 天；当前选择最多可请 ${this.formatNumber(maxDays)} 天。`
      }
      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)} 天。` : '当前未匹配到产假规则，请先联系管理员维护规则。'
      }
      return ''
    },
    selectedLeaveMaxDays() {
      if (this.isRestScene) return Number(this.restQuota.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)
      return null
    },
    canFillMaxDays() {
      return this.selectedLeaveMaxDays !== null && this.selectedLeaveMaxDays > 0
    }
  },
  created() {
    this.initializePage()
  },
  watch: {
    '$route.query': {
      deep: true,
      handler() {
        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: {
    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) {
      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)} 天`
      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)} 天`
      }
      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>
