package mobvista.dmp.datasource.taobao

import mobvista.dmp.common.CommonSparkJob
import org.apache.commons.cli.Options
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.sql.{DataFrame, SparkSession}
import org.apache.spark.storage.StorageLevel

import java.net.URI

/**
 * @author jiangfan
 * @date 2021/8/5 14:38
 */

class  EtlLazadaIosActivitionDaily  extends CommonSparkJob  {
  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("vn_idfaoutput", true, "[must] vn_idfaoutput")
    options.addOption("today", true, "[must] today")
    options.addOption("last_req_day", true, "[must] last_req_day")
    options
  }



  override protected def run(args: Array[String]): Int = {
    val commandLine = commParser.parse(options, args)
    if (!checkMustOption(commandLine)) {
      printUsage(options)
      return -1
    } else printOptions(commandLine)

    val today = commandLine.getOptionValue("today")
    val vn_idfaoutput = commandLine.getOptionValue("vn_idfaoutput")
    val last_req_day = commandLine.getOptionValue("last_req_day")


    val spark = SparkSession.builder()
      .appName("EtlLazadaIosActivitionDaily")
      .config("spark.rdd.compress", "true")
      .config("spark.io.compression.codec", "snappy")
      .config("spark.sql.orc.filterPushdown", "true")
      .config("spark.sql.warehouse.dir", "s3://mob-emr-test/spark-warehouse")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .enableHiveSupport()
      .getOrCreate()

    import spark.implicits._

    FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(vn_idfaoutput), true)

    try {

      val sql2=
        s"""
           |select lower(device_id) device_id,lower(country) country
           |from dwh.ods_dmp_user_info where dt = '${today}' and last_req_day >= '${last_req_day}' and business not in ('other', 'ali_acquisition', 'ali_activation', 'adn_install')
           | and device_type='idfa'
           | and platform='ios'
           | group by lower(device_id),lower(country)
        """.stripMargin

      val dfCache: DataFrame = spark.sql(sql2).persist(StorageLevel.MEMORY_AND_DISK_SER)

      dfCache.rdd.filter(_.getAs[String]("country").toUpperCase() == "VN").map(_.getAs[String]("device_id")).coalesce(60).saveAsTextFile(vn_idfaoutput)


    } finally {
      spark.stop()
    }
    0
  }
}

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