<template>
    <view class="withdraw-container">
        <!-- 顶部banner轮播图 -->
        <!-- <view class="banner">
      <swiper
        :indicator-dots="false"
        :autoplay="true"
        :interval="3000"
        :duration="500"
        circular
        style="width: 100%; height: 390rpx;"
      >
        <swiper-item v-for="(item, index) in bannerList" :key="item.id || index">
          <image v-if="item.image" :src="item.image" mode="aspectFill" style="width: 100%; height: 100%;" />
        </swiper-item>
      </swiper>
    </view>
    <view class="nav-bar">
      <view class="back" @tap="goBack">
        <uni-icons type="left" size="20"></uni-icons>
      </view>
      <text class="title">提现</text>
    </view> -->

        <navbar title="提现" leftClick @leftClick="$utils.navigateBack" />

        <!-- 主内容卡片 -->
        <view class="main-card" :style="{ marginLeft: '24rpx', marginRight: '24rpx' }">
            <!-- <view class="section-title">微信提现</view> -->
            <view class="form-group">
                <view class="form-label">真实姓名</view>
                <input class="form-input" v-model="realName" placeholder="请输入" placeholder-class="input-placeholder" />
            </view>
            <view class="divider"></view>
            <view class="form-group">
                <view class="form-label">提现金额</view>
                <input class="form-input" v-model="amount" type="digit" placeholder="请输入" 
                placeholder-class="input-placeholder" />
            </view>
        </view>

        <!-- 说明文字 -->
        <view class="desc-area">
            <text>
                请仔细检查并确认相关信息，因用户个人疏忽导致的充值错误，需由用户自行承担。
                <text class="desc-link" @tap="showNotice">《提现须知》</text>
            </text>
        </view>

        <!-- 提现须知弹窗 -->
        <view v-if="showNoticePopup" class="notice-popup">
            <view class="popup-mask" @tap="closeNotice"></view>
            <view class="popup-content">
                <view class="popup-title">提现须知</view>
                <scroll-view class="popup-body" scroll-y>
                    <!-- <view class="section">
            <text class="section-title">1.适用范围:</text>
            <text class="section-content">(1)本规则仅适用于【可提现】账户</text>
          </view>
          <view class="section">
            <text class="section-title">2.提现规则:</text>
            <text class="section-content">(1)提现时间:订单确认收货次月25日可提现。由于财务审核、遇节假日、不可抗力等原因，部分时间段将无法支持提现操作，具体请以提现页面信息为准。</text>
            <text class="section-content">(2)提现限额:单笔提现不能低于人民币10元，不能超过5万元，具体请以提现页面信息为准。</text>
            <text class="section-content">到账时间:一般发起提现申请后48小时内到账您在瀚海回收绑定的微信账户上。</text>
            <text class="section-content">(3)提现账号绑定:一个瀚海回收账号只可以绑定一个微信账号</text>
            <text class="section-content">(4)账号进行提现:需要确认您填写的微信账号信息是真实有效的，否则有可能会导致您提现失败。</text>
            <text class="section-content">(5)提现条件:您应满足瀚海回收提现的前置条件，并根据提现页面提示的流</text>
          </view> -->
                    <uv-parse :content="withdrawal_instructions"></uv-parse>
                </scroll-view>
                <view class="popup-footer">
                    <text class="confirm-btn" @tap="closeNotice">知道了</text>
                </view>
            </view>
        </view>

        <!-- 底部按钮 -->
        <view class="footer-btn-area">
            <button :class="['main-btn', fromPromotion ? 'promotion' : '', loading ? 'loading' : '']" 
                    :disabled="loading" 
                    @tap="submitWithdraw">
                {{ loading ? '提现中...' : '提现' }}
            </button>
        </view>
    </view>
</template>

