package mobvista.dmp.datasource.reyun

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

import java.net.URI

/**
 * @author jiangfan
 * @date 2021/5/25 11:50
 */
class ReyunDaily extends CommonSparkJob with Serializable{
  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("coalesce", true, "[must] coalesce")
    options.addOption("output", true, "[must] output")
    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 output = commandLine.getOptionValue("output")
    val dt_today = commandLine.getOptionValue("dt_today")

    val spark = SparkSession.builder()
      .appName("ReyunDaily")
      .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(output), true)
    val Delimiter01="\u0006"
    val Delimiter02="\u0005"

    try {
      val sql1=
        s"""
           |select  t2.device_id,t2.device_type,case when t2.platform is not null then t2.platform else 'android' end as  platform,  t2.package_name,'cn' country  from
           |(select t1.device_id,
           |case when t1.tmp_device_type='imei2' and t1.device_id rlike  '${imeiPtn}' then 'imei'
           |when t1.tmp_device_type='_imei' and t1.device_id rlike  '${imeiPtn}' then 'imei'
           |when t1.tmp_device_type='oaid' and (t1.device_id rlike '${didPtn}' or t1.device_id rlike  '${oaidAnotherPtn}' ) then 'oaid'
           |when t1.tmp_device_type='androidid' and t1.device_id rlike '${andriodIdPtn}' then 'androidid'
           |end  as device_type,
           |t1.platform,
           |t1.package_name
           | from
           |(select nvl(xcontext['_deviceid'],xcontext['deviceid']) as device_id,
           | case when nvl(xcontext['_deviceid'],xcontext['deviceid']) = xcontext['_imei2'] then 'imei2'
           | when nvl(xcontext['_deviceid'],xcontext['deviceid']) = xcontext['_meid'] then 'meid'
           | when nvl(xcontext['_deviceid'],xcontext['deviceid']) = xcontext['_oaid'] then 'oaid'
           | when nvl(xcontext['_deviceid'],xcontext['deviceid']) = xcontext['_androidid'] then 'androidid'
           | else '_imei' end as tmp_device_type,
           | xcontext['_ryos'] platform,
           | package_name
           | from reyun.pkginfo
           | LATERAL VIEW explode(str_to_map(xcontext['pkglist'],'\u0006','\u0005')) tmp01 AS package_name,value  where ds='${dt_today}' )  t1)  t2
           | where t2.device_type is not null
        """.stripMargin


      spark.sql(sql1).createOrReplaceTempView("reyun_daily_origin")
      val sql2=
        s"""
           |select
           |device_id,
           |device_type,
           |platform,
           |package_name,
           |country
           |from reyun_daily_origin
           |union
           |select
           |device_id,
           |device_type,
           |platform,
           |concat(package_name,"_",device_type,"_reyun") package_name,
           |country
           |from reyun_daily_origin
           |where package_name in ("com.taobao.taobao","com.sankuai.meituan","com.eg.android.AlipayGphone")
           |   and  device_type in ("imei","oaid")
        """.stripMargin

      spark.sql(sql2).coalesce(coalesce.toInt)
        .write
        .mode(SaveMode.Overwrite)
        .option("orc.compress", "zlib")
        .option("mapreduce.fileoutputcommitter.marksuccessfuljobs", false)
        .orc(output)

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

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