<template>
  <view class="min-h-screen bg-blue-50/30">
    <view class="p-4">
      <!-- 提现卡片 -->
      <view class="bg-white rounded-lg p-5 mb-4">
        <view class="flex items-center mb-6">
          <view class="w-6 h-6 bg-orange-100 rounded-full flex items-center justify-center mr-2">
            <text class="text-orange-400 text-sm">￥</text>
          </view>
          <text class="text-lg font-bold">支付宝提现</text>
        </view>

        <wd-form :model="form" :rules="rules" label-position="top" class="withdraw-form">
          <!-- 支付宝账号 -->
          <view class="mb-4">
            <view class="mb-2">
              <text class="text-red-500 mr-1">*</text>
              <text class="text-base">支付宝账号</text>
            </view>
            <wd-input v-model="form.alipayAccount" prop="alipayAccount" placeholder="请输入支付宝账号"
              custom-class="custom-input" />
            <text class="text-gray-400 text-xs mt-1 block">可填写支付宝账户绑定的手机号</text>
          </view>

          <!-- 支付宝实名姓名 -->
          <view class="mb-4">
            <view class="mb-2">
              <text class="text-red-500 mr-1">*</text>
              <text class="text-base">实名姓名</text>
            </view>
            <wd-input v-model="form.realName" prop="realName" placeholder="请输入支付宝认证姓名" custom-class="custom-input" />
            <text class="text-gray-400 text-xs mt-1 block">请填写支付宝账户认证的真实姓名</text>
          </view>

          <!-- 提现金额 -->
          <view class="mb-4">
            <view class="mb-2">
              <text class="text-red-500 mr-1">*</text>
              <text class="text-base">提现金额</text>
            </view>
            <view class="relative">
              <wd-input v-model="form.amount" prop="amount" type="digit" placeholder="请输入提现金额"
                custom-class="custom-input" @input="handleAmountInput" />
              <view class="absolute right-2 top-1/2 transform -translate-y-1/2">
                <view class="bg-blue-100 text-blue-600 rounded-full px-3 py-1 text-sm" @click="fillMaxAmount">
                  全部提现
                </view>
              </view>
            </view>
          </view>
        </wd-form>

        <!-- 金额提示 -->
        <view class="text-sm text-gray-500 my-4">
          可提现金额：<text class="text-blue-600 font-semibold">¥{{ safeTruncate(availableAmount) }}</text>
        </view>

        <!-- 提现规则 -->
        <view class="bg-gray-50 p-4 rounded-lg">
          <view class="flex items-center">
            <text class="text-orange-500 mr-1">⚠</text>
            <text class="text-blue-600 text-sm">提现须知</text>
          </view>
          <view class="text-xs text-gray-600 mt-2 space-y-1">
            <text class="block">· 每日限提现1次，最低50元</text>
            <text class="block">· 超过800元需人工审核（1-3个工作日）</text>
            <text class="block">· 到账时间：24小时内</text>
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <wd-button type="primary" block :loading="isSubmitting" @click="handleSubmit" custom-class="submit-button">
        立即提现
      </wd-button>
    </view>

    <!-- 状态弹窗 -->
    <wd-popup v-model="popupVisible" custom-class="w-[85%] rounded-xl" closable close-on-click-modal>
      <view class="p-8 bg-gradient-to-b from-white to-blue-50/30 relative">
        <!-- 状态内容 -->
        <view class="text-center space-y-5">
          <!-- 状态图标 -->
          <view class="relative inline-block">
            <view class="w-14 h-14 rounded-full flex items-center justify-center" :class="statusIconClass[status]">
              <text class="text-4xl">{{ statusIcon[status] }}</text>
            </view>
          </view>

          <!-- 状态文案 -->
          <view>
            <text class="text-xl font-semibold mb-1 block" :class="statusTextColors[status]">
              {{ statusMessages[status] }}
            </text>
            <template v-if="status === 2">
              <text class="text-sm text-gray-500 block">
                已向 <text class="text-blue-500">{{ form.alipayAccount }}</text> 转账
              </text>
              <text class="text-2xl font-bold text-green-600 mt-2 block">¥{{ form.amount }}</text>
            </template>
            <template v-if="status === 3">
              <text class="text-red-500 text-sm px-4 block">{{ failMsg }}</text>
            </template>
          </view>

          <!-- 进度条（处理中状态） -->
          <view v-if="status === 1" class="my-2">
            <wd-progress :percentage="60" hide-text color="#4080ff" />
          </view>

          <!-- 辅助文案 -->
          <view class="text-xs text-gray-400 space-y-1.5">
            <template v-if="status === 2">
              <text class="block">预计24小时内到账</text>
              <text class="block">到账后可在支付宝账单中查看详情</text>
            </template>
            <template v-if="status === 1">
              <text class="block">您的申请已进入处理队列</text>
              <text class="block">5分钟后结果在提现记录中查看</text>
            </template>
          </view>

          <!-- 操作按钮 -->
          <wd-button type="primary" block class="mt-4" :style="{ backgroundColor: statusButtonColor[status] }"
            @click="handlePopupAction">
            {{ status === 1 ? '知道了' : status === 2 ? '完成' : '重新提现' }}
          </wd-button>
        </view>
      </view>
    </wd-popup>
    <wd-toast />
  </view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useToast } from 'wot-design-uni'
