"use strict";
var ApiRequest = require("../libs/ApiRequest");
var async = require("async");
var config = require(__config_path + "/config");
var _ = require("lodash");
var request = require("request");
var numeral = require("numeral");
var validator = require("validator");
var moment = require("moment");
var lstDocuments = require("../resources/document.json")
var seoConfig = require("../resources/seo.json");
var Order = require("../models/Order");

// trang chu 
exports.index = function(req, res, next) {
    let user = 'mobile';
    let pass = '123456';

    request.post( {
        headers: {
            'Content-Type': 'application/json',
            'X-TENANT-ID': 'macca_tenant_1',
            'Authorization': 'Basic bW9iaWxlOjEyMzQ1Ng=='
        },
        url: 'https://macca-test.viviet.vn/api/macca/auth/oauth/token',
        form: {
            grant_type: "password",
            username: "huyenvtt",
            password: "123456"
        }
    }, function(err,data) {
        // console.log(data.body);
        renderPage(req, res, "frontend/index", {

        });
    });

    
    // if (req.subDomain.selfDomain && !req.subDomain.having) {
    //     async.parallel(
    //         [
    //             cb => {
    //                 ApiRequest.get("Front/LstPrice", (err, res) => {
    //                     return cb(null, res);
    //                 });
    //             },
    //             cb => {
    //                 ApiRequest.get("Front/LstCustomer", (err, res) => {
    //                     return cb(null, res);
    //                 });
    //             },
    //             cb => {
    //                 ApiRequest.get("Front/LstBlog", (err, res) => {
    //                     return cb(null, res);
    //                 });
    //             }

    //         ],
    //         (err, result) => {
    //             if (err) return renderPage(req, res, "404");

    //             let lstPrice = result[0];
    //             let lstCustomer = result[1];
    //             let lstBlog = result[2];
    //             if (lstBlog && lstBlog.length && lstBlog.length > 4) {
    //                 lstBlog = lstBlog.splice(0, 4);
    //             }
    //             // không có subdomain, render trang index
    //             renderPage(req, res, "frontend/index", {
    //                 hostname: req.hostname,
    //                 prices: lstPrice,
    //                 survey: lstCustomer,
    //                 top3news: lstBlog,
    //                 titleActive: 'trang-chu'
    //             });
    //         }
    //     );
    // } else {
    //     return next();
    // }
};

// bang gia 
exports.pricePage = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstPrice", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");
                let lstPrice = result[0];
                renderPage(req, res, "frontend/pages/price-page", {
                    prices: lstPrice,
                    titleActive: "bang-gia"
                });
            }
        );
    } else {
        return next();
    }
};

// van ban phap luat 
exports.document = function(req, res, next) {
    // Set page size
    let pageSize = 10;
    // Get page
    let page = req.query.page ? parseInt(req.query.page) : 1;
    // tong so ban ghi
    let totalRecords = lstDocuments.length;
    // so trang
    let totalPage = Math.ceil(totalRecords / pageSize);
    // data view
    let totalViews = [];
    let lstDocClone = [...lstDocuments];
    totalViews = lstDocClone.splice((page - 1) * pageSize, pageSize);
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        // co subdomain, next do dynamic
        renderPage(req, res, "frontend/pages/document", {
            document: totalViews,
            totalPage: totalPage,
            titleActive: "van-ban"
        });
    }
    else {
        return next();
    };
};

// get dang ky package
exports.register = function(req, res, next) {
    let check = req.query.package;
    let email = req.query.email;
    let ma_daily = req.query.dl;

    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstPrice", (err, res) => {
                        return cb(null, res);
                    });
                },
                cb => {
                    ApiRequest.get("Front/LstTinh", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");

                let lstPrice = result[0];
                let pack_price = 0;
                let pack_price_init = 0;
                let pack_sl = 0;
                let pack_name = '';
                for (let i = 0; i < lstPrice.length; i++) {
                    if (lstPrice[i].dmhanghoa_id === check) {
                        let price = lstPrice[i].don_gia.replace(".", "");
                        price = price.replace(".", "");
                        price = price.replace(".", "");
                        price = parseInt(price);
                        pack_price = price;
                        let price_init = lstPrice[i].phi_khoi_tao.replace(".", "");
                        price_init = price_init.replace(".", "");
                        price_init = price_init.replace(".", "");
                        price_init = parseInt(price_init);
                        pack_price_init = price_init;
                        let so_luong = lstPrice[i].so_luong_hoa_don.replace(".", "");
                        so_luong = so_luong.replace(".", "");
                        pack_sl = so_luong;
                        pack_name = lstPrice[i].ten_hang_hoa;
                    }
                }

                let lstTinh = result[1];
                if (ma_daily && ma_daily.length > 0) {
                    checkDL(ma_daily, true).then((data) => {
                        if (data && data.ma_daily) {
                            renderPage(req, res, "frontend/register", {
                                isDaily: true,
                                ma_daily: data.ma_daily,
                                prices: lstPrice,
                                provinces: lstTinh,
                                check: check,
                                pack_price: pack_price,
                                pack_price_init: pack_price_init,
                                pack_sl: pack_sl,
                                pack_name: pack_name,
                                email: email,
                                titleActive: "bang-gia"
                            })
                        } else {
                            renderPage(req, res, "frontend/register", {
                                isDaily: false,
                                prices: lstPrice,
                                provinces: lstTinh,
                                check: check,
                                pack_price: pack_price,
                                pack_price_init: pack_price_init,
                                pack_sl: pack_sl,
                                pack_name: pack_name,
                                email: email,
                                titleActive: "bang-gia"
                            })
                        }
                    });
                }
                else {
                    renderPage(req, res, "frontend/register", {
                        isDaily: false,
                        prices: lstPrice,
                        provinces: lstTinh,
                        check: check,
                        pack_price: pack_price,
                        pack_price_init: pack_price_init,
                        pack_sl: pack_sl,
                        pack_name: pack_name,
                        email: email,
                        titleActive: "bang-gia"
                    })
                }
            }
        );
    } else {
        return next();
    }
};

// get dang ky lam dai ly
exports.registerAgency = function(req, res, next) {
    // co subdomain
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstTinh", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");
                let lstCountry = result[0];
                renderPage(req, res, "frontend/registerAgency", {
                    provinces: lstCountry,
                    titleActive: 'dai-ly'
                });
            }
        );
    } else {
        return next();
    }

};

