<template>
    <view class="partner-apply">
        <!-- 手机号和验证码区域 -->
        <u-form :model="form" ref="uForm" :rules="rules" :error-type="['toast']" :label-width="160">
            <view class="form-section">
                <u-form-item label="新手机号" prop="mobile">
                    <u-input v-model="form.mobile" placeholder="获取手机号码" />
                    <!-- #ifdef MP-WEIXIN -->
                    <u-button slot="right" type="success" size="mini" open-type="getPhoneNumber"
                        @getphonenumber="getPhoneNumber" plain>获取手机号</u-button>
                    <!-- #endif -->
                    <!-- #ifdef MP-ALIPAY -->
                    <button class="phone-btn" slot="right" type="success" size="mini" scope="phoneNumber"
                        open-type="getAuthorize" @getAuthorize="onGetAuthorize" @error="handleAuthError">获取手机号</button>
                    <!-- #endif -->
                </u-form-item>

                <u-form-item label="验证码" prop="verifyCode">
                    <u-input v-model="form.verifyCode" placeholder="请输入验证码" />
                    <u-button slot="right" type="success" size="mini" @click="getCode" :disabled="counting" plain>
                        {{ counting ? `${countdown}s后获取` : "获取验证码" }}
                    </u-button>
                </u-form-item>
            </view>

            <!-- 基本信息区域 -->
            <view class="form-section">
                <u-form-item label="姓名" prop="name" required>
                    <u-input v-model="form.name" placeholder="请输入真实姓名" />
                </u-form-item>

                <u-form-item label="地址选择" prop="address" required>
                    <uni-data-picker v-model="selAddressCodes" :localdata="dataList" placeholder="请选择所在区县"
                        popup-title="请选择所在区县" @change="cityChange"></uni-data-picker>
                </u-form-item>

                <u-form-item label="学校" prop="school" required>
                    <u-input v-model="form.school" placeholder="请输入学校" />
                </u-form-item>

                <u-form-item label="院系" prop="faculties" required>
                    <u-input v-model="form.faculties" placeholder="请输入院系" />
                </u-form-item>

                <u-form-item label="专业" prop="specialty" required>
                    <u-input v-model="form.specialty" placeholder="请输入专业" />
                </u-form-item>

                <u-form-item label="年级" prop="grade" required>
                    <u-input v-model="form.grade" placeholder="请输入年级" />
                </u-form-item>
            </view>
        </u-form>

        <view class="agreement">
            <u-checkbox v-model="agreement" shape="circle">
                <text>我已阅读并同意</text>
                <text class="agreement-link" @click="goToAgreement">《书嗨用户协议》</text>
            </u-checkbox>
        </view>

        <view class="fixed-bottom">
            <u-button type="primary" color="#38C148" @click="submit">提交</u-button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            form: {
                provinceId: "",
                cityId: "",
                districtId: "",
                name: "",
                school: "",
                faculties: "",
                specialty: "",
                grade: "",
                mobile: "",
                verifyCode: "",
            },
            agreement: false,
            counting: false,
            countdown: 60,
            rules: {
                mobile: [{ required: true, message: "请输入手机号" }],
                verifyCode: [{ required: true, message: "请输入验证码" }],
                name: [{ required: true, message: "请输入真实姓名" }],
                school: [{ required: true, message: "请输入学校" }],
                faculties: [{ required: true, message: "请输入院系" }],
                specialty: [{ required: true, message: "请输入专业" }],
                provinceId: [{ required: true, message: "请选择所在区县" }],
                grade: [{ required: true, message: "请输入年级" }],
            },
            // 省市区相关数据
            selAddressCodes: [],
            dataList: [],
        };
    },
    onLoad() {
        // 获取省市区数据
        this.getDistrictData();
    },
    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm?.setRules(this.rules);
	},
    methods: {
        // 获取省市区数据
        async getDistrictData() {
            try {
                const res = await uni.$u.http.get("/token/getAllDistrict");
                if (res.code == 200) {
                    this.dataList = res.data;
                }
            } catch (error) {
                uni.$u.toast("获取地区数据失败");
            }
        },

        // 省市区选择回调
        cityChange(e) {
            let { value } = e.detail;
            if (!value.length) return;
            this.form.provinceId = value[0].value;
            this.form.cityId = value[1].value;
            this.form.districtId = value[2].value || "";
        },
        //支付宝获取手机号
        onGetAuthorize(e) {
            my.getPhoneNumber({
                success: (res) => {
                    this.getPhoneNumberApi(res.response, 'alipay')
                },
                fail: (err) => {
                    console.log('获取手机号失败', err);
                }
            })
        },
        handleAuthError(e) {
            console.log(e, 'handleAuthError')
        },

        // 获取手机号
        async getPhoneNumber(e) {
            if (e.detail.errMsg !== "getPhoneNumber:ok") {
                return uni.$u.toast("获取手机号失败");
            }

            try {
                uni.showLoading({
                    title: "手机号获取中",
                });

                // 调用后端接口解密手机号
                this.getPhoneNumberApi(e.detail.code)
            } catch (error) {
                uni.$u.toast("手机号获取失败");
            } finally {
                uni.hideLoading();
            }
        },

        // 获取手机号
        getPhoneNumberApi(code, type = 'wechat') {
            let params = type === 'wechat' ? { code } : code
            // 调用后端接口解密手机号
            uni.$u.http.post('/token/user/wxMobileUpdate', params).then(res => {
                if (res.code === 200) {
                    this.form.mobile = res.data.mobile;
                    uni.showToast({
                        title: "手机号绑定成功",
                        icon: "success",
                    });
                } else {
                    uni.$u.toast(res.msg);
                }
            })
        },

        async getCode() {
            if (!this.form.mobile) {
                uni.$u.toast("请先获取手机号");
                return;
            }

            try {
                const res = await uni.$u.http.post("/token/applyPartner/getMobileCode", {
                    mobile: this.form.mobile,
                });

                if (res.code === 200) {
                    this.startCountdown();
                    uni.$u.toast("验证码已发送");
                } else {
                    uni.$u.toast(res.msg);
                }
            } catch (error) {
                uni.$u.toast("获取验证码失败");
            }
        },

        startCountdown() {
            this.counting = true;
            this.countdown = 60;
            const timer = setInterval(() => {
                this.countdown--;
                if (this.countdown <= 0) {
                    clearInterval(timer);
                    this.counting = false;
                }
            }, 1000);
        },

        goToAgreement() {
            uni.navigateTo({
                url: "/pages-home/pages/user-agreement",
            });
        },

        async submit() {
            if (!this.agreement) {
                uni.$u.toast("请先阅读并同意用户协议");
                return;
            }
            try {
                this.$refs.uForm.validate(async (valid) => {
                    if (valid) {
                        const res = await uni.$u.http.post("/token/applyPartner", this.form);
                        if (res.code === 200) {
                            uni.navigateTo({
                                url: "/pages-mine/pages/partner/partner-status?status=pending",
                            });
                        } else {
                            uni.$u.toast(res.msg);
                        }
                    }
                });
            } catch (error) {
                uni.$u.toast("提交失败");
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.partner-apply {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 20rpx;
    padding-bottom: 120rpx;

    .form-section {
        background-color: #fff;
        margin-bottom: 20rpx;
        padding: 0 30rpx;
        border-radius: 10rpx;

        :deep(.u-form-item) {
            .u-form-item--left {
                white-space: nowrap;
            }

            .u-button {
                margin-left: 20rpx;
            }
        }
    }

    .agreement {
        margin: 30rpx;
        display: flex;

        .agreement-link {
            color: #38c148;
        }
    }

    .phone-btn {
        color: #19be6b;
        border: 1px solid #71d5a1;
        background-color: #dbf1e1;
        font-size: 12px;
        padding: 0 20rpx;
        height: 52rpx;
        line-height: 52rpx;
        border-radius: 2rpx;
        &::after{
            border: none;
        }
    }

    .fixed-bottom {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #fff;
        padding: 20rpx 30rpx;
        box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
        padding-bottom: 60rpx;

        .u-button {
            width: 100%;
            height: 80rpx;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}
</style>
