<template>
  <view class="apply-refund-page">
    <view class="section">
      <view class="section-title">退款类型</view>
      <radio-group @change="handleTypeChange" class="type-group">
        <label class="type-item">
          <radio value="1" :checked="refundType === 1" color="#ff4444" />
          <text>仅退款</text>
        </label>
        <label class="type-item">
          <radio value="2" :checked="refundType === 2" color="#ff4444" />
          <text>退货退款</text>
        </label>
      </radio-group>
    </view>

    <view class="section">
      <view class="section-title">退款原因</view>
      <picker @change="handleReasonChange" :range="reasonList" class="picker">
        <view class="picker-content">
          <text v-if="refundReason">{{ refundReason }}</text>
          <text v-else class="placeholder">请选择退款原因</text>
          <text class="arrow">></text>
        </view>
      </picker>
    </view>

    <view class="section">
      <view class="section-title">退款金额</view>
      <view class="amount-input-wrap">
        <text class="currency">¥</text>
        <input 
          type="digit" 
          v-model="refundAmount" 
          class="amount-input" 
          :placeholder="`最多可退 ¥${maxAmount}`"
        />
      </view>
      <text class="amount-tip">最多可退 ¥{{ maxAmount }}，含发货邮费 ¥{{ deliveryFee }}</text>
    </view>

    <view class="section">
      <view class="section-title">退款说明</view>
      <textarea 
        v-model="description" 
        class="desc-input" 
        placeholder="选填：补充详细的退款说明，有助于商家快速处理"
        maxlength="200"
      />
    </view>

    <view class="submit-bar">
      <button class="submit-btn" @click="submitRefund" :loading="submitting">提交申请</button>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
// import supa from '@/components/supadb/aksupainstance.uts'

const orderId = ref('')
const orderItemId = ref('') // Optional, if refunding specific item
const refundType = ref(1) // 1: Only Refund, 2: Return & Refund
const refundReason = ref('')
const refundAmount = ref('')
const description = ref('')
const maxAmount = ref(0)
const deliveryFee = ref(0)
const submitting = ref(false)

const reasonList = [
  '多拍/错拍/不想要',
  '快递一直未送达',
  '未按约定时间发货',
  '快递无记录',
  '空包裹/少货/错发',
  '质量问题',
  '其他'
]

onMounted(() => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options as any
  
  if (options.orderId) {
    orderId.value = options.orderId
    loadOrderInfo()
  }
})

const loadOrderInfo = async () => {
  try {
    const { data, error } = await supa
      .from('orders')
      .select('actual_amount, delivery_fee')
      .eq('id', orderId.value)
      .single()
      
    if (error == null && data != null) {
      maxAmount.value = data['actual_amount'] as number
      deliveryFee.value = data['delivery_fee'] as number
      refundAmount.value = maxAmount.value.toString()
    }
  } catch (err) {
    console.error('加载订单信息失败', err)
  }
}

const handleTypeChange = (e: any) => {
  refundType.value = parseInt(e.detail.value)
}

const handleReasonChange = (e: any) => {
  const index = e.detail.value as number
  refundReason.value = reasonList[index]
}

const submitRefund = async () => {
  if (!refundReason.value) {
    uni.showToast({ title: '请选择退款原因', icon: 'none' })
    return
  }
  
  const amount = parseFloat(refundAmount.value)
  if (isNaN(amount) || amount <= 0 || amount > maxAmount.value) {
    uni.showToast({ title: '请输入有效的退款金额', icon: 'none' })
    return
  }
  
  submitting.value = true
  
  try {
    const userStore = uni.getStorageSync('userInfo')
    const userId = userStore?.id
    
    // 1. Create Refund Record
    /* const { data, error } = await supa
      .from('refunds')
      .insert({
        user_id: userId,
        order_id: orderId.value,
        refund_no: 'REF' + Date.now(),
        refund_type: refundType.value,
        refund_reason: refundReason.value,
        refund_amount: amount,
        description: description.value,
        status: 1, // 待处理
        status_history: [{
          status: 1,
          remark: '用户提交申请',
          created_at: new Date().toISOString()
        }]
      })
      
    if (error != null) throw error */
    
    // MOCK SUBMIT
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 2. Update Order Status (Optional, e.g. to "After-sales")
    // Assuming status 6 is "After-sales/Refund"
    /*
    await supa
      .from('orders')
      .update({ status: 6 })
      .eq('id', orderId.value)
    */
    
    uni.showToast({ title: '提交成功', icon: 'success' })
    
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/mall/consumer/refund'
      })
    }, 1500)
    
  } catch (err) {
    console.error('提交退款失败', err)
    uni.showToast({ title: '提交失败，请重试', icon: 'none' })
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.apply-refund-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 15px;
  padding-bottom: 80px;
}

.section {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
}

.type-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.type-item {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.picker-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #333;
}

.placeholder {
  color: #999;
}

.arrow {
  color: #ccc;
}

.amount-input-wrap {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.currency {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-right: 10px;
}

.amount-input {
  flex: 1;
  font-size: 24px;
  font-weight: bold;
  height: 40px;
}

.amount-tip {
  font-size: 12px;
  color: #999;
}

.desc-input {
  width: 100%;
  height: 100px;
  font-size: 14px;
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 10px;
  box-sizing: border-box;
}

.submit-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
}

.submit-btn {
  background-color: #ff4444;
  color: #ffffff;
  border-radius: 22px;
  font-size: 16px;
  font-weight: bold;
}
</style>
