/**
 * 短信业务模型
 *
 * @author EllisRan
 * @date 2018/4/17
 * @version
 */
const Request = require("request");
const BaseModel = require("../../common/base/base_model");

class SmsModel extends BaseModel {

    /**
     * 状态信息
     *
     * @var {object}
     */
    statusMsg = { 1:'发送成功', 2:'该手机号已注册', 3:'该手机号未注册', 0:'参数有误',
        4:'短信接口方出错', 5:'验证码添加到数据库出错', 6:'手机号更改到数据库出错',
        7:'验证码有误', 8:'sso账号不存在' };

    /**
     * 根据手机号和短信类型调用SSO短信接口获取信息
     *
     * @param {string} mobile
     * @param {int} type  短信用途: 1->未注册过sso手机或更换手机号; 2->找回密码或修改密码;
     * @return {int}  返回状态码
     */
    async sendSmsFromSSO(mobile, type) {
        let postData = {
            url: 'http://sso.smartcost.com.cn/building/api/smscode',
            form: {mobile: mobile, type: type},
            encoding: 'utf8'
        };
        return new Promise(function (resolve, reject) {
            try {
                // 请求接口
                Request.post(postData, function (err, postResponse, body) {
                    if (err) {
                        console.log('222');
                        throw '请求错误';
                    }
                    if (postResponse.statusCode !== 200) {
                        throw '通行证验证失败！';
                    }
                    resolve(body);
                });
            } catch (error) {
                reject([]);
            }
        });
    }

    /**
     * 根据手机号和短信调用SSO短信接口并更新手机号
     *
     * @param {string} ssoid
     * @param {string} mobile
     * @param {string} code
     * @return {int}  返回状态码
     */
    async checkCodeFromSSO(ssoid, mobile, code) {
        let postData = {
            url: 'http://sso.smartcost.com.cn/building/api/set/mobile',
            form: {ssoId: ssoid, mobile: mobile, code: code},
            encoding: 'utf8'
        };
        return new Promise(function (resolve, reject) {
            try {
                // 请求接口
                Request.post(postData, function (err, postResponse, body) {
                    if (err) {
                        console.log('333');
                        throw '请求错误';
                    }
                    if (postResponse.statusCode !== 200) {
                        throw '通行证验证失败！';
                    }
                    resolve(body);
                });
            } catch (error) {
                reject([]);
            }
        });
    }


    /**
     * 根据状态码获取反馈信息
     *
     * @param {string} status
     * @return {string}
     */
    async getStatusMsg(status) {
        return this.statusMsg[status];
    }
}

module.exports = SmsModel;