const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const zhugeBaseUrl = "https://api.zhugeio.com/v2/stat/96223";
class DatastatisticService extends ServiceBase {
  constructor() {
    super("aggregation", ServiceBase.getDaoName(DatastatisticService));
    this.zhugeClient = system.getObject("util.zhugeClient");
    this.logClient = system.getObject("util.logClient");
    this.launchchannelDao = system.getObject("db.configmag.launchchannelDao");
  }
  async findAndCountAll(obj) {
    var sta_date=null;
    var sqlParams={};
    if(obj && obj.search && obj.search.statistic_date){
      sta_date = obj.search.statistic_date;
      if(sta_date[0]){
        sta_date[0]= await this.dateConvert2String(sta_date[0]);
        sqlParams["startDate"]=sta_date[0];
      }
      if(sta_date[1]){
        sta_date[1]= await this.dateConvert2String(sta_date[1]);
        sqlParams["endDate"]=sta_date[1];
      }
      obj.search.statistic_date=sta_date;
    }
    const apps = await this.dao.findAndCountAll(obj);
    if(apps && apps.results && apps.results.rows && apps.results.rows.length>0){
      var sql = "SELECT channel_code, sub_date, count(distinct contact_mobile) as user_count, sum( sub_success ) as sub_count, sum( push_success ) as push_count "+
      " FROM ( "+
      " SELECT IF ( sub_status = 1, 1, 0 ) AS sub_success, IF ( push_status = 1, 1, 0 ) AS push_success, contact_mobile, channel_code, "+
      " DATE_FORMAT(created_at,'%Y%m%d') as sub_date FROM `mc_need_info`  ) AS data_source where 1=1 ";
      if(sqlParams.startDate && sqlParams.endDate){
        sql = sql+" and (sub_date between :startDate and :endDate ) ";
      }
      if(obj.search && obj.search.channel_code){
        sqlParams.channel_code = obj.search.channel_code
        sql = sql+" and (channel_code = :channel_code ) ";
      }
      sql=sql+" GROUP BY channel_code,sub_date ";
      var countList = await this.dao.customQuery(sql,sqlParams);
      for(var i=0;i<apps.results.rows.length;i++){
        var row = apps.results.rows[i].dataValues;
        for(var j=0;j<countList.length;j++){
          var countObj = countList[j];
          if(countObj.channel_code == row.channel_code && countObj.sub_date == row.statistic_date){
            row.sub_count=countObj.sub_count;
            row.push_count = countObj.push_count;
            row.customer_count = countObj.user_count;
          }
        }
      }
    }
    return apps;
  }
  async stringConvert2Date(dateString){

  }
  async dateConvert2String(d){
    var date = new Date(d);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var dateStr = year + "" + month + "" + day;
    return dateStr;
  }
  /**
   * 通过诸葛io同步统计数据
   */
  async synchronizeStatisticDataByZhugeIO(){
      var channelList = await this.launchchannelDao.model.findAll({
        raw:true,
        attributes:["code","name"],
      });
      var channelObj={};
      for(var z=0;z<channelList.length;z++){
        var channel = channelList[z];
        if(channel.code && channel.name){
          channelObj[channel.code]= channel.name;
        }
      }
      if(channelObj && Object.keys(channelObj).length>0){
        var occurrencesList = await this.getOccurrences();
        console.log(occurrencesList,"occurrencesList++++++++++++");
        for(var i=0;i<occurrencesList.length;i++){
          var event = occurrencesList[i];
          if(event.day && event.utm_source && channelObj[event.utm_source]){
            event.occurrences2= event.occurrences;
            event.channel_name= channelObj[event.utm_source];
            var sql = "INSERT INTO `mc_data_statistic` ( statistic_date, channel_code,channel_name, pv ) VALUES (:day,:utm_source,:channel_name,:occurrences) ON DUPLICATE KEY UPDATE pv = :occurrences2";
            var res = await this.dao.customInsert(sql,event);
            console.log(res,"11111111:"+event.day+","+event.utm_source+","+event.occurrences);
          }
          
        }
        var userList = await this.getUsers();
        console.log(userList);
        for(var a=0;a<userList.length;a++){
          var event = userList[a];
          if(event.day && event.utm_source && channelObj[event.utm_source]){
            event.users2= event.users;
            event.channel_name= channelObj[event.utm_source];
            var sql = "INSERT INTO `mc_data_statistic` ( statistic_date, channel_code,channel_name, uv ) VALUES (:day,:utm_source,:channel_name,:users) ON DUPLICATE KEY UPDATE uv = :users2";
            var res = await this.dao.customInsert(sql,event);
            console.log(res,"2222222:"+event.day+","+event.utm_source+","+event.users);
          }
          
        }
      }
      
      return channelList;
  }
  /**
   * 通过解析Excel文件同步统计数据
   */
  async synchronizeStatisticDataByExcel(){
      // 1、日期判断，判断文件中的日期不能超过当前日期（且不包含当前日期）
      // 2、判断渠道信息，获取全部渠道信息，只保存有效数据
      // 3、判断统计数据类型 PV UV 
  }
  //获取事件触发次数
  async getOccurrences(){
      try {
          var url = zhugeBaseUrl+"?metrics=occurrences&dimensions=$day,$utm_source";
          var rtn = await this.zhugeClient.execGet(null,url);
          console.log(rtn,"rtn+++++++++++++++++++++++++++++++++++++")
          this.logClient.pushlog("获取诸葛IO事件触发次数返回结果-getOccurrences",null, rtn, null);
          if(rtn && rtn.stdout){
              var res = JSON.parse(rtn.stdout);
              if(res && res.code==10001 && res.data){
                  var dataList = res.data.results;
                  return dataList;
              }
          }
          return null;
          
      } catch (e) {
          // this.logClient.pushlog("获取诸葛IO事件触发次数返回异常-getOccurrences",null, e, null);
          console.log(e);
          return null;
      }
      
  }
  //获取活跃用户数量
  async getUsers(){
      try {
          var url = zhugeBaseUrl+"?metrics=users&dimensions=$day,$utm_source";
          var rtn = await this.zhugeClient.execGet(null,url);
          console.log(rtn,"rtn+++++++++++++++++++++++++++++++++++++")
          // this.logClient.pushlog("获取诸葛IO活跃用户数量返回结果-getUsers",null, rtn, null);
          if(rtn && rtn.stdout){
              var res = JSON.parse(rtn.stdout);
              if(res && res.code==10001 && res.data){
                  var dataList = res.data.results;
                  return dataList;
              }
          }
          return null;
      } catch (e) {
        // this.logClient.pushlog("获取诸葛IO活跃用户数量返回异常-getUsers",null, e, null);
        console.log(e);
        return null;
      }
      
  }
}
module.exports = DatastatisticService;
// var task = new DatastatisticService();
// task.dateConvert2String(null).then(d=>{
//   console.log(d,"-----end--------------------");
// })