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 6) {
          val df = processData(date, i, spark)
            .repartition(coalesce)
          df.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)
            .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)
            .write.mode(SaveMode.Overwrite)
            .option("orc.compress", "zlib")
            .orc(output + s"/android/${i}")

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

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

          spark.createDataFrame(otherTab, otherSchema)
            .write.mode(SaveMode.Overwrite)
            .option("orc.compress", "zlib")
            .orc(output + s"/other/${i}")

          df.unpersist(true)
        }
      } else {
        val df = processData(date, 0, spark)
          .repartition(coalesce)
        df.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)
          .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)
          .write.mode(SaveMode.Overwrite)
          .option("orc.compress", "zlib")
          .orc(output + s"/android")

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

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

        spark.createDataFrame(otherTab, otherSchema)
          .write.mode(SaveMode.Overwrite)
          .option("orc.compress", "zlib")
          .orc(output + s"/other")
      }
      spark.sql(
        s"""
           |ALTER TABLE dws.dws_device_id_ios_frequency ADD IF NOT EXISTS PARTITION (dt='$date',source='${business}')
           | LOCATION '$output/ios'
           |""".stripMargin)

      spark.sql(
        s"""
           |ALTER TABLE dws.dws_device_id_android_frequency ADD IF NOT EXISTS PARTITION (dt='$date',source='${business}')
           | LOCATION '$output/android'
           |""".stripMargin)
    } finally {
      if (spark != null) {
        spark.stop()
      }
    }
    0
  }

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