<template>
    <z-paging ref="paging" bgColor="#fff">
        <template #top>
            <up-navbar :fixed="true" title="登录注册" bgColor="transparent">
                <template #left>
                    <up-icon @click="homeBack()" name="arrow-left" color="#333" size="40rpx"></up-icon>
                </template>
            </up-navbar>
        </template>
        <view class="h-620 w-100%" style="background: url('https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/loginTopBg.png'); background-size: auto 100%; background-repeat: no-repeat; position: absolute; top: 0; left: 0; z-index: -1"> </view>
        <view class="login-centent">
            <view class="login-logo-wrap p-rtv d-flex j-c a-c b-radius"></view>
            <view v-if="!isShowPhoneLogin" class="login-form pl-20 pd-25 b-radius p-rtv">
                <image class="w-100%" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/loginMidBg.png" mode="widthFix" style="position: absolute; top: 0; left: 0" />
                <view class="pd-40"></view>
                <template v-if="isBindPhone">
                    <up-button class="mb-40" @click="handleLogin" color="#28A94B" type="primary" shape="circle">
                        <view class="d-flex a-c j-c">
                            <image class="w-45 mr-10" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/login/weixin_logo.png" mode="widthFix" />
                            一键登录
                        </view>
                    </up-button>
                </template>
                <template v-else>
                    <up-button class="mb-40" color="#28A94B" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" type="primary" shape="circle">
                        <view class="d-flex a-c j-c">
                            <image class="w-45 mr-10" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/login/weixin_logo.png" mode="widthFix" />
                            一键登录
                        </view>
                    </up-button>
                </template>
                <view class="d-flex a-c pd-10 mb-20" @click="clickAgree">
                    <up-checkbox activeColor="#2A6D52" size="32rpx" name="agree" usedAlone v-model:checked="form.aloneChecked"></up-checkbox>
                    <view class="d-flex a-c f-s-24">
                        <text class="c-999">我已阅读并同意</text>
                        <text class="c-primary" @click="$u.route({ url: '/views/tool/agreement/agreement' })">《用户协议》</text>
                        <text class="c-666">和</text>
                        <text class="c-primary" @click="$u.route({ url: '/views/tool/privacy/privacy' })">《隐私政策》</text>
                    </view>
                </view>
                <official-account></official-account>
            </view>
            <view v-if="isShowPhoneLogin" class="login-form pl-20 pd-25 b-radius">
                <up-form :model="forms" :rules="rules" ref="upFormRef" labelWidth="auto" labelPosition="top">
                    <up-form-item prop="phonenumber">
                        <up-input v-model="forms.phonenumber" fontSize="28rpx" :prefixIconStyle="prefixIconStyle" placeholderClass="placeholder" :customStyle="customStyle" maxlength="11" placeholder="请输入您的手机号" border="none" clearable shape="circle">
                            <template #prefix>
                                <view class="d-flex a-c mr-20">
                                    <image class="small-icon" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/login-phone/tel_icon.png" mode="widthFix" />
                                </view>
                            </template>
                        </up-input>
                    </up-form-item>
                    <up-form-item prop="smsCode">
                        <up-input v-model="forms.smsCode" fontSize="28rpx" :prefixIconStyle="prefixIconStyle" placeholderClass="placeholder" :customStyle="customStyle" placeholder="请输入验证码" border="none" clearable shape="circle">
                            <template #prefix>
                                <view class="d-flex a-c mr-20">
                                    <image class="small-icon" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images/login-phone/sms_code_icon.png" mode="widthFix" />
                                </view>
                            </template>
                            <template #suffix>
                                <up-button :disabled="disabled" @click="sendCode" style="color: #2a6d52" type="primary" color="#F6F6F6">
                                    <up-count-down ref="countDown" @change="onChange" :autoStart="false" :time="60 * 1000" format="（ss）" millisecond @finish="finish">
                                        <text>{{ codeText }}</text>
                                    </up-count-down>
                                </up-button>
                            </template>
                        </up-input>
                    </up-form-item>
                    <view class="pd-40"></view>
                    <up-button type="primary" @click="save" shape="circle">登录</up-button>
                    <up-form-item prop="aloneChecked">
                        <view class="d-flex a-c pd-10" @click="clickAgrees">
                            <up-checkbox activeColor="#2A6D52" size="32rpx" name="agree" usedAlone v-model:checked="forms.aloneChecked"></up-checkbox>
                            <view class="d-flex a-c f-s-24">
                                <text class="c-999">我已阅读并同意</text>
                                <text class="c-primary" @click="$u.route({ url: '/views/tool/agreement/agreement' })">《用户协议》</text>
                                <text class="c-666">、</text>
                                <text class="c-primary" @click="$u.route({ url: '/views/tool/privacy/privacy' })">《隐私政策》</text>
                            </view>
                        </view>
                    </up-form-item>
                </up-form>
            </view>
            <up-divider text="更多登录方式" class="pd-30"></up-divider>
            <view class="d-flex j-sa pl-20 pr-20">
                <view v-if="!isShowPhoneLogin" class="d-flex flex-cln j-c a-c" @click="isShowPhoneLogin = true">
                    <view class="bc-#f2f2f2 d-flex j-c a-c">
                        <image class="w-95 h-95" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/accountNumber.png" mode="widthFix" />
                    </view>
                    <view class="c-#ccc f-s-24 pt-10">账号密码</view>
                </view>
                <view v-if="isShowPhoneLogin" class="d-flex flex-cln j-c a-c" @click="isShowPhoneLogin = false">
                    <view class="bc-#f2f2f2 d-flex j-c a-c">
                        <image class="w-95 h-95" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/QuickLogin.png" mode="widthFix" />
                    </view>
                    <view class="c-#ccc f-s-24 pt-10">一键登录</view>
                </view>
                <view class="d-flex flex-cln j-c a-c">
                    <view class="bc-#f2f2f2 d-flex j-c a-c">
                        <image class="w-95 h-95" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/SZYYLogo.png" mode="widthFix" />
                    </view>
                    <view class="c-#ccc f-s-24 pt-10">数字云药</view>
                </view>
                <view class="d-flex flex-cln j-c a-c">
                    <view class="bc-#f2f2f2 d-flex j-c a-c">
                        <image class="w-95 h-95" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/cxlmLogo.png" mode="widthFix" />
                    </view>
                    <view class="c-#ccc f-s-24 pt-10">中药材创新联盟</view>
                </view>
            </view>
        </view>
        <image class="login-bttom-bg" src="https://ta.zycpzs.cn/oss-file/smart-trace/szyy/images-plt/plant/loginBottomBg.png" mode="widthFix" />
    </z-paging>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { useInfoStore } from '@/store';
