const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");

class NeedinfoService extends ServiceBase {
    constructor() {
        super("media", ServiceBase.getDaoName(NeedinfoService));
        this.launchchannelDao = system.getObject("db.configmag.launchchannelDao");
        this.execClient = system.getObject("util.execClient");
        this.mediabrowsingRecordsLogUrl = settings.mediabrowsingRecordsLogUrl();
    }
    //提交商机/线索
    async submitNeed(pobj){
        if(!pobj || !pobj.actionBody){
            return system.getResultFail(-100,"参数错误");
        }
        var ab = pobj.actionBody;
        var res = await this.checkAndPackageSubmitParams(ab);//校验封装参数
        if(res && res.status && res.status<0){
            return res;
        }
        var createRes = await this.dao.create(res);
        this.pushMediaNeed2Queue(createRes.id);
        return system.getResultSuccess();

    }
    //校验封装参数
    async checkAndPackageSubmitParams(ab){
        if(!ab.submit_type){
            return system.getResultFail(-101,"提交方式不能为空！")
        }else if(ab.submit_type!="1" && ab.submit_type!="2"){
            return system.getResultFail(-102,"提交方式参数错误！")
        }
        if(!ab.channel_code){
            return system.getResultFail(-103,"渠道编码不能为空！")
        }
        if(!ab.page_code){
            return system.getResultFail(-104,"页面编码不能为空！")
        }
        if(!ab.page_name){
            return system.getResultFail(-105,"页面名称不能为空！")
        }
        if(!ab.original_need){
            return system.getResultFail(-106,"需求信息不能为空！")
        }
        if(!ab.contact_mobile){
            return system.getResultFail(-107,"联系电话不能为空！")
        }
        var channel = await this.launchchannelDao.model.findOne({
            attributes:["code","name"],
            where:{code:ab.channel_code},raw:true
        });
        if(!channel || !channel.code){
            return system.getResultFail(-300,"渠道信息不存在")
        }
        ab["channel_name"] = channel.name;
        return ab;
    }
    //推送需求至队列
    async pushMediaNeed2Queue(id) {
        try {
            if (!id) {
                return;
            }
            var url = "http://sytxpublic-msgq-service.chaolai/api/queueAction/producer/springBoard";
            var obj = {
                "actionType": "produceData",// Y 功能名称
                "actionBody": {
                    "pushUrl": "https://mmc.gongsibao.com/external/action/template/springBoard",// Y 推送地址
                    "actionType": "pushAggregationNeedInfo2fq",// Y 推送地址接收时的功能名称               
                    "identifyCode": "marketmedia-pushneed2fq",// Y 操作的业务标识
                    "messageBody": { // Y 推送的业务消息，必须有一项对象属性值
                        "id": id
                    }
                }
            };
            // var result = await this.execClient.execPost(obj, url);
            // console.log(JSON.stringify(result), "result....push....");
        } catch (e) {
            console.log(e, "pushMediaNeed2Queue++++++++++++++++++++++++++++++++++++")
        }
    }
    //添加媒体聚合页浏览记录
    async addbrowsingrecord(pobj){
        if(pobj && pobj.actionBody){
            var addObj=pobj.actionBody ||{};
            if(!addObj.channel_code){
                addObj.channel_code="未知";
            }
            if(!addObj.channel_name){
                addObj.channel_name="未知";
            }
            if(!addObj.platform){
                addObj.platform="未知";
            }
            if(!addObj.equipment){
                addObj.equipment="未知";
            }
            if(!addObj.page_code){
                addObj.page_code="未知";
            }
            if(!addObj.page_name){
                addObj.page_name="未知";
            }
            var myDate = new Date();
            addObj["created_year"] = myDate.getFullYear();
            addObj["created_month"] =myDate.getMonth()+1;
            addObj["created_day"] =myDate.getDate();
            addObj["created_date"]=myDate.getTime();
            if(pobj.clientIp){
                addObj.clientIp= pobj.clientIp;
                var list = await this.getbrowsingrecordlist(pobj.clientIp,myDate.getTime());
                if(list && list.length>=60){
                    addObj.is_warning=1;
                }
            }
            var res = await this.execClient.execPostEs(addObj, this.mediabrowsingRecordsLogUrl);
        }
        return system.getResultSuccess();
    }


    async getbrowsingrecordlist(ip,time){
        time = time - 60*1000;
        var queryObj={
            "query": {
              "bool": {
                "must": [
                  {
                    "term": {
                      "clientIp": ip
                    }
                  },
                  {
                    "range": {
                      "created_date": {
                        "gte": time
                      }
                    }
                  }
                ],
                "must_not": [],
                "should": []
              }
            },
            "from": 0,
            "size": 60,
            "sort": [],
            "aggs": {}
        };
        var res = await this.execClient.execPostEs(queryObj, "http://43.247.184.94:7200/marketmedia_browsingrecords_log/_search");
        if(res && res.stdout){
            res = JSON.parse(res.stdout);
            if(res.hits && res.hits.hits){
                return res.hits.hits;
            }
        }
        return null;
    }
}

module.exports = NeedinfoService;