var zxy = require('zxy-comm');
var fs = require('fs');
var path = require('path');
var promise = require('bluebird');
var conf = require('./conf');
// exports.sendSMSCode = function () {
//     return new promise(function (resolve, reject) {
//         console.warn("ucpaas短信网关未成功初始化，请延迟调用");
//         reject();
//     });
// }
// exports.sendSMSNotify = function () {
//     return new promise(function (resolve, reject) {
//         console.warn("ucpaas短信网关未成功初始化，请延迟调用");
//         reject();
//     });
// }
var log = function (cellphone, content, templateId, send_status, gnway_uid, gnway_send_time) {
    var sql = "INSERT INTO zxy_ucpaas_sms_log(id,send_time,cellphone,content,templateId,send_status,gnway_uid,gnway_send_time)VALUES(UUID(),NOW(),"
        + "@cellphone,@content,@templateId,@send_status,@gnway_uid,@gnway_send_time);";
    zxy.app.m_mysql.run(sql, {
        cellphone: cellphone,
        content: content,
        templateId: templateId,
        send_status: send_status,
        gnway_uid: gnway_uid,
        gnway_send_time: gnway_send_time
    });
}
// setTimeout(function () {
// if (!zxy.app.m_mysql) {
//     console.warn("ucpaas短信网关启动失败，请先连接mysql数据库");
// }
// else {
exports.sendSMSCode = function (to, content) {
    return new promise(function (resolve, reject) {
        if (!zxy.app.m_verify.checkCellphone(to)) {
            return reject({ errcode: 1, errmsg: '手机号码格式不正确' });
        }
        var sql = "SELECT CASE WHEN COUNT(1) < @send_count THEN 1 ELSE 0 END `send` FROM zxy_ucpaas_sms_log WHERE cellphone = @cellphone AND (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(send_time))/60 < 1 AND templateId = '" + conf.sms.code_templateid + "';";
        zxy.app.m_mysql.run(sql, {
            send_count: conf && conf.confine ? conf.confine : 1,
            cellphone: to
        }).then(function (result) {
            if (result && result[0] && result[0].send) {
                var path = "/{SoftVersion}/Accounts/{accountSid}/Messages/templateSMS?sig=";
                path = path.replace("{SoftVersion}", conf.softversion).replace("{accountSid}", conf.accountsid);
                var time = new Date().Format('yyyyMMddhhmmss');
                var sig = zxy.app.m_cryptogram.md5(conf.accountsid + conf.authtoken + time).toUpperCase();
                path += sig;
                var Authorization = zxy.app.m_encode.base64Encode(conf.accountsid + ":" + time);
                var data = {
                    "templateSMS": {
                        "appId": conf.appid,
                        "templateId": conf.sms.code_templateid,
                        "to": to,
                        "param": content
                    }
                };
                zxy.app.m_request.postRequest('https', 'api.ucpaas.com', '443', path, data, {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json;charset=utf-8',
                    'Authorization': Authorization
                }, null, function (r) {
                    r = zxy.app.m_convert.jsonStrToJson(r);
                    if (r && r.resp && r.resp.respCode && r.resp.respCode == "000000") {
                        var smsId = r.resp.templateSMS.smsId;
                        var createDate = r.resp.templateSMS.createDate;
                        log(to, content, conf.sms.code_templateid, "000000", smsId, createDate);
                        resolve({ errcode: 0, errmsg: '发送成功' });
                    }
                    else {
                        log(to, content, conf.sms.code_templateid, (r && r.resp && r.resp.respCode ? r.resp.respCode : 3), "", "");
                        reject({ errcode: r && r.resp && r.resp.respCode ? r.resp.respCode : 3, errmsg: r && r.resp && r.resp.respMsg ? r.resp.respMsg : '参考http://docs.ucpaas.com/doku.php?id=rest_error' });
                    }
                });

            }
            else {
                return reject({ errcode: 2, errmsg: '发送超出上限或校验失败' });
            }
        }).catch(function (err) {
            reject(err);
        });
    });
};
exports.sendSMSNotify = function (to, content) {
    return new promise(function (resolve, reject) {
        if (!zxy.app.m_verify.checkCellphone(to)) {
            return reject({ errcode: 1, errmsg: '手机号码格式不正确' });
        }
        var path = "/{SoftVersion}/Accounts/{accountSid}/Messages/templateSMS?sig=";
        path = path.replace("{SoftVersion}", conf.softversion).replace("{accountSid}", conf.accountsid);
        var time = new Date().Format('yyyyMMddhhmmss');
        var sig = zxy.app.m_cryptogram.md5(conf.accountsid + conf.authtoken + time).toUpperCase();
        path += sig;
        var Authorization = zxy.app.m_encode.base64Encode(conf.accountsid + ":" + time);
        var data = {
            "templateSMS": {
                "appId": conf.appid,
                "templateId": conf.sms.notify_templateid,
                "to": to,
                "param": content
            }
        };
        zxy.app.m_request.postRequest('https', 'api.ucpaas.com', '443', path, data, {
            'Accept': 'application/json',
            'Content-Type': 'application/json;charset=utf-8',
            'Authorization': Authorization
        }, null, function (r) {
            r = zxy.app.m_convert.jsonStrToJson(r);
            if (r && r.resp && r.resp.respCode && r.resp.respCode == "000000") {
                var smsId = r.resp.templateSMS.smsId;
                var createDate = r.resp.templateSMS.createDate;
                log(to, content, conf.sms.notify_templateid, "000000", smsId, createDate);
                resolve({ errcode: 0, errmsg: '发送成功' });
            }
            else {
                log(to, content, conf.sms.notify_templateid, (r && r.resp && r.resp.respCode ? r.resp.respCode : 3), "", "");
                reject({ errcode: r && r.resp && r.resp.respCode ? r.resp.respCode : 3, errmsg: r && r.resp && r.resp.respMsg ? r.resp.respMsg : '参考http://docs.ucpaas.com/doku.php?id=rest_error' });
            }
        });
    });
};
    // }
// }, 0);