<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="#ff5000" class="type-radio" />
          <text>仅退款</text>
        </label>
        <label class="type-item">
          <radio value="2" :checked="refundType === 2" color="#ff5000" class="type-radio" />
          <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"
      ></textarea>
    </view>

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

<script setup lang="uts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { supabaseService } from '@/utils/supabaseService.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 = [
  '多拍/错拍/不想要',
  '快递一直未送达',
  '未按约定时间发货',
  '快递无记录',
  '空包裹/少货/错发',
  '质量问题',
  '其他'
]

const loadOrderInfo = async () => {
  try {
    const orderData = await supabaseService.getOrderDetail(orderId.value)
      
    if (orderData != null) {
      // Cast to UTSJSONObject to access properties safely
      const order = orderData as UTSJSONObject
      const total = order.getNumber('total_amount') ?? 0
      const shipping = order.getNumber('shipping_fee') ?? 0
      
      maxAmount.value = total
      deliveryFee.value = shipping
      refundAmount.value = maxAmount.value.toString()
    }
  } catch (err) {
    console.error('加载订单信息失败', err)
    uni.showToast({
        title: '加载订单失败',
        icon: 'none'
    })
  }
}

onLoad((options) => {
  if (options['orderId'] != null) {
    orderId.value = options['orderId'] as string
    loadOrderInfo()
  }
})

const handleTypeChange = (e: any) => {
  // Use bracket notation to access detail property safely on 'any' type in UTS
  // The structure is e -> detail -> value
  // We need to cast e to UTSJSONObject first if we want to use bracket notation,
  // OR we can use JSON.parse/stringify trick if simple casting fails,
  // BUT the most standard way for UTS 'any' which is actually a Map/JSONObject at runtime:
  
  const target = e as UTSJSONObject
  const detail = target['detail'] as UTSJSONObject
  const value = detail['value'] as string
  refundType.value = parseInt(value)
}

const handleReasonChange = (e: any) => {
  // Use bracket notation to access detail property safely on 'any' type in UTS
  const target = e as UTSJSONObject
  const detail = target['detail'] as UTSJSONObject
  const value = detail['value'] as number
  const index = value
  refundReason.value = reasonList[index]
}

const submitRefund = async () => {
  console.log('=== 提交退款 ===')
  console.log('refundReason:', refundReason.value)
  console.log('refundAmount:', refundAmount.value)
  console.log('maxAmount:', maxAmount.value)
  
  if (refundReason.value == '') {
    uni.showToast({ title: '请选择退款原因', icon: 'none' })
    return
  }
  
  const amount = parseFloat(refundAmount.value)
  console.log('解析后金额:', amount)
  
  if (isNaN(amount) || amount <= 0 || amount > maxAmount.value) {
    uni.showToast({ title: '请输入有效的退款金额', icon: 'none' })
    return
  }
  
  submitting.value = true
  uni.showLoading({ title: '提交中...' })
  
  try {
    console.log('调用 createRefund, orderId:', orderId.value)
    const result = await supabaseService.createRefund({
      order_id: orderId.value,
      refund_type: refundType.value,
      refund_reason: refundReason.value,
      refund_amount: amount,
      description: description.value
    })
    
    console.log('createRefund 结果:', JSON.stringify(result))
    uni.hideLoading()
    
    if (result.success) {
        uni.showToast({ title: '提交成功', icon: 'success' })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
    } else {
        uni.showToast({ title: result.message, icon: 'none' })
    }
  } catch (err) {
    console.error('提交退款失败', err)
    uni.hideLoading()
    uni.showToast({ title: '提交异常', icon: 'none' })
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.apply-refund-page {
  flex: 1;
  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;
}

.type-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 14px;
}

.type-radio {
    margin-right: 10px;
}

.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: #ff5000;
  color: #ffffff;
  border-radius: 22px;
  font-size: 16px;
  font-weight: bold;
}
</style>