// register: post
exports.registerUse = function(req, res) {
    var data_new = req.body.data;
    if (data_new && data_new.code && data_new.code.length > 0) {
        checkDL(data_new.code, true).then((res3) => {
            let request_data = {
                editmode: 1,
                data: [
                    {
                        dmserver_id: config.server_id,
                        user_new: 'Online',
                        date_new: null,
                        trang_thai_tk: 1,
                        kd_insert: 1,
                        lan_gia_han: null,
                        ten_dvcs: null,
                        dia_chi: data_new.address,
                        server_name: null,
                        hh_ctv_dl: null,
                        pt_nguoigt: null,
                        da_thu_tien_hd: null,
                        da_thu_ho_so: null,
                        ngay_hop_dong: null,
                        id: null,
                        index: null,
                        dmkh_id: null,
                        loai_kh: "Mới",
                        ms_thue: data_new.taxCode,
                        ten_kh: data_new.dk_unit,
                        diachi_lh: data_new.address,
                        co_quan_thue: null,
                        tinh_thanh: data_new.location.city,
                        nguoi_dai_dien: data_new.dk_name,
                        chuc_vu: data_new.title,
                        sdt: data_new.dk_mobile,
                        email: (data_new.dk_email && data_new.dk_email !== undefined) ? data_new.dk_email : "",
                        website: "",
                        stk: "",
                        ngan_hang: "",
                        nguoi_lien_he: data_new.name,
                        sdt_nguoi_lien_he: (data_new.xhd_mobile && data_new.xhd_mobile !== undefined) ? data_new.xhd_mobile : "",
                        email_nguoi_lien_he: (data_new.xhd_email && data_new.xhd_email !== undefined) ? data_new.xhd_email : "",
                        so_luong_hd: data_new.so_luong_hoa_don,
                        choose: 0,
                        ma_dvcs: (res3 && res3.ma_daily) ? res3.ma_daily : 'VP',
                        ghi_chu: "",
                        ngay_kich_hoat: "",
                        trang_thai_db: "Đã tạo DB",
                        end_user: "",
                        is_trial: true,
                        date_expried: moment()
                            .add(7, "days")
                            .format("MM/DD/YYYY")
                    }
                ]
            };
            // console.log('data',request_data);
            request.post(
                {
                    url: "https://www.google.com/recaptcha/api/siteverify",
                    form: {
                        secret: "6LfP1MIUAAAAAGX6fJsmwC_pWPcCsOy73QLl80CW",
                        response: req.body["g-recaptcha-response"],
                        ip: req.ip
                    }
                },
                function(err, httpResponse, data) {
                    var errorMes = "Đã có lỗi xảy ra. Vui lòng thử lại.";
                    if (!data) {
                        return res.status(400).send(errorMes);
                    }
                    var body = JSON.parse(data);
                    if (body["success"] === true) {
                        if (data_new.payment && data_new.payment === 'after') {
                            // call api to register user
                            ApiRequest.post("Front/RegisterAutoDmkh", request_data, function(
                                err,
                                response
                            ) {
                                if (response && response.error) {
                                    res.status(400).send(response.error);
                                } else {
                                    if (data_new.taxCode && data_new.taxCode.indexOf('-') > -1) {
                                        data_new.taxCode = data_new.taxCode.replace('-', '');
                                    }
                                    req.session.register_info = {
                                        company: data_new.dk_unit,
                                        link: "https://" + data_new.taxCode + ".ahoadon.com"
                                    };
                                    sendMailTrial({
                                        company: data_new.dk_unit,
                                        taxCode: data_new.taxCode,
                                        address: data_new.address,
                                        contact: data_new.name,
                                        email: data_new.dk_email,
                                        mobile: data_new.dk_mobile,
                                        address: data_new.address,
                                        address: data_new.address
                                    }, () => {
                                        res.status(200).send();
                                    });
                                }
                            });
                        } else {
                            let newOrder = new Order();
                            newOrder.dmserver_id = config.server_id;
                            newOrder.user_new = 'Online';
                            newOrder.date_new = null;
                            newOrder.trang_thai_tk = 1;
                            newOrder.kd_insert = 1;
                            newOrder.lan_gia_han = null;
                            newOrder.ten_dvcs = null;
                            newOrder.dia_chi = data_new.address;
                            newOrder.server_name = null;
                            newOrder.hh_ctv_dl = null;
                            newOrder.pt_nguoigt = null;
                            newOrder.da_thu_tien_hd = null;
                            newOrder.da_thu_ho_so = null;
                            newOrder.ngay_hop_dong = null;
                            newOrder.id = null;
                            newOrder.index = null;
                            newOrder.dmkh_id = null;
                            newOrder.loai_kh = "Mới";
                            newOrder.ms_thue = data_new.taxCode;
                            newOrder.ten_kh = data_new.dk_unit;
                            newOrder.diachi_lh = data_new.address;
                            newOrder.tinh_thanh = data_new.location.city;
                            newOrder.nguoi_dai_dien = data_new.dk_name;
                            newOrder.co_quan_thue = null;
                            newOrder.chuc_vu = data_new.title;
                            newOrder.sdt = data_new.dk_mobile;
                            newOrder.email = data_new.dk_email;
                            newOrder.website = "";
                            newOrder.stk = "";
                            newOrder.ngan_hang = "";
                            newOrder.nguoi_lien_he = data_new.name;
                            newOrder.sdt_nguoi_lien_he = data_new.xhd_mobile;
                            newOrder.email_nguoi_lien_he = data_new.xhd_email;
                            newOrder.so_luong_hd = data_new.so_luong_hoa_don;
                            newOrder.choose = 0;
                            newOrder.ma_dvcs = (res3 && res3.ma_daily) ? res3.ma_daily : 'VP';
                            newOrder.ghi_chu = "";
                            newOrder.ngay_kich_hoat = "";
                            newOrder.trang_thai_db = "Đã tạo DB";
                            newOrder.end_user = "";
                            newOrder.is_trial = true;
                            newOrder.date_expried = moment()
                                .add(7, "days")
                                .format("MM/DD/YYYY");
                            newOrder.status = 0;
                            newOrder.order_name = data_new.ten_goi;
                            newOrder.phi_khoi_tao = data_new.phi_khoi_tao;
                            newOrder.gia_goi = data_new.gia_goi;
                            newOrder.save((err4, data4) => {
                                if (data_new.taxCode && data_new.taxCode.indexOf('-') > -1) {
                                    data_new.taxCode = data_new.taxCode.replace('-', '');
                                }
                                req.session.register_info = {
                                    company: data_new.dk_unit,
                                    link: "https://" + data_new.taxCode + ".ahoadon.com"
                                };

                                res.status(200).send();
                            });
                        }
                    } else {
                        if (body["error-codes"]) {
                            switch (body["error-codes"][0]) {
                                case "missing-input-response":
                                    {
                                        errorMes = "Bạn chưa thực hiện xác thực.";
                                    }
                                    break;
                                case "missing-input-secret":
                                    {
                                        errorMes = "The secret parameter is missing.";
                                    }
                                    break;
                                case "invalid-input-secret":
                                    {
                                        errorMes = "The secret parameter is invalid or malformed.";
                                    }
                                    break;
                                case "invalid-input-response":
                                    {
                                        errorMes = "Mã xác thực không hợp lệ.";
                                    }
                                    break;
                            }
                        }
                    }
                });
        });
    } else {
        let request_data = {
            editmode: 1,
            data: [
                {
                    dmserver_id: config.server_id,
                    user_new: 'Online',
                    date_new: null,
                    trang_thai_tk: 1,
                    kd_insert: 1,
                    lan_gia_han: null,
                    ten_dvcs: null,
                    dia_chi: data_new.address,
                    server_name: null,
                    hh_ctv_dl: null,
                    pt_nguoigt: null,
                    da_thu_tien_hd: null,
                    da_thu_ho_so: null,
                    ngay_hop_dong: null,
                    id: null,
                    index: null,
                    dmkh_id: null,
                    loai_kh: "Mới",
                    ms_thue: data_new.taxCode,
                    ten_kh: data_new.dk_unit,
                    diachi_lh: data_new.address,
                    tinh_thanh: data_new.location.city,
                    nguoi_dai_dien: data_new.dk_name,
                    co_quan_thue: null,
                    chuc_vu: data_new.title,
                    sdt: data_new.dk_mobile,
                    email: data_new.dk_email,
                    website: "",
                    stk: "",
                    ngan_hang: "",
                    nguoi_lien_he: data_new.name,
                    sdt_nguoi_lien_he: data_new.xhd_mobile,
                    email_nguoi_lien_he: data_new.xhd_email,
                    so_luong_hd: data_new.so_luong_hoa_don,
                    choose: 0,
                    ma_dvcs: "VP",
                    ghi_chu: "",
                    ngay_kich_hoat: "",
                    trang_thai_db: "Đã tạo DB",
                    end_user: "",
                    is_trial: true,
                    date_expried: moment()
                        .add(7, "days")
                        .format("MM/DD/YYYY")
                }
            ]
        };
        request.post(
            {
                url: "https://www.google.com/recaptcha/api/siteverify",
                form: {
                    secret: "6LfP1MIUAAAAAGX6fJsmwC_pWPcCsOy73QLl80CW",
                    response: req.body["g-recaptcha-response"],
                    ip: req.ip
                }
            },
            function(err, httpResponse, data) {
                var errorMes = "Đã có lỗi xảy ra. Vui lòng thử lại.";
                if (!data) {
                    return res.status(400).send(errorMes);
                }
                var body = JSON.parse(data);
                if (body["success"] === true) {
                    if (data_new.payment && data_new.payment === 'after') {
                        // call api to register user
                        ApiRequest.post("Front/RegisterAutoDmkh", request_data, function(
                            err,
                            response
                        ) {
                            if (response && response.error) {
                                res.status(400).send(response.error);
                            } else {
                                if (data_new.taxCode && data_new.taxCode.indexOf('-') > -1) {
                                    data_new.taxCode = data_new.taxCode.replace('-', '');
                                }
                                req.session.register_info = {
                                    company: data_new.dk_unit,
                                    link: "https://" + data_new.taxCode + ".ahoadon.com"
                                };
                                sendMailTrial({
                                    company: data_new.dk_unit,
                                    taxCode: data_new.taxCode,
                                    address: data_new.address,
                                    contact: data_new.name,
                                    email: data_new.dk_email,
                                    mobile: data_new.dk_mobile,
                                    address: data_new.address,
                                    address: data_new.address
                                }, () => {
                                    res.status(200).send();
                                });
                            }
                        });
                    } else {
                        let newOrder = new Order();
                        newOrder.dmserver_id = config.server_id;
                        newOrder.user_new = 'Online';
                        newOrder.date_new = null;
                        newOrder.trang_thai_tk = 1;
                        newOrder.kd_insert = 1;
                        newOrder.lan_gia_han = null;
                        newOrder.ten_dvcs = null;
                        newOrder.dia_chi = data_new.address;
                        newOrder.server_name = null;
                        newOrder.hh_ctv_dl = null;
                        newOrder.pt_nguoigt = null;
                        newOrder.da_thu_tien_hd = null;
                        newOrder.da_thu_ho_so = null;
                        newOrder.ngay_hop_dong = null;
                        newOrder.id = null;
                        newOrder.index = null;
                        newOrder.dmkh_id = null;
                        newOrder.loai_kh = "Mới";
                        newOrder.ms_thue = data_new.taxCode;
                        newOrder.ten_kh = data_new.dk_unit;
                        newOrder.diachi_lh = data_new.address;
                        newOrder.tinh_thanh = data_new.location.city;
                        newOrder.nguoi_dai_dien = data_new.dk_name;
                        newOrder.co_quan_thue = null;
                        newOrder.chuc_vu = data_new.title;
                        newOrder.sdt = data_new.dk_mobile;
                        newOrder.email = data_new.dk_email;
                        newOrder.website = "";
                        newOrder.stk = "";
                        newOrder.ngan_hang = "";
                        newOrder.nguoi_lien_he = data_new.name;
                        newOrder.sdt_nguoi_lien_he = data_new.xhd_mobile;
                        newOrder.email_nguoi_lien_he = data_new.xhd_email;
                        newOrder.so_luong_hd = data_new.so_luong_hoa_don;
                        newOrder.choose = 0;
                        newOrder.ma_dvcs = "VP";
                        newOrder.ghi_chu = "";
                        newOrder.ngay_kich_hoat = "";
                        newOrder.trang_thai_db = "Đã tạo DB";
                        newOrder.end_user = "";
                        newOrder.is_trial = true;
                        newOrder.date_expried = moment()
                            .add(7, "days")
                            .format("MM/DD/YYYY");
                        newOrder.status = 0;
                        newOrder.order_name = data_new.ten_goi;
                        newOrder.phi_khoi_tao = data_new.phi_khoi_tao;
                        newOrder.gia_goi = data_new.gia_goi;

                        newOrder.save((err4, data4) => {
                            if (data_new.taxCode && data_new.taxCode.indexOf('-') > -1) {
                                data_new.taxCode = data_new.taxCode.replace('-', '');
                            }
                            req.session.register_info = {
                                company: data_new.dk_unit,
                                link: "https://" + data_new.taxCode + ".ahoadon.com"
                            };
                            res.status(200).send();
                        });

                    }
                } else {
                    if (body["error-codes"]) {
                        switch (body["error-codes"][0]) {
                            case "missing-input-response":
                                {
                                    errorMes = "Bạn chưa thực hiện xác thực.";
                                }
                                break;
                            case "missing-input-secret":
                                {
                                    errorMes = "The secret parameter is missing.";
                                }
                                break;
                            case "invalid-input-secret":
                                {
                                    errorMes = "The secret parameter is invalid or malformed.";
                                }
                                break;
                            case "invalid-input-response":
                                {
                                    errorMes = "Mã xác thực không hợp lệ.";
                                }
                                break;
                        }
                    }
                }
            });
    }
};

