
const sms = require("ali-sms");
const SMSAccessKeyID     = process.env.ALI_SMS_ACCESSKEYID || "LTAI5tETwA37KgHfDo5p2Ej6";
const SMSAccessKeySecret = process.env.ALI_SMS_ACCESSKEYSECRET || "EBDQEchETlNcEYzE8zYb1zl4gBImrJ";

/**
 * @desc
 curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' http://8.140.98.43/parse/functions/aliSmsSend
 curl -X POST -H "Content-Type: application/json" -H 'X-Parse-Application-Id: edu-textbook' -d '{ "mobileList": ["18607007073"],"templateCode":"SMS_468995773","params":{},"signName":"普通高等教育教材网" }' http://127.0.0.1:61337/parse/functions/aliSmsSend
 * @returns
 成功
 {"result":"{\"Message\":\"OK\",\"RequestId\":\"41DDC6F4-A8B8-55A3-95E7-AD06D3F0E94F\",\"Code\":\"OK\",\"BizId\":\"261804722010619993^0\"}"}
 失败
 {"result":"{\"Message\":\"手机号码格式错误\",\"RequestId\":\"63C4A4DB-B337-5630-8E00-51535C7377D7\",\"Code\":\"isv.MOBILE_NUMBER_ILLEGAL\"}"}

 */
 export function defineAliSMSSend(){
    // function defineAuthingLogin(){
        Parse.Cloud.define("aliSmsSend", async (request) => {
            let mobileList = request.params.mobileList;
            let signName = request.params.signName;
            let params = request.params.params;
            let templateCode = request.params.templateCode;
            
            let result = await sendAliyunSMS({
                signName:signName,
                mobileList:mobileList,
                params:params,
                templateCode:templateCode
                
            })
            return result
        },{
            fields : {
                mobileList:{
                    required:true
                },
                params:{
                    required:true
                },
                signName:{
                    required:true
                },
                templateCode:{
                    required:true
                },
            }
        });
}


/**
 * @desc
    手机号解绑验证码 SMS_469065757
    手机号修改验证码 SMS_469055726
    手机号绑定验证码 SMS_468890757
    密码重置验证码 SMS_468915747
    账号认证失败通知 SMS_468995773
    账号认证成功通知 SMS_468870790
    账号注册通知 SMS_469060724
 */
async function sendAliyunSMS(options){
    return new Promise(resolve=>{
        const config = {
            accessKeyID       : SMSAccessKeyID,
            accessKeySecret   : SMSAccessKeySecret,
            paramString       : options?.params,
            recNum            : options?.mobileList,
            signName          : options?.signName,
            templateCode      : options?.templateCode,
        };
        sms(config, (err, body) => {
            console.log(err, body);
            resolve(body||err)
        });
    })

}

module.exports.sendAliyunSMS = sendAliyunSMS()