package mobvista.dmp.datasource.dm

import mobvista.dmp.common.CommonSparkJob
import mobvista.dmp.format.TextMultipleOutputFormat
import org.apache.commons.cli.Options
import org.apache.commons.lang.StringUtils
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.hadoop.io.Text
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.sql.{DataFrame, Row, SparkSession}
import org.apache.spark.sql.functions.{concat_ws, lit}
import org.apache.spark.storage.StorageLevel

import java.net.URI
import scala.collection.mutable.ArrayBuffer

/**
 * @author jiangfan
 * @date 2021/8/19 14:17
 */

class ComEgAndroidAlipayGphoneReyun 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("output2", true, "[must] output2")
    options.addOption("output3", true, "[must] output3")
    options.addOption("output4", true, "[must] output4")
    options.addOption("output5", true, "[must] output5")
    options.addOption("dt_today", true, "[must] dt_today")
    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 output2 = commandLine.getOptionValue("output2")
    val output3 = commandLine.getOptionValue("output3")
    val output4 = commandLine.getOptionValue("output4")
    val output5 = commandLine.getOptionValue("output5")
    val dt_today = commandLine.getOptionValue("dt_today")

    val spark = SparkSession.builder()
      .appName("ComEgAndroidAlipayGphoneReyun")
      .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
    import spark.implicits._

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

    try {
      val sql1=
        s"""
           |select device_id, device_type from dwh.dm_install_list_v2  where dt='${dt_today}' and business='reyun' and package_name='com.eg.android.AlipayGphone' and device_type not in ('androidid','android_id')
        """.stripMargin

      spark.sql(sql1).rdd.flatMap(buildRes(_)).coalesce(coalesce.toInt)
        .saveAsNewAPIHadoopFile(s"${output1}", classOf[Text], classOf[Text], classOf[TextMultipleOutputFormat], spark.sparkContext.hadoopConfiguration)

      val sql2=
        s"""
           |select device_id, device_type from dwh.dm_install_list_v2  where dt='${dt_today}' and business='reyun' and package_name='com.taobao.litetao' and device_type not in ('androidid','android_id')
        """.stripMargin

      spark.sql(sql2).rdd.flatMap(buildRes(_)).coalesce(coalesce.toInt)
        .saveAsNewAPIHadoopFile(s"${output2}", classOf[Text], classOf[Text], classOf[TextMultipleOutputFormat], spark.sparkContext.hadoopConfiguration)

      val sql3=
        s"""
           |select device_id, device_type from dwh.dm_install_list_v2  where dt='${dt_today}' and business='reyun' and package_name='com.ss.android.ugc.aweme' and device_type not in ('androidid','android_id')
        """.stripMargin

      spark.sql(sql3).rdd.flatMap(buildRes(_)).coalesce(coalesce.toInt)
        .saveAsNewAPIHadoopFile(s"${output3}", classOf[Text], classOf[Text], classOf[TextMultipleOutputFormat], spark.sparkContext.hadoopConfiguration)

      val sql4=
        s"""
           |select device_id, device_type from dwh.dm_install_list_v2  where dt='${dt_today}' and business='btop' and package_name='com.taobao.litetao' and device_type not in ('androidid','android_id')
        """.stripMargin

      spark.sql(sql4).rdd.flatMap(buildRes(_)).coalesce(coalesce.toInt)
        .saveAsNewAPIHadoopFile(s"${output4}", classOf[Text], classOf[Text], classOf[TextMultipleOutputFormat], spark.sparkContext.hadoopConfiguration)

      val sql5=
        s"""
           |select device_id, device_type from dwh.dm_install_list_v2  where dt='${dt_today}' and business='btop' and package_name='com.ss.android.ugc.aweme' and device_type not in ('androidid','android_id')
        """.stripMargin

      spark.sql(sql5).rdd.flatMap(buildRes(_)).coalesce(coalesce.toInt)
        .saveAsNewAPIHadoopFile(s"${output5}", classOf[Text], classOf[Text], classOf[TextMultipleOutputFormat], spark.sparkContext.hadoopConfiguration)

    } finally {
      spark.stop()
    }
    0
  }

  def buildRes( row: Row): Array[Tuple2[Text, Text]] = {
    val buffer = new ArrayBuffer[Tuple2[Text, Text]]()
    val device_id = row.getAs[String]("device_id")
    val device_type = row.getAs[String]("device_type")
    if (StringUtils.isNotBlank(device_type)) {
      buffer += Tuple2(new Text(s"${device_type}, "), new Text(device_id))
    }
    buffer.toArray
  }
}


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