// registerDungthu: post
exports.registerTrial = function(req, res) {
    var data_new = req.body.data;
    let request_data = {
        editmode: 1,
        data: [
            {
                dmserver_id: config.server_id,
                user_new: 'Online',
                date_new: null,
                trang_thai_tk: 1,
                kd_insert: 1,
                lan_gia_han: null,
                ten_dvcs: null,
                dia_chi: data_new.address,
                server_name: null,
                hh_ctv_dl: null,
                pt_nguoigt: null,
                da_thu_tien_hd: null,
                da_thu_ho_so: null,
                ngay_hop_dong: null,
                id: null,
                index: 1,
                dmkh_id: null,
                loai_kh: "Mới",
                ms_thue: data_new.taxCode,
                ten_kh: data_new.company,
                diachi_lh: data_new.address,
                co_quan_thue: null,
                tinh_thanh: data_new.location.city,
                nguoi_dai_dien: data_new.contact,
                chuc_vu: data_new.name,
                sdt: "",
                email: data_new.email,
                website: "",
                stk: "",
                ngan_hang: "",
                nguoi_lien_he: data_new.contact,
                sdt_nguoi_lien_he: data_new.mobile,
                email_nguoi_lien_he: data_new.email,
                so_luong_hd: "300",
                choose: 0,
                ma_dvcs: "VP",
                ghi_chu: "",
                ngay_kich_hoat: "",
                trang_thai_db: "Đã tạo DB",
                end_user: "",
                is_trial: true,
                date_expried: moment()
                    .add(7, "days")
                    .format("MM/DD/YYYY")
            }
        ]
    };
    // console.log(request_data);

    request.post(
        {
            url: "https://www.google.com/recaptcha/api/siteverify",
            form: {
                secret: "6LfP1MIUAAAAAGX6fJsmwC_pWPcCsOy73QLl80CW",
                response: req.body["g-recaptcha-response"],
                ip: req.ip
            }
        },
        function(err, httpResponse, data) {
            var errorMes = "Đã có lỗi xảy ra. Vui lòng thử lại.";
            if (!data) {
                return res.status(400).send(errorMes);
            }
            var body = JSON.parse(data);

            if (body["success"] === true) {
                // call api to register user
                ApiRequest.post("Front/RegisterAutoDmkh", request_data, function(
                    err,
                    response
                ) {
                    if (response && response.error) {
                        res.status(400).send(response.error);
                    } else {
                        if (data_new.taxCode && data_new.taxCode.indexOf('-') > -1) {
                            data_new.taxCode = data_new.taxCode.replace('-', '');
                        }
                        req.session.register_info = {
                            company: data_new.company,
                            link: "https://" + data_new.taxCode + ".ahoadon.com"
                        };

                        sendMailTrial(data_new, () => {
                            res.status(200).send();
                        });
                    }
                });
            } else {
                if (body["error-codes"]) {
                    switch (body["error-codes"][0]) {
                        case "missing-input-response":
                            {
                                errorMes = "Bạn chưa thực hiện xác thực.";
                            }
                            break;
                        case "missing-input-secret":
                            {
                                errorMes = "The secret parameter is missing.";
                            }
                            break;
                        case "invalid-input-secret":
                            {
                                errorMes = "The secret parameter is invalid or malformed.";
                            }
                            break;
                        case "invalid-input-response":
                            {
                                errorMes = "Mã xác thực không hợp lệ.";
                            }
                            break;
                    }
                }
                res.status(400).send(errorMes);
            }
        }
    );
};

