<template>
  <el-dialog v-model="visible" title="退宿结算" width="650px" append-to-body destroy-on-close>
    <el-descriptions title="基础信息" :column="2" border>
      <el-descriptions-item label="姓名">{{ student?.name }}</el-descriptions-item>
      <el-descriptions-item label="学号/身份证">{{ student?.id }}</el-descriptions-item>
      <el-descriptions-item label="房间号">{{ roomNo }}</el-descriptions-item>
      <el-descriptions-item label="床位号">{{ bed?.no }}</el-descriptions-item>
      <el-descriptions-item label="入住时间">{{ checkInDate }}</el-descriptions-item>
      <el-descriptions-item label="退宿时间">{{ today }}</el-descriptions-item>
    </el-descriptions>

    <div class="fee-section mt-20">
      <div class="section-title">
        <span>费用结算</span>
        <el-tag size="small" type="info" class="ml-10">由管家配置</el-tag>
      </div>
      
      <el-form label-width="100px">
        <el-form-item label="计费模式">
           <el-radio-group v-model="feeType" @change="recalculate">
             <el-radio label="long_term_year">长期住宿 (按年)</el-radio>
             <el-radio label="temp_month">临时住宿 (按月)</el-radio>
             <el-radio label="hotel_day">酒店式 (按天)</el-radio>
           </el-radio-group>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预收金额">
              <span class="text-success font-bold">¥ {{ paidAmount.toFixed(2) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item label="实际应收">
              <span class="font-bold">¥ {{ actualCost.toFixed(2) }}</span>
              <span class="text-gray text-xs ml-5">({{ durationStr }})</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="挂账(欠费)">
          <span v-if="outstandingAmount > 0" class="text-danger font-bold">¥ {{ outstandingAmount.toFixed(2) }}</span>
          <span v-else class="text-gray">无欠费</span>
          <el-button v-if="outstandingAmount > 0" type="text" class="ml-10" @click="viewBills">查看明细</el-button>
        </el-form-item>

        <el-divider />

        <div class="result-box">
           <div class="label">{{ finalAmount >= 0 ? '应退金额' : '应补缴金额' }}</div>
           <div class="value" :class="finalAmount >= 0 ? 'text-success' : 'text-danger'">
             ¥ {{ Math.abs(finalAmount).toFixed(2) }}
           </div>
           <div class="desc">
             计算公式: 预收 ({{ paidAmount }}) - 实际应收 ({{ actualCost }}) - 挂账 ({{ outstandingAmount }})
           </div>
        </div>
      </el-form>
    </div>

    <div class="action-section mt-20" v-if="outstandingAmount > 0">
       <el-alert title="检测到该生有未结清的挂账账单" type="warning" show-icon :closable="false">
          <div class="mt-5">
            <el-button size="small" type="primary" @click="handleRemind">发送催缴通知</el-button>
          </div>
       </el-alert>
    </div>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="handlePrint">打印结算单</el-button>
      <el-button type="primary" @click="handleConfirm">确认退宿并结算</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

const emit = defineEmits(['success'])

const visible = ref(false)
const student = ref(null)
const bed = ref(null)
const roomNo = ref('')

const today = dayjs().format('YYYY-MM-DD')
const checkInDate = ref('2025-09-01') // Mock

// Fee Config
const feeType = ref('long_term_year')
const unitPrice = ref(8000) // Default for year

const paidAmount = ref(8000)
const outstandingAmount = ref(0)
const actualCost = ref(0)
const durationStr = ref('')

// Computed
const finalAmount = computed(() => {
  return paidAmount.value - actualCost.value - outstandingAmount.value
})

// Methods
const recalculate = () => {
  const start = dayjs(checkInDate.value)
  const end = dayjs(today)
  const diffDays = end.diff(start, 'day')
  const diffMonths = end.diff(start, 'month', true) // float

  if (feeType.value === 'long_term_year') {
    // 按年：假设一年 8000-10000，按实际天数/365 比例或者按学期退费
    // 这里简单模拟：按天比例扣除
    unitPrice.value = 8000
    actualCost.value = (unitPrice.value / 365) * diffDays
    durationStr.value = `共住 ${diffDays} 天`
    // Mock outstanding for long term
    outstandingAmount.value = 200 // 比如水电费挂账
  } else if (feeType.value === 'temp_month') {
    // 按月：1500/月
    unitPrice.value = 1500
    actualCost.value = unitPrice.value * Math.ceil(diffMonths)
    durationStr.value = `共住 ${Math.ceil(diffMonths)} 个月`
    outstandingAmount.value = 0
  } else if (feeType.value === 'hotel_day') {
    // 按天：100/天
    unitPrice.value = 100
    actualCost.value = unitPrice.value * diffDays
    durationStr.value = `共住 ${diffDays} 天`
    outstandingAmount.value = 0
  }
}

const open = (data) => {
  student.value = data.student
  bed.value = data.bed
  roomNo.value = data.roomNo
  
  // Random mock based on student id to simulate different types
  if (student.value.id.startsWith('G')) {
     feeType.value = 'hotel_day' // Guest
     paidAmount.value = 1000
  } else if (student.value.id.startsWith('L')) {
     feeType.value = 'temp_month' // Temp
     paidAmount.value = 3000
  } else {
     feeType.value = 'long_term_year' // Student
     paidAmount.value = 8000
  }
  
  recalculate()
  visible.value = true
}

const handleRemind = () => {
  ElMessage.success('催缴通知已发送至学生手机/邮箱')
}

const viewBills = () => {
  ElMessage.info('查看挂账明细功能')
}

const handlePrint = () => {
  ElMessage.success('正在打印结算单...')
}

const handleConfirm = () => {
  const actionText = finalAmount.value >= 0 ? '退款' : '补缴'
  const absAmount = Math.abs(finalAmount.value).toFixed(2)
  
  let msg = `确认办理退宿？`
  if (finalAmount.value >= 0) {
    msg += ` 系统将自动发起 ¥${absAmount} 的退款申请。`
  } else {
    msg += ` 请确认学生已线下补缴 ¥${absAmount}。`
  }

  if (outstandingAmount.value > 0) {
    msg += ` (包含挂账扣除 ¥${outstandingAmount.value})`
  }

  ElMessageBox.confirm(msg, '结算确认', {
    confirmButtonText: '确认办理',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // Call API
    ElMessage.success('退宿办理成功')
    visible.value = false
    emit('success', {
      studentId: student.value.id,
      bedId: bed.value.id
    })
  })
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.mt-20 { margin-top: 20px; }
.mt-5 { margin-top: 5px; }
.ml-10 { margin-left: 10px; }
.ml-5 { margin-left: 5px; }
.text-success { color: var(--el-color-success); }
.text-danger { color: var(--el-color-danger); }
.text-gray { color: #909399; }
.font-bold { font-weight: bold; }
.text-xs { font-size: 12px; }

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  border-left: 4px solid var(--el-color-primary);
  padding-left: 10px;
  display: flex;
  align-items: center;
}

.result-box {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  
  .label { font-size: 14px; color: #606266; margin-bottom: 10px; }
  .value { font-size: 32px; font-weight: bold; margin-bottom: 10px; }
  .desc { font-size: 12px; color: #909399; }
}
</style>
