<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { reactive, ref } from 'vue';
import { showLoad, hideLoad, showModal, showNone, routeTo } from "@/utils/polish";
import { douyinMiniAppBaseAuth, douyinMiniAppLoginAndSync } from "../api";

let loginRes = ref(null);
let dyPhoneAuthorize = ref(false);
const APPID = tt.getEnvInfoSync()?.microapp?.appId ?? '';
const optionsQuery = ref(null)
onLoad(() => {
    dysilentLogin();
    console.log(process.env.NODE_ENV)
});

// 抖音获取登陆code， 手机解析需要获取code在点击之前
let dyGetLoginCode = async function(){
    try{
        let _loginRes = await uni.login();
        if(!_loginRes.code)return showModal({ content: '获取登陆凭证失败！请稍后重试' });
        return loginRes.value = _loginRes;
    }catch(err){
        return showModal({ content: '获取登陆凭证失败！请稍后重试' })
    }
}

// 静默登陆，审核多按钮登陆不过
// 判断是否需要需要绑定手机，直接手机号登陆
const dysilentLogin = async function(){
    try{
        let _loginRes = await dyGetLoginCode();
        let _bData = await douyinMiniAppBaseAuth({
            data: { code: _loginRes.code, appid: APPID  },
            catch: true,
            errorModal: false
        })
        .catch(err=>{
            //  如果返回11005 则是用户从未授权过
            if(err?.data?.code === 11005)return err;
            return Promise.reject(err);
        })
        dyCheckPhoneStatus(_bData, true);
    }catch(err){
        hideLoad();
        console.warn('silentLogin err --->', err);
    }
}


// 抖音检查手机绑定状态
let dyCheckPhoneStatus = async function(_bData, isSilent = false){
    if(_bData.data.code == 0){
        let _data = _bData.data.data;
        if(_data?.user?.extension?.is_auth_mobile === false){ // 手机登陆
            let _codeInfo = await dyGetLoginCode();
            if(_codeInfo&&_codeInfo.code){
                dyPhoneAuthorize.value = true;
                !isSilent&&showNone('未绑定手机，请用手机号登陆！');
            }
            return;
        }
        // 成功后登陆操作
        console.log('成功后登陆操作')
        // if(_data?.token&&!isSilent)return this.successOperate(_bData);
    }else if(_bData.data.code == 11005){ // 手机登陆
        let _codeInfo = await dyGetLoginCode();
        if(_codeInfo&&_codeInfo.code){
            dyPhoneAuthorize.value = true;
            !isSilent&&showNone('未授权，请用手机号登陆！');
        }
    }else{
        !isSilent&&showNone(_bData.data.message || '登陆失败！');
    }
}

// 抖音获取手机号
async function douyinGetPhoneNumberHandler(e){
    console.log('douyinGetPhoneNumberHandler', e);
    let _detail = e.detail || {};
    if(!_detail?.encryptedData || !_detail?.iv){
        return showModal({
            content: _detail?.errMsg ?? '授权手机失败，请重新操作',
            showCancel: true,
            success: mRes => {
                if(mRes.confirm){
                    // 调试
                    if(process.env.NODE_ENV === 'development'){
                        showModal({
                            content: '调试登录',
                            showCancel: true,
                            success(debugRes){
                                if(debugRes?.confirm)debugLogin();
                            }
                        })
                    }

                }
                if(mRes.cancel){ showNone('已取消登录！'); }
            }
        })
    }
    douyinLoginReq({ phoneDetail: _detail });
}


function debugLogin(){
    douyinMiniAppLoginAndSync({ data: {
        code: loginRes?.value?.code ?? '',
        appid: APPID,
        version: 'dev',
        dev_data: { phoneNumber: 15521015328 }
    } })
    .then(res=>{
        successOperate(res);
    })
}


// 抖音后台登陆
function douyinLoginReq({ phoneDetail = null, }){
    let _query = {
        appid: APPID ?? '',
        code: loginRes?.value?.code ?? '',
    };
    if(phoneDetail){
        _query = {
            ..._query,
            encryptedData: phoneDetail?.encryptedData ?? '',
            iv: phoneDetail?.iv ?? '',
        }
    }
    douyinMiniAppLoginAndSync({ data: _query, catch: true })
    .then(res=>{
        successOperate(res);
    })
    .catch(err=>{
        setTimeout(_=>dyGetLoginCode(), 1000);
    })
}

// 获取token 成功&缓存查个人信息
function successOperate(res){
    console.log(res);
    showNone(res?.message || '登陆成功！');
    let _data = res?.data ?? {};
    uni.setStorageSync('token',_data?.token ?? '');
    setTimeout(routeOperate, 1200);
}

// 授权成功后路由
function routeOperate(){
    let _pageLs = getCurrentPages();
    let _opts = optionsQuery?.value ?? {}
    if(+_opts?.type === 2 &&_opts?.path){
        let _path = decodeURIComponent(_opts?.path);
        // getCurrentPages的微信小程序二维码的secne值会encodeURIComponent两次
        return routeTo(decodeURIComponent(_path), 'rT');
    }
    if(+_opts?.type === 1&&_pageLs.length > 1)return routeTo();
    if(_pageLs.length <= 1)return routeTo('/pages/index/index', 'sT');
    routeTo();
}
</script>

<template>
    <view class="authorize-index">
        <view class="ac-tit">您还未登录</view>
        <view class="ac-tip">请先登录再进行操作</view>
        <image class="ac-img" mode="aspectFit" src="@/subpackage/authorize/static/images/authorize.png"></image>
        <view class="ac-btns">
            <button v-if="dyPhoneAuthorize" plain  class="ab-btn" open-type="getPhoneNumber" @getphonenumber="douyinGetPhoneNumberHandler">抖音手机号授权快捷登录</button>
            <button v-else plain class="ab-btn" >抖音用户信息授权登录</button>
            <button plain class="ab-btn" hover-class="hover-active" @click="cancel">暂不登录</button>
        </view>
    </view>
</template>

<style lang="scss" scoped>
.authorize-index{
    padding-top: 124upx;
    .ac-tit{
        text-align: center;
        @include flcw(32upx, 44upx, #333, 500);
    }
    .ac-tip{
        margin-top: 20upx;
        text-align: center;
        @include flcw(28upx, 40upx, #9A9A9D);
    }
    .ac-img{
        display: block;
        margin: 2upx auto 0;
        width: 578upx;
        height: 578upx;
    }
    .ac-btns{
        margin-top: 62upx;
        width: 100%;
        padding: 0 20upx;
        .ab-btn{
            @include clearBtn;
            margin-top: 24upx;
            text-align: center;
            border: 2upx solid $mColor;
            border-radius: 44upx;
            background-color: $mColor;
            @include flcw(28up, 84upx, #fff);
            &+.ab-btn{
                border-color: #C9C9CB;
                color: #9a9a9d;
                background-color: transparent;
            }
        }
    }
}
</style>