// dang ky dai ly post
exports.registerAgencyPost = function(req, res) {
    var data_new = req.body.data;
    let request_data = {
        "editmode": 1,
        "data":
            [
                {
                    chon: null,
                    chu_tk: "",
                    chuc_vu: null,
                    database_code: null,
                    date_edit: null,
                    date_new: "",
                    dia_chi: data_new.address,
                    dien_thoai: data_new.mobile,
                    dmdvcs_id: "",
                    dmkh_id: null,
                    dvcs_me_id: "",
                    email: data_new.email,
                    email_dvcq: null,
                    fax: null,
                    giam_doc: null,
                    id: "",
                    loai_daily: null,
                    loai_hop_dong: "DL",
                    ly_do: null,
                    ma_capdaily: "DL",
                    ma_cqthuecapql: null,
                    ma_cqthuecaptinh: null,
                    ma_dvcs: data_new.dl_taxCode,
                    ms_thue: data_new.dl_taxCode,
                    mst_dvcq: null,
                    ngay_bd_nam_tc: null,
                    ngay_kich_hoat: "",
                    nguoi_dai_dien: "",
                    nguoi_gt: "",
                    nguoi_lien_he: data_new.contact,
                    nh_cuoi: null,
                    phantram_gt: 0,
                    pt_du_an: 0,
                    pt_hoahong: 0,
                    pt_khac: 0,
                    qhns: null,
                    quan_huyen: null,
                    sl_hoadon: null,
                    sl_hoadon_full: true,
                    su_dung: "C",
                    tai_khoan: "",
                    tai_nh: "",
                    ten_dvcq: null,
                    ten_dvcs: data_new.unit,
                    ten_en: null,
                    tinh_thanh: "",
                    user_edit: null,
                    user_new: "Online",
                    wb_user_id: null
                }
            ]
    }
    // console.log(request_data);
    request.post(
        {
            url: "https://www.google.com/recaptcha/api/siteverify",
            form: {
                secret: "6LcuMtAUAAAAAEk0w-E1wWTps3nraSARGWwTvoBo",
                response: req.body["g-recaptcha-response"],
                ip: req.ip
            }
        },
        function(err, httpResponse, data) {
            var errorMes = "Đã có lỗi xảy ra. Vui lòng thử lại.";
            if (!data) {
                return res.status(400).send(errorMes);
            }
            var body = JSON.parse(data);

            if (body["success"] === true) {
                // call api to register user
                ApiRequest.post("Front/SaveThongTinDaiLy", request_data, function(
                    err,
                    response
                ) {
                    if (response && response.error) {
                        res.status(400).send(response.error);
                    } else {
                        req.session.register_info = {
                            dl_taxCode: data_new.dl_taxCode,
                            unit: data_new.unit,
                            contact: data_new.contact,
                            address: data_new.address,
                            mobile: data_new.mobile,
                            email: data_new.email,
                            link: "https://" + data_new.dl_taxCode + ".hoadonviet.net"
                        };
                        sendMailAgency(data_new, () => {
                            res.status(200).send();
                        });
                    }
                });
            } else {
                if (body["error-codes"]) {
                    switch (body["error-codes"][0]) {
                        case "missing-input-response":
                            {
                                errorMes = "Bạn chưa thực hiện xác thực.";
                            }
                            break;
                        case "missing-input-secret":
                            {
                                errorMes = "The secret parameter is missing.";
                            }
                            break;
                        case "invalid-input-secret":
                            {
                                errorMes = "The secret parameter is invalid or malformed.";
                            }
                            break;
                        case "invalid-input-response":
                            {
                                errorMes = "Mã xác thực không hợp lệ.";
                            }
                            break;
                    }
                }
                res.status(400).send(errorMes);
            }
        }
    );
};

// đăng ký thành công
exports.registerOk = function(req, res, next) {
    let data = req.session.register_info;
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        renderPage(req, res, "frontend/pages/registersuccess", {
            data: data,
            code: '00',
            is_trial: 1
        });
    }
    else {
        return next();
    };
};

// đăng ký dùng thử thành công
exports.registerTrialSuccess = function(req, res, next) {
    let data = req.session.register_info;
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        renderPage(req, res, "frontend/pages/registerTrialSuccess", {
            data: data
        });
    }
    else {
        return next();
    };
};

// đăng ký đại lý thành công 
exports.registerAgencySuccess = function(req, res, next) {
    let data = req.session.register_info;
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        // co subdomain, next do dynamic
        renderPage(req, res, "frontend/pages/registerAgencySuccsess", {
            data: data
        });
    }
    else {
        return next();
    };

};

// tính năng
exports.details = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        renderPage(req, res, "frontend/pages/features/details", {
            titleActive: "tinh-nang"
        });
    }
    else {
        return next();
    };

};

// blog
exports.listBlog = function(req, res, next) {
    // co subdomain
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstBlog", (err, res) => {
                        return cb(null, res);
                    });
                },
                cb => {
                    ApiRequest.get("Front/LstBlogCategory", (err, res) => {
                        return cb(null, res);
                    });
                },
                cb => {
                    ApiRequest.get("Front/LstBlog", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");
                let lstBlog = result[0];
                let LstBlogCategory = result[1];
                let topBlog = result[2].sort(result[2].DATE_CREATED);
                if (topBlog.length > 5) {
                    topBlog = topBlog.slice(0, 5);
                }
                //    tin tuc ngau nhien
                let blogRandom = _.sample(result[0], 5);
                // XU LY PAGING
                // SO BAN GHI 1 TRANG
                let pageSize = 10;
                //  SO LUONG PAGE
                let page = req.query.page ? parseInt(req.query.page) : 1;
                // tong so ban ghi
                let totalRecords = lstBlog.length;
                // so trang
                let totalPage = Math.ceil(totalRecords / pageSize);
                // data view
                let totalViews = [];
                totalViews = lstBlog.splice((page - 1) * pageSize, pageSize);

                renderPage(req, res, "frontend/pages/blog/home", {
                    blog: totalViews,
                    totalPage: totalPage,
                    blogCategory: LstBlogCategory,
                    titleActive: "tin-tuc",
                    topBlog: topBlog,
                    blogRandom: blogRandom
                });
            }
        );
    }
    else {
        return next();
    }

};

// blog category
exports.listBlogCategory = function(req, res, next) {
    let blog_category_url = req.params.blog_category_url;
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstBlogByCate?cate_url=" + blog_category_url, (err, res) => {
                        return cb(null, res);
                    });
                },
                cb => {
                    ApiRequest.get("Front/LstBlogCategory", (err, res) => {
                        return cb(null, res);
                    });
                },
                cb => {
                    ApiRequest.get("Front/LstBlog", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");
                let LstBlog = result[0];
                let LstBlogCategory = result[1];
                let topBlog = result[2].sort(result[2].DATE_CREATED);
                if (topBlog.length > 5) {
                    topBlog = topBlog.splice(0, 5);
                }

                renderPage(req, res, "frontend/pages/blog/home", {
                    blog: LstBlog,
                    blogCategory: LstBlogCategory,
                    titleActive: "tin-tuc",
                    topBlog: topBlog,
                    title: 'Tin tức - A hóa đơn | Hóa Đơn Điện Tử | Tiết kiệm 90% Chi Phí | An toàn nhất'
                });
            }
        );
    }
    else {
        return next();
    }
};

// blog tags
exports.listBlogByTags = function(req, res, next) {
    renderPage(req, res, "frontend/pages/blog/home", []);
};

// blog - chi tiet
exports.getBlogDetail = function(req, res, next) {
    var title_url = req.params.title_url;
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstBlogCategory", (err, data) => {
                        return cb(err, data);
                    });
                },
                cb => {
                    ApiRequest.get("Front/GetBlogByUrl?url=" + title_url, (err, data) => {
                        return cb(err, data);
                    })
                },
                // Top 5 bài viết
                cb => {
                    ApiRequest.get("Front/LstBlog", (err, res) => {
                        return cb(null, res);
                    });
                },
                // 3 bài ngầu nhiên
                cb => {
                    ApiRequest.get("Front/LstBlog", (err, res) => {
                        return cb(null, res);
                    });
                }

            ],
            (err, result) => {
                if (err && result[1].length === 0) {
                    return res.render('404');
                } else {
                    // tin tức nổi bật
                    let topBlog = result[2].sort(result[2].DATE_CREATED);
                    if (topBlog.length > 3) {
                        topBlog = topBlog.splice(0, 5);
                    }
                    //  3 tin tức ngẫu nhiên
                    let blogRandom = _.sample(result[3], 5);
                    renderPage(req, res, "frontend/pages/blog/details", {
                        title: result[1][0].TITLE + '- A hóa đơn | Hóa Đơn Điện Tử | Tiết kiệm 90% Chi Phí | An toàn nhất',
                        detail: result[1][0],
                        category: result[0],
                        description: result[1][0].DESCRIPTION,
                        blog: result[2],
                        titleActive: "tin-tuc",
                        topBlog: topBlog,
                        blogRandom: blogRandom
                    });
                }
            }
        );
    }
    else {
        return next();
    }

};
// tra cuu
exports.search = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        // co subdomain, next do dynamic
        renderPage(req, res, "frontend/pages/search/home", {
            titleActive: "tra-cuu"
        });
    }
    else {
        return next();
    };
}