import config from '@/config';
import { debounce } from 'uview-plus';
import { onLoad } from '@dcloudio/uni-app';
import { recursiveDecodeURIComponent } from '@/utils/ruoyi';
import { useClientRequest } from '@/utils/request';
const pages = ref(getCurrentPages());
const infoStore = useInfoStore();
const paging = ref(null);
const redirect = ref('');
// 判断是否绑定手机号
const isBindPhone = ref(0);
// 判断是否展示手机号登录
const isShowPhoneLogin = ref(false);
const form = ref({
    aloneChecked: false,
    phoneCode: '',
    xcxcode: '',
    grantType: 'xcx',
    clientId: config.clientId,
    // tenantId: config.tenantId,
});
const clickAgree = () => {
    form.value.aloneChecked = !form.value.aloneChecked;
};

const checkUserRegist = (data) => {
    return useClientRequest.post('/plt-api/auth/checkUserRegist', data, false);
};
const getPhoneNumber = (e) => {
    console.log(e);
    // 判读是否获取成功
    if (!e.detail.code) {
        uni.showToast({
            title: '获取手机号失败',
            icon: 'none',
        });
        return;
    }
    form.value.phoneCode = e.detail.code;
    // 判断是否勾选隐私协议
    if (!form.value.aloneChecked) {
        uni.showToast({
            title: '请阅读并同意用户协议和隐私政策',
            icon: 'none',
        });
        return;
    }
    // 手机号登录方法
    handleLogin();
};
const handleLogin = () => {
    // 判断是否勾选隐私协议
    if (!form.value.aloneChecked) {
        uni.showToast({
            title: '请阅读并同意用户协议和隐私政策',
            icon: 'none',
        });
        return;
    }
    // 微信小程序登录获取的code
    uni.login({
        provider: 'weixin',
        success: function (loginRes) {
            // 获取用户信息
            if (loginRes.errMsg === 'login:ok') {
                form.value.xcxcode = loginRes.code;
                // 请求登录接口
                weixinLogin();
            }
        },
    });
};
const weixinLogin = async () => {
    try {
        // 请求登录接口
        uni.showLoading({
            title: '登录中...',
            mask: true,
        });
        //判断是什么类型的登录
        if (isShowPhoneLogin) {
            console.log(form.value, 'form.value');

            await infoStore.wxLogin(form.value);
        } else {
            await infoStore.wxLogin(forms.value);
        }

        // 调用获取用户信息接口
        infoStore.getUserInfo();
        console.log('调用获取用户信息接口');

        infoStore.getCompanyInfo();
        uni.hideLoading();
        // 重定向或跳转首页
        // 获取redirect参数
        const redirectUrl = redirect.value || '/pages/plant/base/index';
        // switchTab 页面
        const switchTabs = ['/pages/plant/base/index', '/pages/plant/port/index', '/pages/plant/processing/index', '/pages/plant/more/index'];
        if (switchTabs.includes(redirectUrl)) {
            uni.$u.route({
                type: 'switchTab',
                url: redirectUrl,
            });
            return;
        }
        uni.$u.route({
            type: 'redirect',
            url: redirectUrl,
        });
    } catch (error) {
        console.log(error);
        uni.showToast({
            title: error.msg || '登录失败，请稍后重试',
            icon: 'none',
        });
    }
};
// 判断用户是否绑定手机号
const hasBindPhone = async () => {
    // 微信小程序登录获取的code
    uni.login({
        provider: 'weixin',
        success: function (loginRes) {
            // 获取用户信息
            if (loginRes.errMsg === 'login:ok') {
                console.log(loginRes, 'loginRes');
                checkUserRegist({
                    code: loginRes.code,
                    clientId: config.clientId,
                }).then((res) => {
                    if (res.code === 200) {
                        isBindPhone.value = +res.data;
                    }
                });
            }
        },
    });
};
const homeBack = () => {
    const pages = getCurrentPages();
    if (pages.length > 1) {
        uni.navigateBack();
    } else {
        const redirectUrl = redirect.value || '/pages/list/index';
        const switchTabs = ['/pages/plant/base/index', '/pages/plant/port/index', '/pages/plant/processing/index', '/pages/plant/more/index'];
        if (switchTabs.includes(redirectUrl)) {
            uni.$u.route({
                type: 'switchTab',
                url: redirectUrl,
            });
            return;
        } else {
            uni.$u.route({
                type: 'switchTab',
                url: '/pages/list/index',
            });
        }
    }
};
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const codeText = ref('获取验证码');
const countDown = ref(null);
const upFormRef = ref(null);
const timeData = ref({});
const disabled = ref(false);
const finish = (e) => {
    disabled.value = false;
    codeText.value = '重新发送';
};
const forms = ref({
    phonenumber: '',
    smsCode: '',
    clientId: config.clientId,
    grantType: 'app_sms',
    aloneChecked: false,
    mverify: false,
});
const rules = reactive({
    phonenumber: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
    ],
    smsCode: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { pattern: /^[0-9]*$/, message: '验证码格式不正确', trigger: 'blur' },
    ],
});
const onChange = (e) => {
    timeData.value = e;
    if (+e.seconds) {
        codeText.value = `重新发送(${e.seconds + 1})`;
    }
};
const customStyle = reactive({
    padding: '0 50rpx',
    backgroundColor: '#F6F6F6',
    height: '98rpx',
});
const prefixIconStyle = reactive({
    // flex上下居中
    display: 'flex',
    alignItems: 'center',
    marginRight: '20rpx',
});
const clickAgrees = () => {
    forms.value.aloneChecked = !forms.value.aloneChecked;
};
const sendCode = () => {
    debounce(async () => {
        upFormRef.value?.validateField('phonenumber', (errorsRes) => {
            if (!errorsRes.length) {
                getCode();
            }
        });
    }, 500);
};
// 获取验证码
const getCode = async () => {
    const res = await useClientRequest.get('/app/auth/sendVercode', { phone: forms.value.phonenumber }, false);
    if (res.code === 200) {
        uni.showToast({
            title: '验证码发送成功',
            icon: 'none',
        });
        countDown.value?.start();
        disabled.value = true;
    }
};
const save = () => {
    debounce(async () => {
        upFormRef.value
            ?.validate()
            .then((res) => {
                if (res) {
                    // 判断是否勾选隐私协议
                    if (!forms.value.aloneChecked) {
                        uni.showToast({
                            title: '请阅读并同意用户协议和隐私政策',
                            icon: 'none',
                        });
                        return;
                    }
                    weixinLogin();
                }
            })
            .catch((error) => {});
    }, 500);
};
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

onLoad((options) => {
    // 获取redirect参数
    const redirectStr = options.redirect ? recursiveDecodeURIComponent(options.redirect) : '';
    console.log(redirectStr, 'redirectStr');
    redirect.value = redirectStr;
    // 判断用户是否绑定手机号
    hasBindPhone();
});
</script>

<style lang="scss" scoped>
.login-logo-wrap {
    width: 750rpx;
    height: 550rpx;
    margin: auto;
    box-sizing: border-box;
}

.bg-circle {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    width: 770rpx;
    height: 770rpx;
    // 360度旋转
    // animation: rotate 10s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

.login-logo {
    width: 493rpx;
    height: 284rpx;
}
.login-form {
    // background: linear-gradient(to bottom, #d5f7d6 0%, #daf7da 5px, #def7e0 15px, #fff 20px, #fff 100%);
    background-color: #fff;
}
.login-bttom-bg {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    width: 687rpx;
    margin: auto;
    // 不能有事件
    pointer-events: none;
}
</style>
