var system = require("../../../system");
const CtlBase = require("../../ctl.base");
const crypto = require("crypto");
const settings = require("./../../../../config/settings");

/**
 *  @module agriculture
 *  @class messageCtl
 *  消息ctl
 */

class messageCtl extends CtlBase {
    constructor() {
        super("agriculture", CtlBase.getServiceName(messageCtl));
        this.servicebillCtl = system.getObject("service.agriculture.servicebillCtl");
    }

    async message(msg) {
        const key = settings.ydzKey().msgSecret;
        const plaintextMsg = this.decryptMessage(key, msg.encryptMsg);
        console.log('-----------------------msg--------------------');
        console.log(plaintextMsg);
        switch (plaintextMsg.msgType) {
            case "CREATE_ACCOUNTING": //新建会计
                await this.servicebillCtl.create(plaintextMsg);
                break;
            case "APP_TICKET": // 应用票据
                await this.service.tempMsgProcessing(plaintextMsg.msgType, plaintextMsg, 30 * 60);
                break;
            case "TEMP_AUTH_CODE": //企业临时授权码
                await this.service.tempMsgProcessing(plaintextMsg.msgType, plaintextMsg);
        }
        return { "result": "success" };
    };
    /**
     * 解密消息内容
     * @param {string} key 16位密钥
     * @param {string} msgContent 加密串儿
     * @return {object} decryptMessage
     */
    decryptMessage(key, msgContent) {
        var iv = "";
        var clearEncoding = 'utf8';
        var cipherEncoding = 'base64';
        var cipherChunks = [];

        var decipher = crypto.createDecipheriv('aes-128-ecb', key, iv);
        decipher.setAutoPadding(true);

        cipherChunks.push(decipher.update(msgContent, cipherEncoding, clearEncoding));
        cipherChunks.push(decipher.final(clearEncoding));

        const decryptMessage = JSON.parse(cipherChunks.join(''));
        return decryptMessage;
    }
}
module.exports = messageCtl;