// mau hoa don
exports.bills = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        // co subdomain, next do dynamic
        renderPage(req, res, "frontend/pages/bill", {
            titleActive: "mau-hoa-don"
        });
    }
    else {
        return next();
    };
}

// tuyen dung
exports.recruitment = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstRecruitment", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");
                let LstRecruitment = result[0];
                console.log(LstRecruitment);
                renderPage(req, res, "frontend/pages/recruitment", {
                    recruitment: LstRecruitment,
                    titleActive: "tuyen-dung"
                });
            }
        );
    } else {
        return next();
    }
};

// ho tro
exports.support = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        // co subdomain, next do dynamic
        renderPage(req, res, "frontend/pages/support/home", {
            titleActive: "ho-tro"
        });
    }
    else {
        return next();
    };
};

// cau hoi thuong gap
exports.faq = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstSupport?type=cau-hoi-thuong-gap", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");
                let LstQuestion = result[0];
                renderPage(req, res, "frontend/pages/support/faq", {
                    questions: LstQuestion,
                    titleActive: "ho-tro"
                });
            }
        );
    } else {
        return next();
    }
};
// video
exports.supportVideo = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        async.parallel(
            [
                cb => {
                    ApiRequest.get("Front/LstSupport?type=video", (err, res) => {
                        return cb(null, res);
                    });
                }
            ],
            (err, result) => {
                if (err) return renderPage(req, res, "404");
                let LstVideo = result[0];
                renderPage(req, res, "frontend/pages/support/video", {
                    videos: LstVideo,
                    titleActive: "ho-tro"
                });
            }
        );
    } else {
        return next();
    }
};

// lien he
exports.contact = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        renderPage(req, res, "frontend/pages/contact", {
            titleActive: "lien-he"
        });
    }
    else {
        return next();
    };
};

// Liên hệ post
exports.contactPost = function(req, res) {
    res.status(200).send();
};

// chinh sach dai ly
exports.policyAgency = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        renderPage(req, res, "frontend/pages/policyAgency", {
            titleActive: 'dai-ly'
        });
    }
    else {
        return next();
    };
};

// chinh sach bao mat
exports.security_infomation = function(req, res, next) {
    if (req.subDomain.selfDomain && !req.subDomain.having) {
        renderPage(req, res, "frontend/pages/security-infomation", {});
    }
    else {
        return next();
    };
};

// Router for /cua_hang_khong_ton_tai và /duong-dan-khong-ton-tai
exports.notFound = function(req, res) {
    res.render("404");
};

// Router for /server-tam-dung
exports.serverError = function(req, res) {
    res.render("500");
};

// gioi thieu
exports.about = function(req, res, next) {
    renderPage(req, res, "frontend/pages/about");
};

exports.policy = function(req, res, next) {
    renderPage(req, res, "frontend/pages/policy");
};

exports.introWebStore = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }
    renderPage(req, res, "frontend/pages/intro-webstore");
};

exports.supportVideoDetail = function(req, res, next) {
    var title_url = req.params.title_url;
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }
    async.parallel(
        [
            function(cb) {
                ApiRequest.get(
                    "api.v1.supportinfo.list",
                    {
                        status: 1,
                        page_size: -1,
                        type: "video_huong_dan"
                    },
                    cb
                );
            },
            function(cb) {
                ApiRequest.get(
                    "api.v1.supportinfo.get",
                    {
                        title_url: title_url
                    },
                    cb
                );
            }
        ],
        function(err, result) {
            if (err) return res.redirect("/server_tam_dung");
            var videoList = result[0].data;
            var detail = result[1];
            renderPage(
                "frontend/pages/support/videodetails",
                _.merge(
                    {
                        videoList: videoList,
                        detail: detail
                    },
                    seoConfig["/ho-tro/video"]
                )
            );
        }
    );
};

exports.supportCateDetail = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }

    renderPage(
        req,
        res,
        "frontend/pages/support/details",
        _.merge(
            {
                detail: {},
                menu: [],
                url: ""
            },
            seoConfig["/ho-tro/huong-dan"]
        )
    );
};

exports.supportDetail = function(req, res, next) {
    var title_url = req.params.title_url;
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }
    async.parallel(
        [
            function(cb) {
                ApiRequest.get(
                    "api.v1.supportinfo.get",
                    {
                        title_url: title_url
                    },
                    cb
                );
            },
            function(cb) {
                ApiRequest.get(
                    "api.v1.supportinfo.category.list",
                    {
                        select: "type name category_url",
                        type: "thong_tin_tro_giup"
                    },
                    function(err, data) {
                        if (!err && data) {
                            var listCate = data;
                            async.each(
                                listCate,
                                function(item, cb1) {
                                    ApiRequest.get(
                                        "api.v1.supportinfo.list",
                                        {
                                            select: "title title_url",
                                            type: "thong_tin_tro_giup",
                                            support_category: item.category_url
                                        },
                                        function(err, response) {
                                            if (!err) {
                                                item.detail = response;
                                                cb1();
                                            }
                                        }
                                    );
                                },
                                function(err) {
                                    if (!err) {
                                        cb(null, listCate);
                                    }
                                }
                            );
                        }
                    }
                );
            }
        ],
        function(err, result) {
            if (err) return res.redirect("/server_tam_dung");
            var detail = result[0];
            var menu = result[1];
            renderPage(
                req,
                res,
                "frontend/pages/support/details",
                _.merge(
                    {
                        detail: detail,
                        menu: menu,
                        url: title_url
                    },
                    seoConfig["/ho-tro/huong-dan"]
                )
            );
        }
    );
};

exports.payment = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }
    renderPage(req, res, "frontend/pages/payment");
};

exports.contactSuccess = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }
    renderPage(req, res, "frontend/pages/contact-success", seoConfig["/lien-he"]);
};

exports.cancelPromotion = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }
    var email = req.query.email;
    if (validator.isNull(email)) {
        res.redirect("/");
    } else {
        ApiRequest.post(
            "api.v1.emailpromotion.cancel",
            {
                email: email
            },
            function(err, response) {
                renderPage(req, res, "frontend/pages/cancel-email");
            }
        );
    }
};

exports.registerPromotion = function(req, res) {
    ApiRequest.post(
        "api.v1.emailpromotion.add",
        {
            email: req.body.email
        },
        function(err, response) {
            res.status(200).send();
        }
    );
};

exports.contactMail = function(req, res) {
    request.post(
        {
            url: "https://www.google.com/recaptcha/api/siteverify",
            form: {
                secret: "6LfP1MIUAAAAAGX6fJsmwC_pWPcCsOy73QLl80CW",
                response: req.body["g-recaptcha-response"],
                ip: req.ip
            }
        },
        function(err, httpResponse, data) {
            var body = JSON.parse(data);
            if (body["success"] === true) {
                var user = req.body.user;
                // call api to register user
                ApiRequest.post(
                    "api.v1.emailinfo.contact.add",
                    {
                        from_email: req.body.from_email,
                        subject: req.body.subject,
                        content: req.body.content
                    },
                    function(err, response) {
                        res.status(200).send();
                    }
                );
            } else {
                var errorMes = "Đã có lỗi xảy ra. Vui lòng thử lại.";
                if (body["error-codes"]) {
                    switch (body["error-codes"][0]) {
                        case "missing-input-response":
                            {
                                errorMes = "Bạn chưa thực hiện xác thực.";
                            }
                            break;
                        case "missing-input-secret":
                            {
                                errorMes = "The secret parameter is missing.";
                            }
                            break;
                        case "invalid-input-secret":
                            {
                                errorMes = "The secret parameter is invalid or malformed.";
                            }
                            break;
                        case "invalid-input-response":
                            {
                                errorMes = "Mã xác thực không hợp lệ.";
                            }
                            break;
                    }
                }
                res.status(400).send(errorMes);
            }
        }
    );
};

