'use strict';

import Request from "request";

/**
 * 建筑短信发送相关接口
 *
 * @author CaiAoLin
 * @date 2018/1/25
 * @version
 */

const crypto = require('crypto');

class SMS {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        this.url = 'http://www.sendcloud.net/smsapi/send';
        this.smsUser = 'smartcost';
        this.smskey = 'kuGmqTt10n6vBXivhxXsAuG8aoCsQ1x6';
    }

    /**
     * 发送信息
     *
     * @param {String|Array} mobile - 发送的电话号码
     * @param {String} code - 验证码
     * @return {Boolean} - 发送结果
     */
    async send(mobile, code) {
        try {
            const formData = {
                smsUser: this.smsUser,
                templateId: 25595,
                msgType: 0,
                phone: mobile,
                vars: '{"%code%":'+ code +'}',
            };
            const signature = await this.getSignature(this.sortDict(formData), this.smskey);
            formData.signature = signature;

            let postData = {
                url: this.url,
                form: formData,
                encoding: 'utf8'
            };

            return new Promise(function (resolve, reject) {
                try {
                    // 请求接口
                    Request.post(postData, function (err, postResponse, body) {
                        if (err) {
                            throw '请求错误';
                        }
                        if (postResponse.statusCode !== 200) {
                            throw '短信发送失败！';
                        }
                        resolve(body);
                    });
                } catch (error) {
                    reject([]);
                }
            });
        } catch (error) {
           console.log(error);
        }
    }

    async sendLoginMsg(mobile, name, date, time, local, ip) {
        console.log(mobile, name, time, local, ip);
        try {
            const formData = {
                smsUser: this.smsUser,
                templateId: 27561,
                msgType: 0,
                phone: mobile,
                vars: '{"%name%": "' + name + '", "%date%": "' + date + '", "%time%": "' + time + '", "%local%": "' + local + '", "%IP%": "' + ip + '"}',
            };
            const signature = await this.getSignature(this.sortDict(formData), this.smskey);
            formData.signature = signature;

            let postData = {
                url: this.url,
                form: formData,
                encoding: 'utf8'
            };

            return new Promise(function (resolve, reject) {
                try {
                    // 请求接口
                    Request.post(postData, function (err, postResponse, body) {
                        if (err) {
                            throw '请求错误';
                        }
                        if (postResponse.statusCode !== 200) {
                            throw '短信发送失败！';
                        }
                        resolve(body);
                    });
                } catch (error) {
                    reject([]);
                }
            });
        } catch (error) {
            console.log(error);
        }
    }

    async sendProductMsg(mobile, status, name, product, deadline) {
        try {
            let templateId = 0;
            switch (status) {
                case 1: templateId = 746377;break;// 产品升级通知
                case 2: templateId = 746376;break;// 产品降级通知
                case 3: templateId = 746378;break;// 产品延期通知
            }
            const formData = {
                smsUser: this.smsUser,
                templateId: templateId,
                msgType: 0,
                phone: mobile,
            };
            formData.vars = '{"%name%": "' + name + '", "%product%": "' + product + '"' + (status !== 2 ? ', "%deadline%": "' + deadline + '"' : '') +'}';
            const signature = await this.getSignature(this.sortDict(formData), this.smskey);
            formData.signature = signature;

            let postData = {
                url: this.url,
                form: formData,
                encoding: 'utf8'
            };

            return new Promise(function (resolve, reject) {
                try {
                    // 请求接口
                    Request.post(postData, function (err, postResponse, body) {
                        if (err) {
                            throw '请求错误';
                        }
                        if (postResponse.statusCode !== 200) {
                            throw '短信发送失败！';
                        }
                        resolve(body);
                    });
                } catch (error) {
                    reject([]);
                }
            });
        } catch (error) {
            console.log(error);
        }
    }

    md5(data) {
        var str = data;
        return crypto.createHash("md5").update(str).digest("hex");
    }

    sortDict(dict){
        var dict2={},
            keys = Object.keys(dict).sort();
        for (var i = 0, n = keys.length, key; i < n; ++i) {
            key = keys[i];
            dict2[key] = dict[key];
        }
        return dict2;
    }

    async getSignature (sorted_param, smsKey) {
        var param_str = "";
        for(var key in sorted_param)
            param_str += (key + '=' + sorted_param[key] + '&')
        var param_str = smsKey + '&' + param_str + smsKey;
        var sign = this.md5(param_str);
        return sign.toUpperCase();
    }

    /**
     * 生成随机字符串
     *
     * @param {Number} length - 需要生成字符串的长度
     * @param {Number} type - 1为数字和字符 2为纯数字 3为纯字母
     * @return {String} - 返回生成结果
     */
    generateRandomString(length, type = 1) {
        length = parseInt(length);
        length = isNaN(length) ? 1 : length;
        let randSeed = [];
        let numberSeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
        let stringSeed = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
            'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

        switch (type) {
            case 1:
                randSeed = stringSeed.concat(numberSeed);
                stringSeed = numberSeed = null;
                break;
            case 2:
                randSeed = numberSeed;
                break;
            case 3:
                randSeed = stringSeed;
                break;
            default:
                break;
        }

        const seedLength = randSeed.length - 1;
        let result = '';
        for (let i = 0; i < length; i++) {
            const index = Math.ceil(Math.random() * seedLength);
            result += randSeed[index];
        }

        return result;
    }
}

module.exports = SMS;
