package mobvista.dmp.datasource.id_mapping

import mobvista.dmp.datasource.id_mapping.Constant.{getDevId, parseUA, process}
import org.apache.commons.lang3.StringUtils
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{Row, SparkSession}

/**
 * @package: mobvista.dmp.datasource.id_mapping
 * @author: wangjf
 * @date: 2021/11/30
 * @time: 7:51 下午
 * @email: jinfeng.wang@mobvista.com
 */
class AdnRequest extends EtlDeviceIdDaily {

  override def processData(date: String, i: Int, spark: SparkSession): RDD[(String, Row)] = {
    spark.udf.register("getDevId", getDevId _)
    spark.udf.register("parseUA", parseUA _)

    val year = date.substring(0, 4)
    val month = date.substring(4, 6)
    val day = date.substring(6, 8)

    //  DWD
    //  val sql = Constant.adn_request_sql.replace("@date", date)
    //  ODS
    val sql = Constant.adn_request_sql_v3
      .replace("@year", year)
      .replace("@month", month)
      .replace("@day", day)
    val rdd = spark.sql(sql).coalesce(20000).rdd.map(row => {
      val gaid = row.getAs[String]("gaid")
      val idfa = row.getAs[String]("idfa")
      val imei = row.getAs[String]("imei")
      val androidId = row.getAs[String]("androidid")
      val extSysid = row.getAs[String]("extsysid")
      val platform = row.getAs[String]("platform")
      val oaid = row.getAs[String]("oaid")
      val idfv = row.getAs[String]("idfv")
      val pkg_name = row.getAs[String]("pkg_name")
      val country = row.getAs[String]("country")
      val ip = row.getAs[String]("ip")
      val ua = row.getAs[String]("ua")
      val brand = row.getAs[String]("brand")
      val model = row.getAs[String]("model")
      val os_version = row.getAs[String]("os_version")
      val osv_upt = row.getAs[String]("osv_upt")
      val upt = row.getAs[String]("upt")
      val network_type = row.getAs[String]("network_type")
      val cnt = row.getAs[Long]("cnt")
      var sysId = ""
      var bkupId = ""
      if (StringUtils.isNotBlank(extSysid)) {
        val arr = extSysid.split(",", -1)
        sysId = if (StringUtils.isNotBlank(arr(0))) {
          arr(0)
        } else {
          ""
        }
        bkupId = if (arr.length == 2 && StringUtils.isNotBlank(arr(1))) {
          arr(1)
        } else {
          ""
        }
      }
      process(idfa, idfv, pkg_name, imei, androidId, oaid, gaid, sysId, bkupId, country, ip, ua, brand, model, os_version,
        osv_upt, upt, network_type, platform, cnt)
    })
    rdd
  }
}

object AdnRequest {
  def main(args: Array[String]): Unit = {
    new AdnRequest().run(args)
  }
}