<script>
import pullRefreshMixin from '@/pages/mixins/pullRefreshMixin.js'
import navbar from '@/compoent/base/navbar.vue'
import api from '@/api/api.js'
import config from '@/config.js'
export default {
    mixins: [pullRefreshMixin],
    components: {
        navbar
    },
    data() {
        return {
            realName: '',
            amount: '',
            showNoticePopup: false,
            fromPromotion: false,
            bannerList: [],
            loading: false
        }
    },
    onLoad(options) {
        if (options && options.fromPromotion === 'true') {
            this.fromPromotion = true
        }
        this.bannerList = getApp().globalData.bannerList || []
    },
    computed: {
        withdrawal_instructions() {
            const item = getApp().globalData.configData.find(i => i.keyName === 'withdrawal_instructions')
            return item ? item.keyContent : ''
        },
    },
    methods: {
        async onRefresh() {
            // 模拟刷新数据
            await new Promise(resolve => setTimeout(resolve, 1000))
            uni.stopPullRefresh()
        },
        goBack() {
            uni.navigateBack()
        },
        showNotice() {
            this.showNoticePopup = true
        },
        closeNotice() {
            this.showNoticePopup = false
        },
        async submitWithdraw() {
            // 表单验证
            if (!this.realName) {
                uni.showToast({ title: '请输入真实姓名', icon: 'none' })
                return
            }
            if (!this.amount) {
                uni.showToast({ title: '请输入提现金额', icon: 'none' })
                return
            }
            
            // 验证金额格式
            const amountNum = parseFloat(this.amount)
            if (isNaN(amountNum) || amountNum <= 0) {
                uni.showToast({ title: '请输入有效的提现金额', icon: 'none' })
                return
            }
            
            // 验证最小提现金额
            if (amountNum <= 0.3) {
                uni.showToast({ title: '单笔提现不能低于等于0.3元', icon: 'none' })
                return
            }
            
            // 验证最大提现金额
            if (amountNum > 200) {
                uni.showToast({ title: '单笔提现不能超过200元，请分多次提现', icon: 'none' })
                return
            }
            
            if (this.loading) {
                return
            }
            
            this.loading = true
            
            try {
                // 调用提现接口
                const withdrawData = {
                    userName: this.realName,
                    money: amountNum
                }
                
                const result = await api('withdraw', withdrawData, '提现申请中...')
                
                if (result.code === 200) {
                    // 提现申请成功，调用微信商户转账
                    await this.requestWechatTransfer(result.result)
                } else {
                    uni.showToast({ 
                        title: result.message || '提现申请失败', 
                        icon: 'none' 
                    })
                }
                
            } catch (error) {
                console.error('提现失败:', error)
                uni.showToast({ 
                    title: error.message || '提现申请失败', 
                    icon: 'none' 
                })
            } finally {
                this.loading = false
            }
        },
        
        // 微信商户转账
        async requestWechatTransfer(withdrawData) {
            try {
                let payData = withdrawData.response
                // 调用微信商户转账API
                const transferResult = await new Promise((resolve, reject) => {
                    // 拉起微信收款确认页面
                    if (!wx.canIUse('requestMerchantTransfer')) {
                        wx.showModal({
                            content: '你的微信版本过低，请更新至最新版本。',
                            showCancel: false,
                        });
                        return
                    }
                    
                    // 在真机环境中，调用API
                    wx.requestMerchantTransfer({
                        mchId: config.mchId,
                        appId: wx.getAccountInfoSync().miniProgram.appId,
                        package: payData.packageInfo,
                        success: (res) => {
                            resolve(res)
                        },
                        fail: (res) => {
                            reject(res)
                        },
                        complete: (res) => {
                        }
                    });
                })

                
                // 转账成功后调用成功接口
                await api('withdrawSUccess', { id: withdrawData.id }, '确认提现中...')

                this.realName = ''
                this.amount = ''
            } catch (error) {
                throw error
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.withdraw-container {
    min-height: 100vh;
    background: #f8f8f8;
    padding-bottom: calc(160rpx + env(safe-area-inset-bottom));
}

.main-card {
    background: #fff;
    border-radius: 32rpx;
    box-shadow: 0 8rpx 32rpx rgba(60, 167, 250, 0.06);
    padding: 48rpx 36rpx 32rpx 36rpx;
    position: relative;
}

.section-title {
    font-size: 34rpx;
    font-weight: bold;
    color: #222;
    margin-bottom: 40rpx;
}

.form-group {
    margin-bottom: 0;
}

.form-label {
    font-size: 28rpx;
    color: #222;
    font-weight: 500;
    margin-bottom: 16rpx;
}

.form-input {
    width: 100%;
    font-size: 28rpx;
    color: #222;
    background: none;
    border: none;
    outline: none;
    padding: 16rpx 0 22rpx 0;
}

.input-placeholder {
    color: #ccc;
    font-size: 28rpx;
}

.divider {
    border-bottom: 1rpx solid #eee;
    margin: 0 0 24rpx 0;
}

.desc-area {
    margin: 36rpx 40rpx 0 40rpx;
    font-size: 24rpx;
    color: #bbb;
    line-height: 1.7;
    text-align: left;
}

.desc-link {
    color: #FFA800;
    margin-left: 4rpx;
    white-space: nowrap;
}

.footer-btn-area {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 10;
    background: #fff;
    padding: 24rpx 0 env(safe-area-inset-bottom);
    display: flex;
    justify-content: center;
}

.main-btn {
    width: 92%;
    height: 100rpx;
    background: linear-gradient(90deg, #FFD36D 0%, #FFA800 100%);
    color: #fff;
    font-size: 36rpx;
    border-radius: 50rpx;
    font-weight: bold;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 16rpx rgba(255, 168, 0, 0.08);
    border: none;
}

.main-btn.promotion {
    background: linear-gradient(90deg, #c2fdab 0%, #08eae0 100%);
    color: #222;
}

.main-btn.loading {
    opacity: 0.7;
    pointer-events: none;
}

.main-btn:disabled {
    opacity: 0.7;
    pointer-events: none;
}

.notice-popup {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 2000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.popup-mask {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.55);
}

.popup-content {
    position: relative;
    width: 86vw;
    max-width: 650rpx;
    background: #fff;
    border-radius: 40rpx;
    overflow: hidden;
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.10);
    display: flex;
    flex-direction: column;
    align-items: center;
}

.popup-title {
    text-align: center;
    font-size: 38rpx;
    font-weight: bold;
    color: #222;
    margin: 48rpx 0 32rpx 0;
}

.popup-body {
    max-height: 600rpx;
    padding: 0 40rpx 0 40rpx !important;
    font-size: 28rpx;
    color: #888;
    line-height: 1.9;
    margin-bottom: 24rpx;
    box-sizing: border-box;
    width: 100%;
}

.section-title {
    font-size: 28rpx;
    color: #888;
    font-weight: bold;
    margin-top: 0;
    margin-bottom: 0;
    display: block;
}

.section-content {
    font-size: 28rpx;
    color: #888;
    margin-bottom: 8rpx;
    display: block;
    word-break: break-all;
}

.popup-footer {
    border-top: 1rpx solid #f2f2f2;
    width: 100%;
    padding: 24rpx 0 32rpx 0;
    display: flex;
    justify-content: center;
}

.confirm-btn {
    color: #FFA800;
    font-size: 34rpx;
    font-weight: bold;
    text-align: center;
}
</style>