package mobvista.dmp.datasource.dm

import mobvista.dmp.common.CommonSparkJob
import mobvista.dmp.format.{RDDMultipleOutputFormat, TextMultipleOutputFormat}
import org.apache.commons.cli.Options
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.hadoop.io.SequenceFile.CompressionType
import org.apache.hadoop.io.Text
import org.apache.hadoop.io.compress.{CompressionCodec, GzipCodec}
import org.apache.spark.sql.SparkSession

import java.net.URI

/**
 * @author jiangfan
 * @date 2021/9/10 14:27
 */

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

    val spark = SparkSession.builder()
      .appName("AdxPackagenameSynchronize")
      .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 conf = spark.sparkContext.hadoopConfiguration
    conf.set("mapreduce.output.compress", "true")
    conf.set("mapreduce.output.compression.codec", "org.apache.hadoop.io.compress.GzipCodec")
    conf.setBoolean("mapreduce.output.fileoutputformat.compress", true)
    conf.set("mapreduce.output.fileoutputformat.compress.type", CompressionType.BLOCK.toString)
    conf.setClass("mapreduce.output.fileoutputformat.compress.codec", classOf[GzipCodec], classOf[CompressionCodec])

    val sc = spark.sparkContext
    import spark.implicits._

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


    try {
      val sql1=
        s"""
           |select package_name, device_type, device_id  from dwh.dm_install_list_v2  where dt='${dt_today}' and business='dsp_req'
           |  and package_name in ('3876827262021090301','id3876827262021090301',
           |  '3332062892021090301','id3332062892021090301',
           |  '13403763232021090301','id13403763232021090301',
           |  '10442830592021090301','id10442830592021090301',
           |  'com.xunmeng.pinduoduo_bes',
           |  'com.ss.android.ugc.aweme_iqiyi',
           |  '11421108952021090302','id11421108952021090302',
           |  'com.xunmeng.pinduoduo_oppoziyou',
           |  'com.xunmeng.pinduoduo_oppoziyou_notinstall',
           |  'com.xunmeng.pinduoduo_oppoziyou_hist_notinstall',
           |  'com.xunmeng.pinduoduo_oppolianmeng',
           |  'com.xunmeng.pinduoduo_oppolianmeng_hist1year_notinstall',
           |  'com.xunmeng.pinduoduo_oppolianmeng_histhalfyear_notinstall'
           |  )
           |  and device_type  in ('imei','gaid','oaid','idfa','imeimd5','gaidmd5','oaidmd5','idfamd5')
           |union
           |select package_name, device_type, device_id  from dwh.dm_install_list_v2  where ( (dt='${dt_today}'  and business in ('btop'))  or  (dt='${dt_day}'  and business in ('TO')) )
           | and package_name in ('com.xunmeng.pinduoduo')
           | and device_type  in ('imei','gaid','oaid','idfa','imeimd5','gaidmd5','oaidmd5','idfamd5')
        """.stripMargin


      spark.sql(sql1).rdd.map(r => {
        val device_id = r.getAs[String]("device_id")
        val device_type = r.getAs[String]("device_type")
        var package_name = r.getAs[String]("package_name")
        if(package_name.matches("^\\d+$"))
          package_name="id"+package_name

        (device_id, device_type,  package_name)
      })
        .coalesce(coalesce.toInt).map(t => {
        (new Text(s"${output1}/${t._3}/${t._2}"), new Text(t._1))
      }).saveAsNewAPIHadoopFile(output1, classOf[Text], classOf[Text], classOf[RDDMultipleOutputFormat[_, _]], conf)

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

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