/**
 * 日志业务逻辑模型
 *
 * @author CaiAoLin
 * @date 2017/7/27
 * @version
 */
const BaseModel = require("../../common/base/base_model");
const LogType = require("../../common/const/log_type_const");
const mongoose = require("mongoose");
const UAParser = require("ua-parser-js");
const Request = require("request");

class LogModel extends BaseModel {

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        let parent = super();
        parent.model = mongoose.model('log');
        parent.init();
    }

    /**
     * 新增日志
     *
     * @param {String} userId
     * @param {Number} type
     * @param {String|Object} message
     * @return {Promise}
     */
    addLog(userId, type, message) {
        let result = null;
        if (typeof message === 'string' && message === '') {
            return result;
        }
        if (typeof message === 'object' && Object.keys(message).length <= 0) {
            return result;
        }

        let addData = {
            user_id: userId,
            type: type,
            message: message,
            create_time: new Date().getTime()
        };
        result = this.db.create(addData);
        return result;
    }

    /**
     * 新增登录日志
     *
     * @param {String} userId
     * @param {Object} request
     * @return {Promise}
     */
    async addLoginLog(userId, request) {
    /*     let ip = request.connection.remoteAddress;
        ip = ip?ip.split(':'):[];
        ip = ip[3] === undefined ? '' : ip[3]; */
        let ip = request.headers["x-real-ip"]? request.headers["x-real-ip"]:"";
        // let ipInfo = '127.0.0.1';//await this.getIpInfoFromApi(ip);
        let ipInfo = await this.getIpInfoFromApi(ip);

        let userAgentObject = new UAParser(request.headers['user-agent']);
        let osInfo = userAgentObject.getOS();
        let cpuInfo = userAgentObject.getCPU();
        let browserInfo = userAgentObject.getBrowser();
        let message = {
            os: osInfo.name + ' ' + osInfo.version + ' ' + cpuInfo.architecture,
            browser: browserInfo.name + ' ' + browserInfo.version,
            ip: ip,
            ip_info:ipInfo
        };

        return this.addLog(userId, LogType.LOGIN_LOG, message);
    }

    /**
     * 获取log列表
     *
     * @param {String} userId
     * @param {Number} type
     * @param {Number} page
     * @param {Number} pageSize
     * @return {Promise}
     */
    async getLog(userId, type, page = 1, pageSize = 3) {
        let condition = {
            user_id: userId,
            type: type
        };
        page = parseInt(page);
        page = page <= 1 ? 1 : page;
        let option = {pageSize: pageSize, offset: parseInt((page - 1) * pageSize), sort: {create_time:-1}};

        let logList = await this.db.find(condition, null, option);
        logList = logList.length > 0 ? logList : [];

        return logList
    }

    /**
     * 获取ip信息
     *
     * @param {String} ip
     * @return {Promise}
     */
    async getIpInfoFromApi(ip) {
        let result = '';
        if (ip === '') {
            return result;
        }
        if (ip === '127.0.0.1') {
            return '服务器本机访问';
        }
        let option = {
            url: 'https://api01.aliyun.venuscn.com/ip?ip=' + ip,
            encoding: 'utf8',
            timeout:2000,
            headers: {
                Authorization: 'APPCODE ' + '85c64bffe70445c4af9df7ae31c7bfcc',
            }
        };
        return new Promise(function (resolve, reject) {
            try {
                // 请求接口
                Request(option, function (err, getResponse, body) {
                    if (err) {
                        //throw '请求错误';
                        resolve("请求错误");
                        return;
                    }
                    if (getResponse.statusCode !== 200) {
                        resolve("获取数据失败！");
                        return;
                        //throw '获取数据失败！';
                    }
                    let responseData = JSON.parse(body);
                    let ipData = responseData.data !== undefined ? responseData.data : [];
                    if (ipData.ip === undefined) {
                        resolve("接口数据有误,ip数据为空！");
                        console.log(ipData);
                        return;
                        //throw '接口数据有误';
                    }
                    resolve(ipData.region + ipData.city + ' ' + ipData.isp);
                });
            } catch (error) {
                reject([]);
            }
        });
    }
}

module.exports = LogModel;