function getHostUrl(req) {
    var hostUrl = req.headers.host;
    if (!hostUrl) hostUrl = req.get("host");
    return hostUrl;
}

/**
 * Render trang frontend, hỗ trợ cấu hình seo
 * @param  {[type]} page  [description]
 * @param  {[type]} extra [description]
 * @return {[type]}       [description]
 */
function renderPage(req, res, page, extra) {
    var path = req.path;
    var mapping = _.merge(
        {
            socket_host: config.socket_host
        },
        seoConfig[path],
        extra
    );
    res.render(page, mapping);
}

exports.resources = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }
    ApiRequest.get("api.v1.blog.category.list", function(err, data) {
        if (err) return cb(err);
        renderPage(req, res, "frontend/pages/resources", {
            title: "Tài nguyên kiến thức - HDV",
            description:
                "Tài nguyên kiến thức Phần mềm hóa đơn điện tử dành cho - HDV.",
            data: data
        });
    });
};

exports.download = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }

    renderPage(req, res, "frontend/pages/download", {
        title: "Tải ứng dụng Phần mềm hóa đơn điện tử dành cho HDV",
        description: "Tải miễn phí ứng dụng Phần mềm hóa đơn điện tử dành cho HDV"
    });
};

exports.createPaymentUrl = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }

    var ipAddr =
        req.headers["x-forwarded-for"] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;

    var dateFormat = require("dateformat");

    var tmnCode = config.vnp.vnp_TmnCode;
    var secretKey = config.vnp.vnp_HashSecret;
    var vnpUrl = config.vnp.vnp_Url;
    var returnUrl = config.vnp.vnp_ReturnUrl;
    var date = new Date();
    var createDate = dateFormat(date, "yyyymmddHHmmss");
    var amount = req.body.amount;

    var vnp_Params = {};
    vnp_Params["vnp_Version"] = "2.0.0";
    vnp_Params["vnp_Command"] = "pay";
    vnp_Params["vnp_TmnCode"] = tmnCode;
    // vnp_Params['vnp_Merchant'] = ''
    vnp_Params["vnp_Locale"] = "vn";
    vnp_Params["vnp_CurrCode"] = "VND";
    vnp_Params["vnp_TxnRef"] = randomTntRef();
    vnp_Params["vnp_OrderInfo"] = req.body.mst;
    vnp_Params["vnp_OrderType"] = "billpayment";
    vnp_Params["vnp_Amount"] = amount * 100;
    vnp_Params["vnp_ReturnUrl"] = returnUrl;
    vnp_Params["vnp_IpAddr"] = ipAddr;
    vnp_Params["vnp_CreateDate"] = createDate;

    vnp_Params = sortObject(vnp_Params);

    var querystring = require("qs");
    var signData =
        secretKey + querystring.stringify(vnp_Params, {encode: false});

    var sha256 = require("sha256");

    var secureHash = sha256(signData);

    vnp_Params["vnp_SecureHashType"] = "SHA256";
    vnp_Params["vnp_SecureHash"] = secureHash;
    vnpUrl += "?" + querystring.stringify(vnp_Params, {encode: true});

    //Neu muon dung Redirect thi dong dong ben duoi
    Order
        .findOne({
            ms_thue: req.body.mst
        })
        .exec((err4, data4) => {
            if (data4) {
                data4.ma_giao_dich = vnp_Params["vnp_TxnRef"];
                data4.total_price = amount * 100;
                data4.save(() => {
                    res.status(200).json({code: "00", data: vnpUrl});
                })
            } else {
                res.status(200).json({code: "00", data: vnpUrl});
            }
        })
};

exports.vnPayReturn = function(req, res, next) {
    var vnp_Params = req.query;

    var secureHash = vnp_Params["vnp_SecureHash"];

    delete vnp_Params["vnp_SecureHash"];
    delete vnp_Params["vnp_SecureHashType"];

    vnp_Params = sortObject(vnp_Params);

    var tmnCode = config.vnp.vnp_TmnCode;
    var secretKey = config.vnp.vnp_HashSecret;

    var querystring = require("qs");
    var signData =
        secretKey + querystring.stringify(vnp_Params, {encode: false});

    var sha256 = require("sha256");

    var checkSum = sha256(signData);

    if (secureHash === checkSum) {
        let vnp_ResponseCode = vnp_Params['vnp_ResponseCode'];
        let vnp_Amount = vnp_Params['vnp_Amount'];
        let vnp_TransactionNo = vnp_Params['vnp_TransactionNo'];
        let vnp_TxnRef = vnp_Params['vnp_TxnRef'];
        Order
            .findOne({
                ma_giao_dich: vnp_TxnRef
            })
            .exec((err, data2) => {
                if (err || !data2) {
                    renderPage(req, res, "frontend/pages/registersuccess", {code: "01"});
                } else if (data2.total_price.toString() !== vnp_Amount.toString()) {
                    renderPage(req, res, "frontend/pages/registersuccess", {code: "04"});
                } else if (data2 && data2.status !== 0) {
                    renderPage(req, res, "frontend/pages/registersuccess", {code: "02"});
                } else if (vnp_ResponseCode == '00') {
                    let request_data = req.session.register_info;
                    let data = {
                        company: request_data.company,
                        link: request_data.link,
                        goi_hoa_don: data2.order_name + ' + Phí khởi tạo lần đầu',
                        so_tien_thanh_toan: (Math.round(parseInt(vnp_Amount) / 100)).toString() + ' VNĐ',
                        cong_thanh_toan: 'VNPAY',
                        ma_giao_dich: vnp_TxnRef
                    };
                    renderPage(req, res, "frontend/pages/registersuccess", {
                        data: data,
                        code: '00',
                        is_trial: 0
                    });
                } else {
                    renderPage(req, res, "frontend/pages/registersuccess", {
                        data: {},
                        code: vnp_ResponseCode,
                        is_trial: 0
                    });
                }
            })
    } else {
        renderPage(req, res, "frontend/pages/registersuccess", {code: "97"});
    }
};