import { getAgentRevenue, agentWithdrawal } from '@/apis/agent'

// 安全截断数字到指定小数位数（不进行四舍五入）
function safeTruncate(num, decimals = 2) {
  if (isNaN(num) || !isFinite(num)) return "0.00";

  const factor = 10 ** decimals;
  const scaled = Math.trunc(num * factor);
  const truncated = scaled / factor;

  return truncated.toFixed(decimals);
}

// 表单数据
const form = ref({
  alipayAccount: '',
  realName: '',
  amount: ''
})
const availableAmount = ref(0)
const isSubmitting = ref(false)

// 使用wot-design-ui的toast组件
const toast = useToast()

// 弹窗控制
const popupVisible = ref(false)

// 状态管理
const status = ref(null)
const failMsg = ref('')


// 表单验证规则
const rules = {
  alipayAccount: [
    { required: true, message: '请输入支付宝账号' }
  ],
  realName: [
    { required: true, message: '请输入姓名' },
    {
      required: true,
      pattern: /^[\u4e00-\u9fa5]{2,4}$/,
      message: '请输入2-4位中文姓名'
    }
  ],
  amount: [
    { required: true, message: '请输入提现金额' },
    {
      validator: (val) => {
        const amountNum = Number(val)
        if (isNaN(amountNum)) {
          return '请输入有效金额'
        }
        // if (amountNum < 50) {
        //   return '提现金额不能低于50元'
        // }
        if (amountNum > availableAmount.value) {
          return '超过可提现金额'
        }
        return true
      }
    }
  ]
}

// 样式配置
const statusIcon = {
  1: '⏳',
  2: '✅',
  3: '❌'
}

const statusIconClass = {
  1: 'bg-blue-100 text-blue-500 border-4 border-blue-200',
  2: 'bg-green-100 text-green-500 border-4 border-green-200',
  3: 'bg-red-100 text-red-500 border-4 border-red-200'
}

const statusTextColors = {
  1: 'text-blue-600',
  2: 'text-green-600',
  3: 'text-red-600'
}

const statusButtonColor = {
  1: '#3b82f6',
  2: '#4ade80',
  3: '#f87171'
}

const statusMessages = {
  1: '提现申请处理中，请稍后再查询结果',
  2: '提现成功',
  3: '提现失败'
}

// 返回上一页
const handleBack = () => {
  uni.navigateBack()
}

// 获取可提现金额
const getData = async () => {
  try {
    const res = await getAgentRevenue()

    if (res.code === 200) {
      availableAmount.value = res.data.balance
    } else {
      toast.error(res.msg || '获取余额失败')
    }
  } catch (error) {
    toast.error('网络错误')
  }
}

