const request = require('./WXHttpRequest.js');
const url = require('./const.js');
const util = require('./util.js');
const httpRequestApi = require('./APIClient');

const HOST = url.baseApi;


function genAPIUrl(action) {
    return HOST + action;
}

// 登录
function wxLogin(successcallback, failcallback) {
    wx.showToast({
        title: '登录中...',
        icon: 'loading',
        duration: 1500,
        mask: true
    })
    wx.login({
        success: function (res) {
            if (res.code) {
                // 获取openid
                console.log('openId', res.code)
                let url = genAPIUrl('wx/user/openId')
                let data = {
                    code: res.code
                }
                return request.getInstance().url(url).data(data).send().success(successcallback).fail(failcallback);
            } else {
                console.log('获取用户登录态失败！' + res.errMsg)
            }
        }
    })
}

function userLoginRecord(uid) {
    if (wx.getStorageSync('uid')) {
        console.log('调用方法')
        let url = genAPIUrl('wx/loginLog');
        return request.getInstance().header({
            uid: wx.getStorageSync('uid')
        }).method('POST').url(url).send().success(() => {}).fail(() => {});
    }

}
//登录
function getLoginSchedule(sessionKey, openId, successcallback, failcallback) {
    wx.getSetting({
        success: function (res) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称
            wx.getUserInfo({
                withCredentials: true,
                success: function (res) {
                    let url = genAPIUrl('wx/user/loginRegist');
                    let appLaunch = wx.getLaunchOptionsSync();
                    let userSourseType = '';
                    console.log(appLaunch.scene)
                    switch (appLaunch.scene) {
                        case 1020:
                            userSourseType = 'profile';
                            break;
                        case 1058:
                            userSourseType = 'article';
                            break;
                        default:
                            userSourseType = wx.getStorageSync('userSourseType');
                            break;
                    }
                    const userData = {
                        encryptedData: res.encryptedData,
                        sessionKey: sessionKey,
                        iv: res.iv,
                        sourceType: userSourseType
                    }
                    request.getInstance().url(url).header({
                        "content-type": "application/x-www-form-urlencoded; charset=UTF-8"
                    }).data(userData).method('POST').send().success(res => {
                        wx.hideToast()
                        wx.showToast({
                            title: '登录成功',
                            icon: 'success',
                            duration: 1500,
                            mask: true
                        })
                        wx.setStorageSync('uid', res.data.data.data.uid)
                        wx.setStorageSync('user', res.data.data.data)
                        userLoginRecord()
                        successcallback(res)

                    });
                },
                fail: function (res) {
                    failcallback(res)
                }
            })
        }
    })

}

// 获取原来的 openid 和 session_key
function getOpenidSessionKey(successcallback, failcallback) {
    // if (wx.getStorageSync('user')) {
    //     successcallback(
    //         wx.getStorageSync('user'),
    //         //分享小程序按钮
    //         wx.showShareMenu({
    //             withShareTicket: true
    //         })
    //     );
    //     return;
    // }
    wxLogin(function (res) {
        if (res.data.code == 200) {
            let sessionKey = res.data.data.session_key;
            let openId = res.data.data.openid;
            getLoginSchedule(sessionKey, openId, successcallback, failcallback);
        }

    }, function (res) {
        failcallback(res);
    })
}



module.exports = {
    getOpenidSessionKey
}