package mobvista.dmp.datasource.id_mapping

import mobvista.dmp.datasource.id_mapping.Constant.{getDevId, parseUA}
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 _)
    //  DWD
    //  val sql = Constant.adn_request_sql.replace("@date", date)
    //  ODS
    val sql = Constant.adn_request_sql_v2.replace("@date", date)
    val rdd = spark.sql(sql).coalesce(2000).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")
      var platform = row.getAs[String]("platform")
      platform = if (StringUtils.isNotBlank(platform)) {
        platform.toLowerCase()
      } else {
        ""
      }
      val oaid = row.getAs[String]("oaid")
      val idfv = row.getAs[String]("idfv")
      var 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")
      country = if (StringUtils.isNotBlank(country)) {
        country.toUpperCase()
      } else {
        ""
      }
      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 {
          ""
        }
      }
      val rw = if ("ios".equalsIgnoreCase(platform)) {
        Row(idfa, idfv, sysId, bkupId, "", "", country, ip, ua, brand, model, os_version, osv_upt, upt)
      } else {
        Row(imei, androidId, oaid, gaid, sysId, bkupId, "", "", country, ip, ua, brand, model, os_version, osv_upt, upt)
      }
      (platform, rw)
    })
    rdd
  }
}

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