package mobvista.dmp.datasource.taobao

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.SparkSession

class YoukuLaXinPollingDataDeduplication extends CommonSparkJob with Serializable {
  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("dt_today", true, "[must] dt_today")
    options.addOption("dt_begin_days", true, "[must] dt_begin_days")
    options.addOption("AcquisitionOutput", true, "[must] AcquisitionOutput")
    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 dt_today = commandLine.getOptionValue("dt_today")
    val dt_begin_days = commandLine.getOptionValue("dt_begin_days")
    val AcquisitionOutput = commandLine.getOptionValue("AcquisitionOutput")


    val spark = SparkSession.builder()
      .appName("YoukuLaXinPollingDataDeduplication")
      .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()

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

    try {
      val sql1=
        s"""
           |select XX.device_id,XX.device_type,XX.platform,XX.package_name,XX.update_date
           |FROM (select X.device_id,X.device_type,X.platform,X.package_name,X.update_date,
           |rank() over(partition by X.device_id order by X.update_date desc) rk
           |from (     select device_id,device_type,platform,package_name,update_date
           |             from dwh.youku_laxin_tmp_daily_to_s3
           |      where  business="youku_acquisition" and dt<='${dt_today}' and dt>='${dt_begin_days}'
           |	  ) X ) XX
           | WHERE XX.rk= 1
        """.stripMargin

      spark.sql(sql1).repartition(500).rdd.map(_.mkString("\t")).coalesce(100).saveAsTextFile(AcquisitionOutput)

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

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