exports.vnPayIPN = function(req, res, next) {
    var vnp_Params = req.query;
    var secureHash = vnp_Params["vnp_SecureHash"];

    delete vnp_Params["vnp_SecureHash"];
    delete vnp_Params["vnp_SecureHashType"];

    vnp_Params = sortObject(vnp_Params);
    var secretKey = config.vnp.vnp_HashSecret;
    var querystring = require("qs");
    var signData =
        secretKey + querystring.stringify(vnp_Params, {encode: false});

    var sha256 = require("sha256");

    var checkSum = sha256(signData);

    if (secureHash === checkSum) {
        var orderId = vnp_Params["vnp_TxnRef"];
        var rspCode = vnp_Params["vnp_ResponseCode"];
        let vnp_Amount = vnp_Params['vnp_Amount'];

        //Kiem tra xem du lieu trong db co hop le hay khong va gui API dang ky len
        Order
            .findOne({
                ma_giao_dich: orderId
            })
            .exec((err5, data5) => {
                if (err5) {
                    return res.status(200).json({RspCode: "99", Message: err5});
                } else if (!data5) {
                    return res.status(200).json({RspCode: "01", Message: "Order not found"});
                } else if (data5.total_price.toString() !== vnp_Amount.toString()) {
                    return res.status(200).json({RspCode: "04", Message: "Invalid amount"});
                } else if (data5 && data5.status !== 0) {
                    return res.status(200).json({RspCode: "02", Message: "Order already confirmed"});
                } else if (rspCode == '00') {
                    data5 = data5.toObject();
                    let data_mail = {
                        company: data5.ten_kh,
                        taxCode: data5.ms_thue,
                        address: data5.diachi_lh,
                        contact: data5.nguoi_lien_he,
                        mobile: data5.sdt,
                        email: data5.email,
                        xhd_contact: data5.nguoi_lien_he,
                        xhd_email: data5.email_nguoi_lien_he,
                        ten_goi: data5.order_name,
                        phi_khoi_tao: data5.phi_khoi_tao,
                        gia_goi: data5.gia_goi,
                        tong_tien: Math.round(data5.total_price / 100),
                        cong_thanh_toan: 'VNPAY',
                        ma_giao_dich: data5.ma_giao_dich
                    }
                    delete data5._id;
                    delete data5.__v;
                    delete data5.status;
                    delete data5.order_name;
                    delete data5.phi_khoi_tao;
                    delete data5.gia_goi;
                    delete data5.ma_giao_dich;
                    let request_data = {
                        editmode: 1,
                        data: [data5]
                    };
                    request_data.data[0].ngay_kich_hoat = moment().format('MM/DD/YYYY');
                    request_data.data[0].is_trial = false;
                    request_data.data[0].date_expried = null;
                    ApiRequest.post(
                        "Front/RegisterAutoDmkh", request_data,
                        (err, res1) => {
                            if (err) {
                                res.status(200).json({RspCode: "01", Message: "Order not found"});
                            };
                            let active_mst = request_data.data[0].ms_thue;
                            ApiRequest.post(
                                "Front/ActiveAccount?mst=" + active_mst, {}, (err, res3) => {
                                    Order.updateMany({
                                        ma_giao_dich: orderId
                                    }, {
                                        status: 1
                                    }, (err6, data6) => {
                                        // Sendmail thanh toán
                                        sendMailUse(data_mail, () => {
                                            res.status(200).json({RspCode: "00", Message: "Confirm Success"});
                                        });
                                    });
                                });
                        }
                    );
                } else {
                    Order.updateMany({
                        ma_giao_dich: orderId
                    }, {
                        status: 2
                    }, (err6, data6) => {
                        res.status(200).json({RspCode: "00", Message: "Confirm Success"});
                    });
                }
            })
    } else {
        res.status(200).json({RspCode: "97", Message: "Invalid signature"});
    }
};

function sortObject(o) {
    var sorted = {},
        key,
        a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
            a.push(key);
        }
    }

    a.sort();

    for (key = 0; key < a.length; key++) {
        sorted[a[key]] = o[a[key]];
    }
    return sorted;
}

function randomTntRef() {
    var result = '';
    var characters = '0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < 6; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

// Lấy thông tin mã số thuế
exports.getCompanyInfoByMST = function(req, res, next) {
    let tax = req.body.tax;
    let apiUrl = "https://thongtindoanhnghiep.co/api/company/" + tax;

    var options = {
        method: "GET",
        uri: apiUrl,
        json: true
    };

    request(options, function(err, httpResponse, body) {
        if (err) {
            res.status(400).send(err);
        } else {
            ApiRequest.get("Front/CheckMst?mst=" + tax, (err, res1) => {
                if (err) return res.status(400).send(err);
                if (res1 && res1.error) {
                    res.status(400).send(res1.error);
                } else {
                    res.status(200).send({
                        name: body.Title,
                        address: body.DiaChiCongTy,
                        contact: body.ChuSoHuu,
                        phone: body.NoiDangKyQuanLy_DienThoai,
                        tinh_thanh: body.TinhThanhTitle
                    });
                }
            });
        }
    });
};

exports.checkMaDL = function(req, res, next) {
    var maDL = req.body.maDL;

    ApiRequest.get("Front/Checkdl?madl=" + maDL, (err, res1) => {
        if (err) return res.status(400).send(err);
        if (res1 && res1.error) {
            res.status(400).send(res1.error);
        } else {
            res.status(200).send();
        }
    });
};

function checkDL(ma_daily, isSubDomain) {
    if (isSubDomain) {
        return new Promise((resolve, reject) => {
            ApiRequest.get("Front/Checkdl?madl=" + ma_daily, (err, res1) => {
                if (err) return resolve({
                    ma_daily: null
                });
                if (res1 && res1.error) {
                    resolve({
                        ma_daily: ma_daily
                    });

                } else {
                    resolve({
                        ma_daily: null
                    });
                }
            });
        });
    } else {
        return new Promise((resolve, reject) => {
            ApiRequest.get("Front/CheckWebsite?web=" + ma_daily, (err, res1) => {
                if (err) return resolve({
                    ma_daily: null
                });
                if (res1 && res1.error) {
                    resolve({
                        ma_daily: null
                    });
                } else {
                    resolve({
                        ma_daily: res1.ma_daily
                    });
                }
            });
        });
    }
}

exports.createPaymentMomoUrl = function(req, res, next) {
    // co subdomain, next do dynamic
    if (req.subDomain.having || !req.subDomain.selfDomain) {
        return next();
    }

    var api_url = config.momo_payment.api_endpoint;
    var accessKey = config.momo_payment.access_key;
    var partnerCode = config.momo_payment.partner_code;
    var requestType = 'captureMoMoWallet';
    var notifyUrl = config.momo_payment.ipn_url;
    var returnUrl = config.momo_payment.return_url;

    var dateFormat = require("dateformat");
    var date = new Date();
    var createDate = "MM" + dateFormat(date, "yyyymmddHHmmss");
    var requestId = createDate;

    var orderId = req.body.mst;
    var amount = req.body.amount;
    var orderInfo = 'Thanh-toan-hoa-don-viet';
    var extraData = '';
    var serectkey = config.momo_payment.secret_key;
    const crypto = require('crypto');

    var request_string = 'partnerCode=' + partnerCode
        + '&accessKey=' + accessKey
        + '&requestId=' + requestId
        + '&amount=' + amount
        + '&orderId=' + orderId
        + '&orderInfo=' + orderInfo
        + '&returnUrl=' + returnUrl
        + '&notifyUrl=' + notifyUrl
        + '&extraData=' + extraData;
    var signature = crypto.createHmac('sha256', serectkey)
        .update(request_string)
        .digest('hex');

    var request_data = {
        accessKey: accessKey,
        partnerCode: partnerCode,
        requestType: requestType,
        notifyUrl: notifyUrl,
        returnUrl: returnUrl,
        requestId: requestId,
        orderId: orderId,
        amount: amount,
        orderInfo: orderInfo,
        extraData: extraData,
        signature: signature
    };

    let options_request = {
        ethod: 'POST',
        uri: api_url,
        json: request_data
    }
    request(options_request, (err, httpResponse, body) => {
        if (err) {
            res.status(400).send(err);
        } else if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
            res.status(400).send('Lỗi');
        } else {
            if (body.errorCode && body.errorCode > 0) {
                res.status(400).send(body.localMessage);
            } else {
                res.status(200).send(body.payUrl);
            }
        }
    });
}

exports.momoReturn = function(req, res, next) {
    if (req.query.partnerCode === config.momo_payment.partner_code && req.query.accessKey === config.momo_payment.access_key && req.query.errorCode == '0') {
        let request_data = req.session.register_info;
        let data = {
            company: request_data.company,
            link: request_data.link
        };
        renderPage(req, res, "frontend/pages/registersuccess", {
            data: data,
            code: '00'
        });
    } else {
        renderPage(req, res, "frontend/pages/registersuccess", {
            code: '97'
        });
    }
}

exports.momoIPN = function(req, res, next) {
    if (req.query.partnerCode === config.momo_payment.partner_code && req.query.accessKey === config.momo_payment.access_key && req.query.errorCode == '0') {
        let orderInfo = req.query.orderId;
        Order
            .findOne({
                ms_thue: orderInfo
            })
            .exec((err5, data5) => {
                if (err5 || !data5) {
                    return res.status(200).json({RspCode: "00", Message: "success"});
                } else {
                    let request_data = {
                        editmode: 1,
                        data: [data5]
                    };
                    request_data.data[0] = request_data.data[0].toObject();
                    delete request_data.data[0]._id;
                    delete request_data.data[0].__v;
                    request_data.data[0].ngay_kich_hoat = moment().format('MM/DD/YYYY');
                    request_data.data[0].is_trial = false;
                    request_data.data[0].date_expried = null;
                    ApiRequest.post(
                        "Front/RegisterAutoDmkh", request_data,
                        (err, res1) => {
                            if (err) {
                                res.status(200).json({RspCode: "00", Message: "success"});
                            };
                            let active_mst = request_data.data[0].ms_thue;
                            Order
                                .deleteMany({
                                    ms_thue: orderInfo
                                })
                                .exec((err6, data6) => {
                                    ApiRequest.post(
                                        "Front/ActiveAccount?mst=" + active_mst, {}, (err, res3) => {
                                            res.status(200).json({RspCode: "00", Message: "success"});
                                        });
                                })
                        }
                    );
                }
            })
    }
}

