<template>
    <view class="login-container">
        <view class="lc-header">
            <view class="lh-logo"><image mode="aspectFit" src="/static/images/logo.png"></image></view>
            <view class="lh-name">欧轩智能场馆</view>
        </view>
        <view class="lc-form">
            <view class="lf-frame"><input placeholder="请输入品牌ID" v-model="formData.brand_id" /></view>
            <view class="lf-frame"><input placeholder="请输入账号" v-model="formData.account" /></view>
            <view class="lf-frame"><input placeholder="请输入密码" v-model="formData.password" password /></view>
        </view>

        <button 
            v-if="isProfile"
            class="lf-btn" 
            hover-class="hover-active" 
            @click="profileSubmit"
        >登录</button>
        <button 
            v-else
            class="lf-btn" 
            hover-class="hover-active" 
            open-type="getUserInfo"
            lang="zh_CN"
            @getuserinfo="submitBtn"
        >登录</button>
        
        <view class="lf-tip">提示：请联系管理员添加您为员工账号</view>
        <!-- <view class="lf-bot-btn" @click="toWebView">成为商家</view> -->
        <view class="lf-bot-btn" @click="toPartyLogin">商家注册</view>
		<!-- <view class="lf-bot-btn" @click="thirdPartyAuthor">test请求商家授权authorize</view> -->
		<!-- <view class="lf-bot-btn" @click="thirdPartyOpenTrial">test打开试用小程序</view> -->
		
		<!-- <view class="lf-bot-btn" @click="">
			<navigator url="plugin://myPlugin/miniprogram-thirdparty-plugin">
			小程序内注册/成为商家
			</navigator>
		</view> -->
		
    </view>
</template>

<script>
import { API } from '../../js/api';
import { servers } from '../../js/server';
import util from '../../utils/util';
// import wxplugin from '../../utils/wx_plugin';
const uniGetSetting = util.promisify(uni.getSetting);
const uniLogin = util.promisify(uni.login);
const APPID = uni.getAccountInfoSync().miniProgram.appId;

const MiniprogramThirdpartyPlugin = requirePlugin('miniprogram-thirdparty-plugin')
export default {
    computed: {
        isProfile: _=> util.isProfile(),
    },
    data(){
        return {
            formData: {
                brand_id: '',
                account: '',
                password: '',
            }
        }
    },
	onReady(){
		
		
		// 初始化
		MiniprogramThirdpartyPlugin.init(wx)
		

	},
    methods: {
        // 跳转到商家登录注册
        toPartyLogin(){
            util.routeTo(`/subpackage/party/pages/login/login`,'nT');
        },
		thirdPartyAuthor(){
			// 请求用户授权
			// let token = "iQhrBPQszUtqc-W59-gnfLTSL-OpZRCKoe89VKGBKvOTQ9BXeLc5q3F4a_Nl7Vpm"
			let token = "4sfXTSZZA-WXWx-cnC3MTDDn6PMc2v2xO6HtWOAYv5bjWQmuGo5DGHBoe1gZpTSZ"
			MiniprogramThirdpartyPlugin.authorize({
			  token: token, // 传入后台返回的create_token，通过【fastregisterbetaweapp】接口获得的authorize_url，该url中的create_token
			  success(res) {
			    // 授权成功
			    wx.showToast({
			      title: '授权成功',
			    })
			  },
			  fail(err) {
			    console.error(err)
			    // 授权失败或其他异常
			    wx.showToast({
			      title: '授权失败',
			    })
			  }
			})
		},
        requestFastRequest(){
            
        },
        getCreateToken(json){
                // 从json的data属性中获取authorize_url  
            const authorizeUrl = json.data.authorize_url;  
            // 使用URLSearchParams来解析URL中的查询参数  
            const params = new URLSearchParams(authorizeUrl.split('?')[1]);  
            // 获取create_token的值  
            const createToken = params.get('create_token');  
            // 返回create_token  
            return createToken;  
        },
		thirdPartyOpenTrial(){
			// 请求打开试用小程序
			MiniprogramThirdpartyPlugin.openTrial({
			  appid: 'appid', // 试用小程序的appid
			  platformAppID: 'platform_appid', // 平台的appid
			  fail() {
			    // 其他异常
			  }
			})
		},
        profileSubmit(){
            uni.getUserProfile({
                lang: 'zh_CN', desc: '用户绑定',
                success: res => {
                    this.submitBtn({detail: {...res}});
                },
                fail: function(err) {
                    util.showNone('获取用户信息失败！请重试');
                    console.warn('getUserProfile Err', err)
                }
            })
        },
        async submitBtn(userRes){
            try{
                util.showLoad();
                if(!userRes.detail.userInfo){
                    util.hideLoad();
                    return util.showNone('获取用户信息失败！请稍后重试');
                }

                let loginRes = await uniLogin();

                if(!loginRes.code){
                    util.hideLoad();
                    return util.showNone('获取登陆凭证失败！稍后重试');
                }
                let userInfo = userRes.detail || {};
                console.log(userRes)
                let { formData } = this;
                servers.post({
                    url: API.WechatMiniApplogin,
                    data: {
                        appid: APPID,
                        code: loginRes.code,
                        encryptedData: userInfo.encryptedData,
                        // is_details: 1,
                        // 后端解密错误，直接传用户信息
                        user_info: userInfo.userInfo,
                        user_raw_data: userInfo.rawData,
                        ...userInfo.userInfo,
                        username: formData.account,
                        password: formData.password,
                        brand_id: formData.brand_id,
                    },
                    isDefaultGet: false,
                })
                .then(res=>{
                    util.hideLoad();
                    let _data = res.data || {};
                    if(_data.code == 0){
                        util.showNone(_data.message || '操作成功！');
                        // 20230829 新增平台角色判断跳过首页检查绑定接口
                        // 修改接口返回数据
                        uni.setStorageSync('token',_data?.data?.token || '');
                        setTimeout(_=>{
                            util.routeTo(`/pages/index/index?role=${_data?.data?.role}`, 'rL');
                        }, 1200);
                    }else{
                        util.showNone(_data.message || '操作失败！');
                    }
                    
                })
                .catch(util.hideLoad)
            }catch(err){
                util.hideLoad();
                console.warn('login err', err);
            }
        },
        toWebView(){
            util.routeTo(`/pages/web_view/web_view`,'rL');
        }
    },
}

