package mobvista.dmp.datasource.toutiao

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

/**
  * @package: mobvista.dmp.datasource.toutiao
  * @author: wangjf
  * @create: 2018-12-05 15:35:44
  **/
class ToutiaoCase 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 output = commandLine.getOptionValue("output")

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

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

    try {

      val sql =
        s"""
           |SELECT device_id,tag_type,first_tag,second_tag,cnt FROM dwh.dm_device_tag_statistics WHERE dt = '20190226' AND MD5(UPPER(device_id)) IN ('51629eb681bdd088ccc5635d9b685cdb','00008d819882008613553e6384659e4b')
        """.stripMargin
      //
      spark.sql(sql).rdd.repartition(1).saveAsTextFile(output)
      //  不压缩，因头条仅支持 zip 格式上传解析

    } finally {
      if (spark != null) {
        spark.stop()
      }
    }
    0
  }

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

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