'use strict';

/**
 * sso相关接口
 *
 * @author CaiAoLin
 * @date 2017/11/15
 * @version
 */

// 加密类
const crypto = require('crypto');
class SSO {

    /**
     * 构造函数
     *
     * @param {Object} ctx - egg全局变量
     * @return {void}
     */
    constructor(ctx) {
        this.authUrl = 'http://sso.smartcost.com.cn/api/jzlogin';
        this.ctx = ctx;
        this.accountID = 0;
    }

    /**
     * SSO登录验证
     *
     * @param {String} username - cld用户名
     * @param {String} password - cld密码
     * @return {boolean} - 验证结果
     */
    async loginValid(username, password) {
        let result = false;
        try {
            if (username === '' || password === '') {
                throw '用户名或密码错误';
            }
            // 生成加密token
            const postData = {
                username,
                userpasswd: password,
            };

            const responseData = await this.ctx.helper.sendRequest(this.authUrl, postData);
            if (responseData.length <= 0 || typeof responseData === 'number') {
                throw '接口返回错误:' + responseData;
            }

            // 如果验证成功，则新增SSO数据到数据库
            const customerId = await this.ctx.service.customer.addSSOUser(responseData[0]);
            this.accountID = customerId;

            // 更新用户登录时间
            const updateData = {
                last_login: new Date().getTime() / 1000,
            };
            result = await this.ctx.service.customer.update(updateData, { email: responseData[0].useremail });
        } catch (error) {
            console.log('sso:' + error);
            result = false;
        }

        return result;
    }

    /**
     * 获取SSO用户数据
     *
     * @param {Number} ssoID - sso中的id
     * @return {String} - 返回json数据
     */
    async getSSOUserData(ssoID) {
        let result = {};
        try {
            result = ssoID;
        } catch (error) {
            result = {};
        }

        return result;
    }

}

module.exports = SSO;
