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;
          }
        }
        var zhl = 0;
        if(!row["sub_count"] || row["sub_count"]==0 || !row["uv"] ||row["uv"]==0){
          zhl = 0;
        }else{
          zhl = Number(row["sub_count"]) / Number(row["uv"])*100;
        }
        zhl = zhl.toFixed(2);
        row.zhl = zhl+"%";
      }
    }
    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(){
    console.log("synchronizeStatisticDataByZhugeIO---------------"+new Date());
      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 date = this.fun_date(-7); 
          var url = zhugeBaseUrl+"?metrics=occurrences&dimensions=$day,$utm_source&conditions=%7B%22$day%22:%5B%22%3E=%22,%22"+date+"%22%5D%7D";
          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 date = this.fun_date(-7); 
          var url = zhugeBaseUrl+"?metrics=users&dimensions=$day,$utm_source&conditions=%7B%22$day%22:%5B%22%3E=%22,%22"+date+"%22%5D%7D";
          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;
      }
      
  }

  fun_date(aa){
      var date1 = new Date(),
      time1=date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate();//time1表示当前时间
      var date2 = new Date(date1);
      date2.setDate(date1.getDate()+aa);
      var year = date2.getFullYear();
      var month = date2.getMonth()+1;
      if(month<10){
        month="0"+month;
      };
      var day = date2.getDate();
      if(day<10){
        day="0"+day;
      }
      var time2 = year+"-"+month+"-"+day;
      return time2;
  }
}
module.exports = DatastatisticService;
// var task = new DatastatisticService();
// task.synchronizeStatisticDataByZhugeIO().then(d=>{
//   console.log(d,"-----end--------------------");
// })