// 填充最大金额
const fillMaxAmount = () => {
  // 使用safeTruncate确保金额正确截断到2位小数
  form.value.amount = safeTruncate(availableAmount.value)
}

// 处理输入事件，控制输入格式
const handleAmountInput = (event) => {
  let value = event.value
  // 转为数字以便比较
  let numValue = parseFloat(value)

  // 如果超过可提现金额，设置为可提现金额并提示
  if (!isNaN(numValue) && numValue > availableAmount.value) {
    value = availableAmount.value
    // 使用toast提示用户
    toast.info(`金额已自动调整为最大可提现金额: ¥${value}`)
  }
  // 如果value的小数位数大于2位，才进行截断处理
  if (value.toString().includes('.') && value.toString().split('.')[1].length > 2) {
    value = safeTruncate(value)
  }
  form.value.amount = value
  console.log(value)
  console.log(form.value.amount)
}

// 提交处理
const handleSubmit = async () => {
  try {
    // 提现金额转为数字
    const amountNum = Number(form.value.amount)

    // 验证表单
    if (!form.value.alipayAccount.trim()) {
      toast.info('请输入支付宝账号')
      return
    }

    if (!form.value.realName.trim()) {
      toast.info('请输入账户实名姓名')
      return
    }

    if (!/^[\u4e00-\u9fa5]{2,4}$/.test(form.value.realName)) {
      toast.info('请输入2-4位中文姓名')
      return
    }

    if (!form.value.amount || isNaN(amountNum)) {
      toast.info('请输入有效金额')
      return
    }

    // if (amountNum < 50) {
    //   toast.info('提现金额不能低于50元')
    //   return
    // }

    if (amountNum > availableAmount.value) {
      toast.info('超过可提现金额')
      return
    }

    isSubmitting.value = true

    const res = await agentWithdrawal({
      payee_account: form.value.alipayAccount,
      amount: amountNum,
      payee_name: form.value.realName
    })

    if (res.code === 200) {
      status.value = res.data.status
      if (status.value === 3) {
        failMsg.value = res.data.fail_msg
      }
      popupVisible.value = true
    } else {
      toast.error(res.msg || '提交失败')
    }
  } catch (error) {
    toast.error('网络错误')
  } finally {
    isSubmitting.value = false
  }
}

// 弹窗操作
const handlePopupAction = () => {
  popupVisible.value = false

  if (status.value === 2) {
    resetForm()
    getData()
  }
}

// 重置表单
const resetForm = () => {
  status.value = null
  form.value = {
    alipayAccount: '',
    realName: '',
    amount: ''
  }
}

// 页面加载
onMounted(() => {
  getData()
})
</script>

<style>
@keyframes progress {
  0% {
    width: 0;
  }

  100% {
    width: 60%;
  }
}

.animate-progress {
  animation: progress 1.5s ease-in-out infinite;
  animation-direction: alternate;
}

/* 自定义样式 */
.withdraw-form :deep(.wd-form-item) {
  margin-bottom: 0;
}

.withdraw-form :deep(.wd-input__label) {
  display: none;
}

.withdraw-form :deep(.custom-input .wd-input__inner) {
  padding: 10px 15px;
  font-size: 14px;
  height: 45px;
  border: none;
  background-color: rgba(64, 128, 255, 0.05);
  border-radius: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.withdraw-form :deep(.custom-input:focus-within .wd-input__inner) {
  border: 2px solid #4080ff;
  background-color: rgba(64, 128, 255, 0.08);
  box-shadow: 0 0 0 2px rgba(64, 128, 255, 0.1);
}

.withdraw-form :deep(.wd-input__prefix) {
  display: none;
}

.submit-button {
  height: 45px;
  border-radius: 6px;
  background-color: #4080ff !important;
  font-size: 16px;
}
</style>
<route type="page" lang="json">{
  "layout": "page",
  "title": "提现",
  "auth": true,
  "agent": true
}</route>