<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="queryParams.contractNo" placeholder="请输入编号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="学生ID" prop="studentId">
              <el-input v-model="queryParams.studentId" placeholder="请输入学生ID" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="contractType">
              <el-select v-model="queryParams.contractType" placeholder="合同类型" clearable style="width: 150px">
                <el-option v-for="opt in contractTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="合同类别" prop="contractCategory">
              <el-select v-model="queryParams.contractCategory" placeholder="合同类别" clearable style="width: 140px">
                <el-option v-for="opt in contractCategoryOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="合同状态" clearable style="width: 150px">
                <el-option v-for="opt in contractStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:contract:add']" type="primary" plain icon="Plus" @click="handleAdd">新增合同</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:contract:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="contractList">
        <el-table-column label="合同编号" align="center" prop="contractNo" width="180" />
        <el-table-column label="学生ID" align="center" prop="studentId" width="90" />
        <el-table-column label="类型" align="center" prop="contractType" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.contractType)">{{ getTypeLabel(scope.row.contractType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="合同类别" align="center" prop="contractCategory" width="100">
          <template #default="scope">
            <span>{{ getCategoryLabel(scope.row.contractCategory) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="总金额" align="center" prop="totalAmount" width="110" />
        <el-table-column label="实收" align="center" prop="paidAmount" width="110" />
        <el-table-column label="是否分期" align="center" prop="isInstallment" width="90">
          <template #default="scope">
            <el-tag :type="scope.row.isInstallment === 'Y' ? 'warning' : 'info'" size="small">{{ scope.row.isInstallment === 'Y' ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="总课时" align="center" prop="totalHours" width="90" />
        <el-table-column label="剩余" align="center" prop="remainHours" width="90" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="签约日期" align="center" prop="signDate" width="110">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.signDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button v-hasPermi="['edu:contract:query']" link type="primary" icon="View" @click="handleDetail(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0'" content="修改" placement="top">
              <el-button v-hasPermi="['edu:contract:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0' || scope.row.status === '1'" content="激活" placement="top">
              <el-button v-hasPermi="['edu:contract:activate']" link type="success" icon="Open" @click="handleActivate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '2'" content="退费" placement="top">
              <el-button v-hasPermi="['edu:contract:refund']" link type="danger" icon="Wallet" @click="handleRefund(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '2'" content="转课" placement="top">
              <el-button v-hasPermi="['edu:contract:transfer']" link type="warning" icon="Sort" @click="handleTransfer(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0'" content="作废" placement="top">
              <el-button v-hasPermi="['edu:contract:edit']" link type="info" icon="RemoveFilled" @click="handleVoid(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip v-if="scope.row.status === '0' || scope.row.status === '9'" content="删除" placement="top">
              <el-button v-hasPermi="['edu:contract:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 详情抽屉 -->
    <el-drawer v-model="detailVisible" title="合同详情" size="55%">
      <el-descriptions v-if="detailData.id" :column="3" border>
        <el-descriptions-item label="合同编号">{{ detailData.contractNo }}</el-descriptions-item>
        <el-descriptions-item label="学生ID">{{ detailData.studentId }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTag(detailData.status)">{{ getStatusLabel(detailData.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="类型">{{ getTypeLabel(detailData.contractType) }}</el-descriptions-item>
        <el-descriptions-item label="合同类别">{{ getCategoryLabel(detailData.contractCategory) }}</el-descriptions-item>
        <el-descriptions-item label="签约日期">{{ proxy.parseTime(detailData.signDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="合同总额"><span class="money">¥{{ detailData.totalAmount }}</span></el-descriptions-item>
        <el-descriptions-item label="优惠"><span class="money-warn">-¥{{ detailData.discountAmount }}</span></el-descriptions-item>
        <el-descriptions-item label="实收"><span class="money-success">¥{{ detailData.paidAmount }}</span></el-descriptions-item>
        <el-descriptions-item label="退费"><span class="money-danger">¥{{ detailData.refundAmount }}</span></el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPayMethodLabel(detailData.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="是否分期">
          <el-tag :type="detailData.isInstallment === 'Y' ? 'warning' : 'info'" size="small">{{ detailData.isInstallment === 'Y' ? '是' : '否' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="有效期">
          {{ proxy.parseTime(detailData.effectiveDate, '{y}-{m}-{d}') }} ~ {{ proxy.parseTime(detailData.expireDate, '{y}-{m}-{d}') }}
        </el-descriptions-item>
        <el-descriptions-item label="服务期限">{{ detailData.servicePeriodText || '-' }}</el-descriptions-item>
        <el-descriptions-item label="服务合同">{{ detailData.serviceContractName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="激活时间">{{ proxy.parseTime(detailData.activatedAt) || '-' }}</el-descriptions-item>
        <el-descriptions-item label="课程顾问">{{ detailData.salesName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="管家">{{ detailData.housekeeperName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="签约人">{{ detailData.signUserName || detailData.signPerson || '-' }}</el-descriptions-item>
        <el-descriptions-item label="签约地点">{{ detailData.signLocation || '-' }}</el-descriptions-item>
        <el-descriptions-item label="合同回收">
          <el-tag :type="detailData.contractRecovered === 'Y' ? 'success' : 'info'" size="small">{{ detailData.contractRecovered === 'Y' ? '已回收' : '未回收' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="汇款人">{{ detailData.remittanceName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="是否需发票">
          <el-tag :type="detailData.needInvoice === 'Y' ? 'warning' : 'info'" size="small">{{ detailData.needInvoice === 'Y' ? '是' : '否' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="收款日期">{{ proxy.parseTime(detailData.paymentReceivedDate, '{y}-{m}-{d}') || '-' }}</el-descriptions-item>
        <el-descriptions-item label="实收总额"><span class="money-success">¥{{ detailData.actualTotalReceived || 0 }}</span></el-descriptions-item>
        <el-descriptions-item label="结算日期">{{ proxy.parseTime(detailData.settlementDate, '{y}-{m}-{d}') || '-' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 缴费计划进度 -->
      <template v-if="detailData.isInstallment === 'Y' && detailData.paymentPlans && detailData.paymentPlans.length > 0">
        <el-card shadow="never" class="mt-3 mb-3">
          <div class="mb-2" style="font-weight: 600; color: #606266;">缴费计划进度</div>
          <el-table border :data="detailData.paymentPlans" size="small">
            <el-table-column label="期次" width="70" align="center">
              <template #default="{ row }">第{{ row.installmentNo }}期</template>
            </el-table-column>
            <el-table-column label="应收金额" prop="planAmount" align="center" width="100" />
            <el-table-column label="应付日期" align="center" width="110">
              <template #default="{ row }">{{ proxy.parseTime(row.planDate, '{y}-{m}-{d}') }}</template>
            </el-table-column>
            <el-table-column label="实收金额" prop="paidAmount" align="center" width="100" />
            <el-table-column label="收款日期" align="center" width="110">
              <template #default="{ row }">{{ row.paidDate ? proxy.parseTime(row.paidDate, '{y}-{m}-{d}') : '-' }}</template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="80">
              <template #default="{ row }">
                <el-tag :type="getPlanStatusTag(row.status)" size="small">{{ getPlanStatusLabel(row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="{ row }">
                <el-button
                  v-if="row.status === '0'"
                  v-hasPermi="['edu:contract:activate']"
                  link type="success" @click="handleReceive(row)"
                >收款确认</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-2 plan-summary">
            <span>应收 <b>¥{{ planSummary.total }}</b></span>
            <span class="ml-3">已收 <b class="money-success">¥{{ planSummary.received }}</b></span>
            <span class="ml-3">待收 <b class="money-warn">¥{{ planSummary.pending }}</b></span>
            <el-progress
              :percentage="planSummary.total ? Math.round(planSummary.received / planSummary.total * 100) : 0"
              :stroke-width="14" :text-inside="true" class="plan-progress"
            />
          </div>
        </el-card>
      </template>

      <!-- 监护人信息 -->
      <template v-if="detailData.guardianName">
        <el-card shadow="never" class="mt-3 mb-3">
          <div class="mb-2" style="font-weight: 600; color: #606266;">监护人信息</div>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="监护人">{{ detailData.guardianName }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ detailData.guardianIdCard || '-' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ detailData.guardianPhone || '-' }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ detailData.guardianEmail || '-' }}</el-descriptions-item>
            <el-descriptions-item label="家庭住址" :span="2">{{ detailData.homeAddress || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </template>

      <!-- 升学服务信息 -->
      <template v-if="detailData.applySchoolCount > 0 || detailData.interviewCamp">
        <el-card shadow="never" class="mt-3 mb-3">
          <div class="mb-2" style="font-weight: 600; color: #606266;">升学服务信息</div>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="申请学校数">{{ detailData.applySchoolCount || 0 }}</el-descriptions-item>
            <el-descriptions-item label="申请地区范围">{{ detailData.applyRegionScope || '-' }}</el-descriptions-item>
            <el-descriptions-item label="面试营">{{ detailData.interviewCamp || '-' }}</el-descriptions-item>
            <el-descriptions-item label="专业营">{{ detailData.majorCamp || '-' }}</el-descriptions-item>
            <el-descriptions-item label="志愿营">{{ detailData.volunteerCamp || '-' }}</el-descriptions-item>
            <el-descriptions-item label="新生营">{{ detailData.freshmanCamp || '-' }}</el-descriptions-item>
            <el-descriptions-item label="GVI项目">{{ detailData.gviProject || '-' }}</el-descriptions-item>
            <el-descriptions-item label="科研项目">{{ detailData.researchProject || '-' }}</el-descriptions-item>
            <el-descriptions-item label="实习项目" :span="2">{{ detailData.internshipProject || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>
      </template>

      <!-- 课时进度(教学合同) -->
      <el-card v-if="detailData.totalHours > 0" shadow="never" class="mt-3 mb-3">
        <div class="hours-progress">
          <span class="hours-label">课时消耗进度</span>
          <el-progress
            :percentage="detailData.totalHours ? Math.round(detailData.usedHours / detailData.totalHours * 100) : 0"
            :color="hoursProgressColor"
            :stroke-width="18"
            :text-inside="true"
          />
          <span class="hours-detail">
            已消 {{ detailData.usedHours }} / 总 {{ detailData.totalHours }} · 剩余 <b style="color:#67c23a">{{ detailData.remainHours }}</b>
            <span v-if="detailData.giftHours > 0"> · 赠送 {{ detailData.giftHours }}</span>
          </span>
        </div>
      </el-card>
      <el-divider content-position="left">课包明细</el-divider>
      <el-table border :data="detailData.packages" size="small">
        <el-table-column label="课包" prop="packageName" align="center" />
        <el-table-column label="类型" prop="packageType" align="center" width="80" />
        <el-table-column label="购买课时" prop="totalHours" align="center" width="90" />
        <el-table-column label="已消耗" prop="usedHours" align="center" width="80" />
        <el-table-column label="剩余" prop="remainHours" align="center" width="80" />
        <el-table-column label="成交价" prop="salePrice" align="center" width="90" />
        <el-table-column label="明细金额" prop="finalAmount" align="center" width="90" />
      </el-table>
      <!-- 里程碑交付进度(升学服务合同) -->
      <template v-if="detailData.milestones && detailData.milestones.length > 0">
        <el-divider content-position="left">里程碑交付进度</el-divider>
        <el-table border :data="detailData.milestones" size="small">
          <el-table-column label="序号" prop="orderNum" align="center" width="60" />
          <el-table-column label="里程碑" prop="milestoneName" align="center" />
          <el-table-column label="计划金额" prop="plannedAmount" align="center" width="100" />
          <el-table-column label="已确认" prop="actualAmount" align="center" width="100" />
          <el-table-column label="状态" align="center" width="90">
            <template #default="scope">
              <el-tag :type="getMilestoneTag(scope.row.status)">{{ getMilestoneLabel(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="交付时间" align="center" width="160">
            <template #default="scope">
              <span>{{ proxy.parseTime(scope.row.deliveredAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                v-if="scope.row.status !== '2' && scope.row.status !== '3'"
                v-hasPermi="['edu:contract:deliver']"
                link
                type="primary"
                @click="handleDeliver(scope.row)"
              >交付</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-divider content-position="left">操作流水</el-divider>
      <el-timeline>
        <el-timeline-item v-for="log in detailData.logs" :key="log.id" :timestamp="proxy.parseTime(log.logTime)" placement="top">
          <el-card shadow="never">
            <h4>{{ log.action }} {{ log.amount ? '· 金额 ' + log.amount : '' }} {{ log.hoursDelta ? '· 课时 ' + log.hoursDelta : '' }}</h4>
            <p>{{ log.operatorName }} - {{ log.reason }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>

    <!-- 新增/修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="960px" append-to-body>
      <el-form ref="contractFormRef" :model="form" :rules="rules" label-width="110px">
        <el-divider content-position="left">基本信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="学生ID" prop="studentId">
              <el-input v-model="form.studentId" placeholder="请输入学生ID" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同类型" prop="contractType">
              <el-select v-model="form.contractType" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in contractTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同类别" prop="contractCategory">
              <el-select v-model="form.contractCategory" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in contractCategoryOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="签约日期" prop="signDate">
              <el-date-picker v-model="form.signDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker v-model="form.effectiveDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="到期日期" prop="expireDate">
              <el-date-picker v-model="form.expireDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="服务期限" prop="servicePeriodText">
              <el-input v-model="form.servicePeriodText" placeholder="如: 2024.9-2025.6" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="服务合同名" prop="serviceContractName">
              <el-input v-model="form.serviceContractName" placeholder="服务合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" placeholder="请选择" style="width: 100%">
                <el-option v-for="opt in paymentMethodOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否分期" prop="isInstallment">
              <el-select v-model="form.isInstallment" placeholder="请选择" style="width: 100%" @change="onInstallmentChange">
                <el-option label="是" value="Y" />
                <el-option label="否" value="N" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.isInstallment === 'Y'">
            <el-form-item label="分期数" prop="installmentCount">
              <el-select v-model="form.installmentCount" placeholder="请选择" style="width: 100%" @change="autoGeneratePlan">
                <el-option label="2 期" :value="2" />
                <el-option label="3 期" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.isInstallment === 'Y'">
            <el-form-item label="应收总额">
              <el-input :model-value="computedTotalAmount" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 缴费计划明细(分期时显示) -->
        <template v-if="form.isInstallment === 'Y'">
          <el-divider content-position="left">
            缴费计划
            <el-button class="ml-2" type="primary" plain icon="MagicStick" size="small" @click="autoGeneratePlan">自动生成</el-button>
          </el-divider>
          <el-table border :data="form.paymentPlans" size="small">
            <el-table-column label="期次" width="80" align="center">
              <template #default="{ row }">第{{ row.installmentNo }}期</template>
            </el-table-column>
            <el-table-column label="应收金额" width="160" align="center">
              <template #default="{ row }">
                <el-input-number v-model="row.planAmount" :min="0" :precision="2" size="small" controls-position="right" />
              </template>
            </el-table-column>
            <el-table-column label="应付日期" width="180" align="center">
              <template #default="{ row }">
                <el-date-picker v-model="row.planDate" type="date" value-format="YYYY-MM-DD" size="small" style="width: 100%" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" align="center">
              <template #default="{ $index }">
                <el-button link type="danger" icon="Delete" @click="form.paymentPlans?.splice($index, 1)" />
              </template>
            </el-table-column>
          </el-table>
        </template>
        <el-row>
          <el-col :span="8">
            <el-form-item label="实收总额" prop="actualTotalReceived">
              <el-input-number v-model="form.actualTotalReceived" :min="0" :precision="2" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结算日期" prop="settlementDate">
              <el-date-picker v-model="form.settlementDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收款日期" prop="paymentReceivedDate">
              <el-date-picker v-model="form.paymentReceivedDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">签约信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="课程顾问" prop="salesId">
              <staff-select v-model="form.salesId" role="SALES" placeholder="课程顾问" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="管家" prop="housekeeperId">
              <staff-select v-model="form.housekeeperId" role="HOUSEKEEPER" placeholder="管家" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签约人" prop="signUserId">
              <staff-select v-model="form.signUserId" placeholder="签约负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="签约地点" prop="signLocation">
              <el-input v-model="form.signLocation" placeholder="签约地点" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同回收" prop="contractRecovered">
              <el-select v-model="form.contractRecovered" placeholder="请选择" style="width: 100%">
                <el-option label="已回收" value="Y" />
                <el-option label="未回收" value="N" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="汇款人" prop="remittanceName">
              <el-input v-model="form.remittanceName" placeholder="汇款人姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否需发票" prop="needInvoice">
              <el-select v-model="form.needInvoice" placeholder="请选择" style="width: 100%">
                <el-option label="是" value="Y" />
                <el-option label="否" value="N" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="签约图片">
              <file-upload v-model="form.signImageUrl" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="合同说明" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入合同说明" />
        </el-form-item>

        <el-divider content-position="left">监护人信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="监护人" prop="guardianName">
              <el-input v-model="form.guardianName" placeholder="监护人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="guardianIdCard">
              <el-input v-model="form.guardianIdCard" placeholder="监护人身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="guardianPhone">
              <el-input v-model="form.guardianPhone" placeholder="监护人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="监护人邮箱" prop="guardianEmail">
              <el-input v-model="form.guardianEmail" placeholder="监护人邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="家庭住址" prop="homeAddress">
              <el-input v-model="form.homeAddress" placeholder="家庭住址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">升学服务信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="申请学校数" prop="applySchoolCount">
              <el-input-number v-model="form.applySchoolCount" :min="0" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地区范围" prop="applyRegionScope">
              <el-input v-model="form.applyRegionScope" placeholder="如: 香港/英国" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="面试营" prop="interviewCamp">
              <el-input v-model="form.interviewCamp" placeholder="面试营" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="专业营" prop="majorCamp">
              <el-input v-model="form.majorCamp" placeholder="专业营" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="志愿营" prop="volunteerCamp">
              <el-input v-model="form.volunteerCamp" placeholder="志愿营" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="新生营" prop="freshmanCamp">
              <el-input v-model="form.freshmanCamp" placeholder="新生营" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="GVI项目" prop="gviProject">
              <el-input v-model="form.gviProject" placeholder="GVI项目" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="科研项目" prop="researchProject">
              <el-input v-model="form.researchProject" placeholder="科研项目" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实习项目" prop="internshipProject">
              <el-input v-model="form.internshipProject" placeholder="实习项目" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 课包明细子表 -->
        <el-divider content-position="left">课包明细</el-divider>
        <el-table border :data="form.packages" size="small">
          <el-table-column label="课包ID" min-width="110" align="center">
            <template #default="{ row }">
              <el-input v-model="row.packageId" placeholder="课包ID" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="购买课时" width="120" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.totalHours" :min="0" :precision="2" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="赠送课时" width="120" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.giftHours" :min="0" :precision="2" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="成交价" width="120" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.salePrice" :min="0" :precision="2" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="明细金额" width="120" align="center">
            <template #default="{ row }">
              <el-input-number v-model="row.finalAmount" :min="0" :precision="2" size="small" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" icon="Delete" @click="form.packages.splice($index, 1)" />
            </template>
          </el-table-column>
        </el-table>
        <el-button class="mt-2" type="primary" plain icon="Plus" size="small" @click="addPackage">添加课包</el-button>

        <el-form-item label="备注" prop="remark" class="mt-4">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 激活弹窗 -->
    <el-dialog v-model="activateDialog.visible" title="激活合同" width="420px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="应收金额">
          <span>{{ activateRow.totalAmount }}</span>
        </el-form-item>
        <el-form-item label="实收金额">
          <el-input-number v-model="activateForm.paidAmount" :min="0" :precision="2" controls-position="right" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="activateForm.paymentMethod" placeholder="请选择" style="width: 100%">
            <el-option v-for="opt in paymentMethodOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitActivate">确 定</el-button>
        <el-button @click="activateDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 退费弹窗 -->
    <el-dialog v-model="refundDialog.visible" title="合同退费" width="420px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="剩余课时">
          <span>{{ refundRow.remainHours }}</span>
        </el-form-item>
        <el-form-item label="退费金额">
          <el-input-number v-model="refundForm.refundAmount" :min="0" :precision="2" controls-position="right" />
        </el-form-item>
        <el-form-item label="退费原因">
          <el-input v-model="refundForm.reason" type="textarea" placeholder="请输入退费原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="danger" @click="submitRefund">确认退费</el-button>
        <el-button @click="refundDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 转课弹窗 -->
    <el-dialog v-model="transferDialog.visible" title="合同转课" width="420px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="剩余课时">
          <span>{{ transferRow.remainHours }}</span>
        </el-form-item>
        <el-form-item label="目标学生ID">
          <el-input v-model="transferForm.targetStudentId" placeholder="转入的学生ID" />
        </el-form-item>
        <el-form-item label="转课原因">
          <el-input v-model="transferForm.reason" type="textarea" placeholder="请输入转课原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="warning" @click="submitTransfer">确认转课</el-button>
        <el-button @click="transferDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 收款确认弹窗 -->
    <el-dialog v-model="receiveDialog.visible" title="缴费计划收款确认" width="420px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="期次">
          <span>第 {{ receiveRow.installmentNo }} 期</span>
        </el-form-item>
        <el-form-item label="应收金额">
          <span>¥{{ receiveRow.planAmount }}</span>
        </el-form-item>
        <el-form-item label="实收金额">
          <el-input-number v-model="receiveForm.paidAmount" :min="0" :precision="2" controls-position="right" />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="receiveForm.paymentMethod" placeholder="请选择" style="width: 100%">
            <el-option v-for="opt in paymentMethodOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="收款日期">
          <el-date-picker v-model="receiveForm.paidDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="receiveForm.remark" type="textarea" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="success" @click="submitReceive">确认收款</el-button>
        <el-button @click="receiveDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduContract" lang="ts">
import {
  listContract,
  getContract,
  addContract,
  updateContract,
  delContract,
  voidContract,
  activateContract,
  refundContract,
  transferContract
} from '@/api/edu/contract';
import {
  ContractForm,
  ContractQuery,
  ContractVO,
  contractTypeOptions,
  contractCategoryOptions,
  contractStatusOptions,
  paymentMethodOptions,
  ContractActivateForm,
  ContractRefundForm,
  ContractTransferForm,
  ContractPackageForm
} from '@/api/edu/contract/types';
import { deliverMilestone } from '@/api/edu/milestone';
import { milestoneStatusOptions } from '@/api/edu/milestone/types';
import { receivePayment } from '@/api/edu/payment-plan';
import { PaymentReceiveForm, PaymentPlanForm, paymentPlanStatusOptions } from '@/api/edu/payment-plan/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const contractList = ref<ContractVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const contractFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({ visible: false, title: '' });
const activateDialog = reactive<DialogOption>({ visible: false, title: '' });
const refundDialog = reactive<DialogOption>({ visible: false, title: '' });
const transferDialog = reactive<DialogOption>({ visible: false, title: '' });
const receiveDialog = reactive<DialogOption>({ visible: false, title: '' });

const detailVisible = ref(false);
const detailData = ref<ContractVO>({} as ContractVO);
const activateRow = ref<ContractVO>({} as ContractVO);
const refundRow = ref<ContractVO>({} as ContractVO);
const transferRow = ref<ContractVO>({} as ContractVO);
const receiveRow = ref<any>({});
const receiveForm = reactive<PaymentReceiveForm>({ id: '', paidAmount: 0, paymentMethod: 'WECHAT', paidDate: '', remark: '' });

const initFormData: ContractForm = {
  id: undefined,
  contractNo: '',
  studentId: undefined,
  contractType: 'ENROLL',
  contractCategory: '',
  selectedSubject: '',
  parentContractId: undefined,
  signDate: '',
  effectiveDate: '',
  expireDate: '',
  servicePeriodText: '',
  serviceContractName: '',
  paymentMethod: 'WECHAT',
  paymentReceivedDate: '',
  isInstallment: 'N',
  installmentSecond: 0,
  installmentThird: 0,
  installmentCount: 2,
  paymentPlans: [],
  actualTotalReceived: 0,
  settlementDate: '',
  signPerson: '',
  signUserId: undefined,
  contractRecovered: 'N',
  remittanceName: '',
  needInvoice: 'N',
  salesId: undefined,
  housekeeperId: undefined,
  signLocation: '',
  signImageUrl: '',
  description: '',
  guardianName: '',
  guardianIdCard: '',
  guardianPhone: '',
  guardianEmail: '',
  homeAddress: '',
  applySchoolCount: 0,
  applyRegionScope: '',
  interviewCamp: '',
  majorCamp: '',
  volunteerCamp: '',
  freshmanCamp: '',
  gviProject: '',
  researchProject: '',
  internshipProject: '',
  remark: '',
  packages: [],
  gifts: []
};

const data = reactive<PageData<ContractForm, ContractQuery>>({
  form: { ...initFormData, packages: [], gifts: [] },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractNo: '',
    studentId: undefined,
    contractType: '',
    contractCategory: '',
    status: '',
    salesId: undefined,
    housekeeperId: undefined
  },
  rules: {
    studentId: [{ required: true, message: '学生ID不能为空', trigger: 'blur' }],
    contractType: [{ required: true, message: '合同类型不能为空', trigger: 'change' }],
    signDate: [{ required: true, message: '签约日期不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const activateForm = reactive<ContractActivateForm>({ id: '', paidAmount: 0, paymentMethod: 'WECHAT', remark: '' });
const refundForm = reactive<ContractRefundForm>({ id: '', refundAmount: 0, reason: '', attachments: '' });
const transferForm = reactive<ContractTransferForm>({ id: '', targetStudentId: '', reason: '' });

const getTypeLabel = (val: string) => contractTypeOptions.find((o) => o.value === val)?.label || val;
const getTypeTag = (val: string) => contractTypeOptions.find((o) => o.value === val)?.elTagType || 'info';
const getCategoryLabel = (val: string) => contractCategoryOptions.find((o) => o.value === val)?.label || val;
const getStatusLabel = (val: string) => contractStatusOptions.find((o) => o.value === val)?.label || val;
const getStatusTag = (val: string) => contractStatusOptions.find((o) => o.value === val)?.elTagType || 'info';
const getPayMethodLabel = (val: string) => paymentMethodOptions.find((o) => o.value === val)?.label || val;
const getMilestoneLabel = (val: string) => milestoneStatusOptions.find((o) => o.value === val)?.label || val;
const getMilestoneTag = (val: string) => milestoneStatusOptions.find((o) => o.value === val)?.elTagType || 'info';
const getPlanStatusLabel = (val: string) => paymentPlanStatusOptions.find((o) => o.value === val)?.label || val;
const getPlanStatusTag = (val: string) => paymentPlanStatusOptions.find((o) => o.value === val)?.elTagType || 'info';

/** 课时进度颜色(>80%红色预警, >50%橙色, 否则绿色) */
const hoursProgressColor = computed(() => {
  if (!detailData.value.totalHours) return '#67c23a';
  const pct = (detailData.value.usedHours / detailData.value.totalHours) * 100;
  return pct >= 80 ? '#f56c6c' : pct >= 50 ? '#e6a23c' : '#67c23a';
});

/** 应收总额(从课包明细汇总) */
const computedTotalAmount = computed(() => {
  return (form.value.packages || []).reduce((sum, p) => sum + (Number(p.finalAmount) || Number(p.salePrice) || 0), 0);
});

/** 缴费计划汇总(详情卡片用) */
const planSummary = computed(() => {
  const plans: any[] = detailData.value.paymentPlans || [];
  const total = plans.reduce((s, p) => s + (Number(p.planAmount) || 0), 0);
  const received = plans
    .filter((p: any) => p.status === '1')
    .reduce((s, p) => s + (Number(p.paidAmount) || 0), 0);
  const pending = plans
    .filter((p: any) => p.status === '0')
    .reduce((s, p) => s + (Number(p.planAmount) || 0), 0);
  return { total, received, pending };
});

/** 分期开关变化 */
const onInstallmentChange = (val: string) => {
  if (val === 'Y') {
    if (!form.value.installmentCount) form.value.installmentCount = 2;
    autoGeneratePlan();
  } else {
    form.value.paymentPlans = [];
  }
};

/** 按规则自动生成缴费计划: 首期吸收尾差, 日期按 30 天间隔 */
const autoGeneratePlan = () => {
  const count = form.value.installmentCount;
  if (!count || (count !== 2 && count !== 3)) {
    proxy?.$modal.msgWarning('请选择分期数(2 或 3)');
    return;
  }
  const total = Number(computedTotalAmount.value) || 0;
  if (total <= 0) {
    proxy?.$modal.msgWarning('应收总额大于 0 才能生成计划');
    return;
  }
  // base = total/count, 第2~N期取 base, 第1期吸收尾差
  const base = Math.round((total / count) * 100) / 100;
  const first = Math.round((total - base * (count - 1)) * 100) / 100;
  const signDate = form.value.signDate || proxy.parseTime(new Date(), '{y}-{m}-{d}');
  const signMs = new Date(signDate).getTime();
  const plans: PaymentPlanForm[] = [];
  for (let i = 1; i <= count; i++) {
    plans.push({
      installmentNo: i,
      planAmount: i === 1 ? first : base,
      planDate: proxy.parseTime(new Date(signMs + 30 * (i - 1) * 86400000), '{y}-{m}-{d}')
    });
  }
  form.value.paymentPlans = plans;
};

/** 缴费计划收款确认 */
const handleReceive = (row: any) => {
  receiveRow.value = row;
  receiveForm.id = row.id;
  receiveForm.paidAmount = row.planAmount;
  receiveForm.paymentMethod = detailData.value.paymentMethod || 'WECHAT';
  receiveForm.paidDate = proxy.parseTime(new Date(), '{y}-{m}-{d}');
  receiveForm.remark = '';
  receiveDialog.visible = true;
};

const submitReceive = async () => {
  await proxy?.$modal.confirm(`确认第 ${receiveRow.value.installmentNo} 期收款 ${receiveForm.paidAmount} 元？`);
  await receivePayment({ ...receiveForm });
  proxy?.$modal.msgSuccess('收款成功');
  receiveDialog.visible = false;
  // 刷新详情
  const res = await getContract(detailData.value.id);
  detailData.value = res.data;
  await getList();
};

const getList = async () => {
  loading.value = true;
  const res = await listContract(queryParams.value);
  contractList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData, packages: [], gifts: [] };
  contractFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增合同(草稿)';
};

const handleUpdate = async (row: ContractVO) => {
  reset();
  const res = await getContract(row.id);
  Object.assign(form.value, res.data);
  form.value.packages = res.data.packages || [];
  // 回填缴费计划(只取表单需要的字段: 期次/金额/日期)
  form.value.paymentPlans = (res.data.paymentPlans || []).map((p: any) => ({
    installmentNo: p.installmentNo,
    planAmount: p.planAmount,
    planDate: p.planDate
  }));
  form.value.installmentCount = res.data.paymentPlans?.length || 2;
  dialog.visible = true;
  dialog.title = '修改合同';
};

const submitForm = () => {
  contractFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.packages.length === 0) {
        proxy?.$modal.msgWarning('请至少添加一个课包明细');
        return;
      }
      // 分期计划校验: 期数与分期数一致 + 金额之和等于应收总额
      if (form.value.isInstallment === 'Y') {
        if (!form.value.installmentCount || form.value.paymentPlans?.length !== form.value.installmentCount) {
          proxy?.$modal.msgWarning('缴费计划期数与分期数不一致, 请点"自动生成"');
          return;
        }
        const sum = (form.value.paymentPlans || []).reduce((s, p) => s + (Number(p.planAmount) || 0), 0);
        if (Math.abs(sum - computedTotalAmount.value) > 0.01) {
          proxy?.$modal.msgWarning(`计划金额之和 ${sum.toFixed(2)} 与应收总额 ${computedTotalAmount.value.toFixed(2)} 不一致`);
          return;
        }
      } else {
        form.value.paymentPlans = [];
      }
      form.value.id ? await updateContract(form.value) : await addContract(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

const handleDetail = async (row: ContractVO) => {
  const res = await getContract(row.id);
  detailData.value = res.data;
  detailVisible.value = true;
};

const handleDelete = async (row: ContractVO) => {
  await proxy?.$modal.confirm('是否确认删除合同"' + row.contractNo + '"？');
  await delContract(row.id);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const handleExport = () => {
  proxy?.download('edu/contract/export', { ...queryParams.value }, `contract_${new Date().getTime()}.xlsx`);
};

/** 作废 */
const handleVoid = async (row: ContractVO) => {
  await proxy?.$modal.confirm(`确认作废合同"${row.contractNo}"？作废后不可恢复`);
  await voidContract(row.id);
  proxy?.$modal.msgSuccess('作废成功');
  await getList();
};

/** 激活 */
const handleActivate = (row: ContractVO) => {
  activateRow.value = row;
  activateForm.id = row.id;
  activateForm.paidAmount = row.totalAmount;
  activateForm.paymentMethod = row.paymentMethod || 'WECHAT';
  activateDialog.visible = true;
};

const submitActivate = async () => {
  await activateContract({ ...activateForm });
  proxy?.$modal.msgSuccess('激活成功');
  activateDialog.visible = false;
  await getList();
};

/** 退费 */
const handleRefund = (row: ContractVO) => {
  refundRow.value = row;
  refundForm.id = row.id;
  refundForm.refundAmount = 0;
  refundForm.reason = '';
  refundDialog.visible = true;
};

const submitRefund = async () => {
  await proxy?.$modal.confirm('确认退费？退费后合同将置为已退费');
  await refundContract({ ...refundForm });
  proxy?.$modal.msgSuccess('退费成功');
  refundDialog.visible = false;
  await getList();
};

/** 转课 */
const handleTransfer = (row: ContractVO) => {
  transferRow.value = row;
  transferForm.id = row.id;
  transferForm.targetStudentId = '';
  transferForm.reason = '';
  transferDialog.visible = true;
};

const submitTransfer = async () => {
  if (!transferForm.targetStudentId) {
    proxy?.$modal.msgWarning('请输入目标学生ID');
    return;
  }
  await proxy?.$modal.confirm('确认转课？剩余课时将转入目标学生');
  await transferContract({ ...transferForm });
  proxy?.$modal.msgSuccess('转课成功');
  transferDialog.visible = false;
  await getList();
};

/** 推进里程碑交付 */
const handleDeliver = async (row: any) => {
  await proxy?.$modal.confirm(`确认交付里程碑"${row.milestoneName}"？将确认金额 ${row.plannedAmount}`);
  await deliverMilestone({ id: row.id, actualAmount: row.plannedAmount });
  proxy?.$modal.msgSuccess('交付成功');
  // 刷新详情抽屉
  const res = await getContract(detailData.value.id);
  detailData.value = res.data;
};

/** 添加课包明细 */
const addPackage = () => {
  const item: ContractPackageForm = {
    packageId: '',
    totalHours: 0,
    giftHours: 0,
    salePrice: 0,
    discountAmount: 0,
    finalAmount: 0,
    expireDate: '',
    remark: ''
  };
  form.value.packages.push(item);
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.money { font-weight: 600; }
.money-success { color: #67c23a; font-weight: 600; }
.money-danger { color: #f56c6c; font-weight: 600; }
.money-warn { color: #e6a23c; font-weight: 600; }
.hours-progress { display: flex; align-items: center; gap: 12px; }
.hours-label { white-space: nowrap; color: #606266; font-weight: 600; }
.hours-detail { white-space: nowrap; font-size: 13px; color: #909399; }
.plan-summary { display: flex; align-items: center; gap: 4px; font-size: 13px; color: #606266; }
.plan-progress { flex: 1; margin-left: 12px; max-width: 280px; }
:deep(.el-drawer__body) { padding-top: 12px; }
</style>
