package mobvista.dmp.datasource.id_mapping

import mobvista.dmp.common.{CommonSparkJob, MobvistaConstant}
import mobvista.dmp.datasource.id_mapping.Constant._
import org.apache.commons.cli.{BasicParser, Options}
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.{Row, SaveMode, SparkSession}
import org.apache.spark.storage.StorageLevel

import java.net.URI

/**
 * @package: mobvista.dmp.datasource.id_mapping
 * @author: wangjf
 * @date: 2021/11/30
 * @time: 10:35 上午
 * @email: jinfeng.wang@mobvista.com
 */
abstract class EtlDeviceIdDaily extends CommonSparkJob with Serializable {
  def commandOptions(): Options = {
    val options = new Options()
    options.addOption("business", true, "business")
    options.addOption("date", true, "date")
    options.addOption("output", true, "output")
    options.addOption("coalesce", true, "coalesce")
    options
  }

  override protected def run(args: Array[String]): Int = {
    val parser = new BasicParser()
    val options = commandOptions()
    val commandLine = parser.parse(options, args)
    val date = commandLine.getOptionValue("date")
    val business = commandLine.getOptionValue("business")
    val output = commandLine.getOptionValue("output")
    val coalesce = Integer.parseInt(commandLine.getOptionValue("coalesce"))

    val spark = MobvistaConstant.createSparkSession(s"EtlDeviceIdDaily.$business.$date")

    try {
      if ("dsp_req".equalsIgnoreCase(business)) {
        for (i <- 0 until 4) {
          val df = processData(date, i, spark)
            .repartition(20000)
            .persist(StorageLevel.MEMORY_AND_DISK_SER)

          val iosTab = df.filter(plf => {
            "ios".equals(plf._1)
          }).map(row => {
            row._2
          })
          FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(output + s"/ios/${i}"), true)

          spark.createDataFrame(iosTab, iosSchema)
            .coalesce(coalesce)
            .write.mode(SaveMode.Overwrite)
            .option("orc.compress", "zlib")
            .orc(output + s"/ios/${i}")

          val adrTab = df.filter(plf => {
            "android".equals(plf._1)
          }).map(row => {
            row._2
          })

          FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(output + s"/android/${i}"), true)

          spark.createDataFrame(adrTab, adrSchema)
            .coalesce(coalesce)
            .write.mode(SaveMode.Overwrite)
            .option("orc.compress", "zlib")
            .orc(output + s"/android/${i}")

          df.unpersist(true)
        }
      } else {
        val df = processData(date, 0, spark)
          .repartition(20000)
          .persist(StorageLevel.MEMORY_AND_DISK_SER)

        val iosTab = df.filter(plf => {
          "ios".equals(plf._1)
        }).map(row => {
          row._2
        })
        FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(output + "/ios"), true)

        spark.createDataFrame(iosTab, iosSchema)
          .coalesce(coalesce)
          .write.mode(SaveMode.Overwrite)
          .option("orc.compress", "zlib")
          .orc(output + "/ios")

        val adrTab = df.filter(plf => {
          "android".equals(plf._1)
        }).map(row => {
          row._2
        })

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

        spark.createDataFrame(adrTab, adrSchema)
          .coalesce(coalesce)
          .write.mode(SaveMode.Overwrite)
          .option("orc.compress", "zlib")
          .orc(output + s"/android")
      }
    } finally {
      if (spark != null) {
        spark.stop()
      }
    }
    0
  }

  def processData(date: String, i: Int, spark: SparkSession): RDD[(String, Row)]
}