exports.sendEmail = function(req, res, next) {
    const body = req.body;
    const sg = require('sendgrid')(config.sendgrid_key);
    const helper = require('sendgrid').mail;
    var from_email = new helper.Email('noreply@ahoadon.com', 'AHOADON.COM');
    var to_email = new helper.Email(body.to);
    var subject = body.subject || 'Thông báo từ AHOADON.COM';
    var content = new helper.Content('text/html', body.content || 'AHOADON.COM ');
    var mail = new helper.Mail(from_email, subject, to_email, content);
    if (body.mail_info) {
        for (var attr in body.mail_info) {
            if (body.mail_info[attr] !== null && body.mail_info[attr] !== undefined && typeof body.mail_info[attr].toString === 'function') {
                body.mail_info[attr] = body.mail_info[attr].toString();
            }
            mail.personalizations[0].addSubstitution(new helper.Substitution('{{' + attr + '}}', body.mail_info[attr]));
        }
    }
    mail.setTemplateId(body.template_id);
    var request = sg.emptyRequest({
        method: 'POST',
        path: '/v3/mail/send',
        body: mail.toJSON()
    });
    sg.API(request, function(error, response) {
        if (error) {
            res.status(400).send(error);
        } else {
            res.status(200).send(response.body);
        }
    });

}

exports.vnPayList = function(req, res, next) {
    Order
        .find()
        .exec((err, data) => {
            if (err) return res.render('404');
            renderPage(req, res, 'frontend/pages/vnpay', {
                lst_order: data
            })
        });
}

function sendMail2(params, callback) {
    const body = params;
    const sg = require('sendgrid')(config.sendgrid_key);
    const helper = require('sendgrid').mail;
    var from_email = new helper.Email('noreply@ahoadon.com', 'AHOADON.COM');
    var to_email = new helper.Email(body.to);
    var subject = body.subject || 'Thông báo từ AHOADON.COM';
    var content = new helper.Content('text/html', body.content || 'AHOADON.COM ');
    var mail = new helper.Mail(from_email, subject, to_email, content);
    if (body.mail_info) {
        for (var attr in body.mail_info) {
            if (body.mail_info[attr] !== null && body.mail_info[attr] !== undefined && typeof body.mail_info[attr].toString === 'function') {
                body.mail_info[attr] = body.mail_info[attr].toString();
            }
            mail.personalizations[0].addSubstitution(new helper.Substitution('{{' + attr + '}}', body.mail_info[attr]));
        }
    }
    mail.setTemplateId(body.template_id);
    var request = sg.emptyRequest({
        method: 'POST',
        path: '/v3/mail/send',
        body: mail.toJSON()
    });
    sg.API(request, function(error, response) {
        if (error) {
            return callback(error)
        } else {
            return callback(response.body);
        }
    });
}

function sendMailTrial(params, callback) {
    async.parallel([(cb) => {
        sendMail2({ // Send mail customer
            to: params.email,
            subject: 'AHOADON.COM – Thông báo đăng ký dùng thử thành công',
            template_id: config.sendgrid_id.register_online_customer,
            mail_info: {
                ten_donvi: params.company,
                ten_daily: "Công ty cổ phần Truyền số liệu Việt Nam DCV",
                ma_so_thue: params.taxCode,
                diachi: params.address,
                nguoilienhe: params.contact,
                email: params.email,
                phone: params.mobile,
                ten_mien: 'https://' + params.taxCode + '.ahoadon.com',
                user_macdinh: params.taxCode,
                password_macdinh: '123456'
            }
        }, (err, result) => {
            return cb();
        })
    }, (cb) => {
        sendMail2({ // Send mail business
            to: config.sendgrid_tvdv_mail,
            subject: 'AHOADON.COM – Đăng ký dùng thử thành công - ' + params.company,
            template_id: config.sendgrid_id.register_online_business,
            mail_info: {
                ten_donvi: params.company,
                ten_mien: 'https://' + params.taxCode + '.ahoadon.com',
                diachi: params.address,
                ma_sothue: params.taxCode,
                nguoi_lienhe: params.contact,
                phone: params.mobile,
                email: params.email
            }
        }, (err, result) => {
            return cb();
        })
    }], () => {
        return callback();
    });
}

function sendMailUse(params, callback) {
    async.parallel([(cb) => {
        sendMail2({ // Send mail customer
            to: params.email,
            subject: 'AHOADON.COM – Thông báo đăng ký và thanh toán thành công',
            template_id: config.sendgrid_id.payment_online_customer,
            mail_info: {
                ten_donvi: params.company,
                ten_daily: "Công ty cổ phần Truyền số liệu Việt Nam DCV",
                phi_khoi_tao: params.phi_khoi_tao,
                ten_goi: params.ten_goi,
                don_gia: params.gia_goi,
                tong_tien: params.tong_tien,
                cong_thanh_toan: params.cong_thanh_toan,
                ma_giao_dich: params.ma_giao_dich,
                ma_so_thue: params.taxCode,
                diachi: params.address,
                nguoilienhe: params.contact,
                email: params.email,
                phone: params.mobile,
                xhd_ma_so_thue: params.taxCode,
                xhd_ten_donvi: params.company,
                xhd_diachi: params.address,
                xhd_nguoilienhe: params.xhd_contact,
                xhd_email: params.xhd_email,
                ten_mien: 'https://' + params.taxCode + '.ahoadon.com',
                user_macdinh: params.taxCode,
                password_macdinh: '123456'
            }
        }, (err, result) => {
            return cb();
        })
    }, (cb) => {
        sendMail2({ // Send mail business
            to: config.sendgrid_tvdv_mail,
            subject: 'AHOADON.COM – Mua ngay thành công - ' + params.company,
            template_id: config.sendgrid_id.payment_online_business,
            mail_info: {
                ten_donvi: params.company,
                ma_sothue: params.taxCode,
                ten_mien: 'https://' + params.taxCode + '.ahoadon.com',
                diachi: params.address,
                nguoi_lienhe: params.contact,
                phone: params.mobile,
                email: params.email
            }
        }, (err, result) => {
            return cb();
        })
    }], () => {
        return callback();
    });
}

function sendMailAgency(params, callback) {
    async.parallel([(cb) => {
        sendMail2({ // Send mail customer
            to: params.email,
            subject: 'AHOADON.COM – Thông báo đã nhận được yêu cầu đăng ký đại lý',
            template_id: config.sendgrid_id.register_agency_customer,
            mail_info: {
                ten_khachhang: params.unit,
                ten_daily: "Công ty cổ phần truyền số liệu Việt Nam DCV",
                ma_sothue: params.dl_taxCode,
                ten_donvi: params.unit,
                diachi: params.address,
                nguoi_lienhe: params.contact,
                phone: params.mobile,
                email: params.email
            }
        }, (err, result) => {
            return cb();
        })
    }, (cb) => {
        sendMail2({ // Send mail business
            to: config.sendgrid_tvdv_mail,
            subject: 'AHOADON.COM – Yêu cầu đăng ký đại lý - Công ty cổ phần Truyền số liệu Việt Nam DCV',
            template_id: config.sendgrid_id.register_agency_business,
            mail_info: {
                ten_daily: "Công ty cổ phần truyền số liệu Việt Nam DCV",
                ma_sothue: params.dl_taxCode,
                tendonvi: params.unit,
                diachi: params.address,
                nguoilienhe: params.contact,
                phone: params.mobile,
                email: params.email
            }
        }, (err, result) => {
            return cb();
        })
    }], () => {
        return callback();
    });
}