</script>

<style lang="scss">
    @import '~style/public.scss';
    page{
        background-color: #fff;
    }
    .login-container{
        padding-bottom: 0;
        padding-bottom: calc( 0 + constant(safe-area-inset-bottom)); /* 兼容 iOS < 11.2 */
        padding-bottom: calc( 0 + env(safe-area-inset-bottom)); /* 兼容 iOS >= 11.2 */
        .lc-header{
            position: relative;
            padding-top: 70upx;
            margin-bottom: 46upx;
            height: 390upx;
            width: 100%;
            overflow: hidden;
            &::before{
                content: '';
                display: block;
                position: absolute;
                left: 50%;
                bottom: 0upx;
                z-index: -1;
                transform: translateX(-50%);
                background-color: $themeColor;
                width: 3000upx;
                height: 3000upx;
                border-radius: 50%;
            }
            .lh-logo{
                margin: 0 auto 20upx;
                width: 170upx;
                height: 170upx;
                border-radius: 50%;
                background-color: #fff;
                overflow: hidden;
                >image{
                    width: 100%;
                    height: 100%;
                }
            }
            .lh-name{
                padding: 0 24upx;
                text-align: center;
                line-height: 50upx;
                font-weight: 500;
                font-size: 36upx;                
                color: #fff;
            }
        }
        .lc-form{
            margin-bottom: 80upx;
            .lf-frame{
                margin: 0 auto 24upx;
                padding: 0 20upx;
                width: 610upx;
                height: 108upx;
                border: 2upx solid #dddddd;
                border-radius: 54upx;
                >input{
                    width: 100%;
                    height: 100%;
                    text-align: center;
                    font-size: 32upx;
                    color: #1A1A1A;
                }
                &:last-child{
                    margin-bottom: 0;
                }
            }
        }
        .lf-btn{
            margin-bottom: 16upx;
            width: 610upx;
            height: 108upx;
            border-radius: 54upx;
            border: none;
            background-color: $themeColor;
            font-size: 36upx;
            line-height: 108upx;
            color: #fff;
        }
        .lf-tip{
            margin-bottom: 120upx;
            text-align: center;
            line-height: 40upx;
            text-align: center;
            font-size: 28upx;
            color: #9A9A9D;
        }
        .lf-bot-btn{
            margin-bottom: 20upx;
            line-height: 40upx;
            text-align: center;
            font-size: 28upx;
            color: $themeColor;
            text-decoration: underline;
        }
    }
</style>