package mobvista.dmp.datasource.device

import java.net.URI

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

/**
  * @package: mobvista.dmp.datasource.device
  * @author: wangjf
  * @create: 2018-09-11 15:03
  **/
class FixOdsDmpUserInfo extends CommonSparkJob with Serializable {
  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 date = commandLine.getOptionValue("date")
    val business = commandLine.getOptionValue("business")
    val output = commandLine.getOptionValue("output")
    val compression = commandLine.getOptionValue("compression", "zlib")

    val spark = SparkSession.builder()
      .appName("FixOdsDmpUserInfo." + date + "." + business)
      .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()
    val sc = spark.sparkContext

    FileSystem.get(new URI(s"s3://mob-emr-test"), sc.hadoopConfiguration).delete(new Path(output), true)
    try {
      val sql = Constant.ods_dmp_user_info_sql.replace("@dt", date).replace("@business", business)
      val df = spark.sql(sql)
        .toDF()
        .sortWithinPartitions("device_id")
        .dropDuplicates

      df.write
        .mode(SaveMode.Overwrite)
        .option("orc.compress", compression)
        .orc(output)

      /*
      val part =
        s"""
           |dt = '${date}', business = '${business}'
        """.stripMargin
      val alter_partition_sql = Constant.alter_partition.replace("@table", "ods_dmp_user_info")
        .replace("@part", part).replace("@location", output)
      println("alter_partition_sql === " + alter_partition_sql)
      spark.sql(alter_partition_sql)
      */
    } finally {
      sc.stop()
      spark.stop()
    }
    0
  }

  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("date", true, "[must] date")
    options.addOption("output", true, "[must] output")
    options.addOption("business", true, "[must] business")
    options.addOption("compression", true, "compression type")
    options
  }
}

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