package mobvista.dmp.datasource.iqiyi

import mobvista.dmp.common.CommonSparkJob
import mobvista.dmp.util.PropertyUtil
import mobvista.dmp.utils.clickhouse.ClickHouseConnectionFactory
import mobvista.dmp.utils.clickhouse.ClickHouseSparkExt._
import org.apache.commons.cli.Options
import org.apache.commons.lang3.StringUtils
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.types.{StringType, StructField, StructType}
import ru.yandex.clickhouse.ClickHouseDataSource

/**
  * @package: mobvista.dmp.datasource.iqiyi
  * @author: wangjf
  * @date: 2020/4/29
  * @time: 11:52 上午
  * @email: jinfeng.wang@mobvista.com
  * @phone: 152-1062-7698
  */
class IQiYiEtl2CK 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 date = commandLine.getOptionValue("date")
    val cluster = commandLine.getOptionValue("cluster")
    val host = commandLine.getOptionValue("host")
    val database = commandLine.getOptionValue("database")
    val table = commandLine.getOptionValue("table")

    val spark = SparkSession
      .builder()
      .appName(s"IQiYiEtl2CK.$date")
      .config("spark.rdd.compress", "true")
      .config("spark.io.compression.codec", "lz4")
      .config("spark.sql.warehouse.dir", "s3://mob-emr-test/spark-warehouse")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .config("spark.clickhouse.driver", "ru.yandex.clickhouse.ClickHouseDriver")
      .config("spark.clickhouse.url", PropertyUtil.getProperty("config.properties", "spark.clickhouse.url"))
      .config("spark.clickhouse.connection.per.executor.max", "5")
      .config("spark.clickhouse.metrics.enable", "true")
      .config("spark.clickhouse.socket.timeout.ms", "300000")
      .config("spark.clickhouse.cluster.auto-discovery", "true")
      .enableHiveSupport()
      .getOrCreate()
    val sc = spark.sparkContext

    val clusterName = cluster
    spark.udf.register("hasNoAny", hasNoAny _)
    try {
      val df = spark.sql(sql.replace("@date", date)).rdd

      val update_date = mobvista.dmp.common.MobvistaConstant.sdf1.format(mobvista.dmp.common.MobvistaConstant.sdf2.parse(date))

      implicit val clickHouseDataSource: ClickHouseDataSource = ClickHouseConnectionFactory.get(host)
      spark.createDataFrame(df, schema).saveToClickHouse(database, table, Seq(update_date), Seq("dt"), Some(clusterName), batchSize = 1000000)
    } finally {
      sc.stop()
      spark.stop()
    }
    0
  }

  val schema = StructType(Array(
    StructField("device_id", StringType),
    StructField("device_type", StringType),
    StructField("platform", StringType)))

  val sql =
    s"""
       |SELECT CASE WHEN platform = 'ios' THEN UPPER(dev_id) ELSE dev_id END device_id, dev_type device_type, platform platform
       |  FROM dwh.ods_dmp_user_info_daily WHERE dt = '@date' AND UPPER(country) = 'CN' AND dev_type IN ('idfa','imei')
       |  AND hasNoAny(install)
    """.stripMargin

  val set = Set("com.iqiyi.tag", "com.iqiyi.k12", "com.iqiyi.english", "00000002220", "00000002221", "00000002222")

  def hasNoAny(install: String): Boolean = {
    var flag = true
    val itr = install.toLowerCase.split(",").iterator
    while (itr.hasNext && flag) {
      val ir = itr.next
      val rs = ir.split("\\|")
      if (StringUtils.isNotBlank(ir) && set.contains(rs(0))) {
        flag = false
      }
    }
    flag
  }

  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("date", true, "date")
    options.addOption("host", true, "host")
    options.addOption("cluster", true, "cluster")
    options.addOption("database", true, "database")
    options.addOption("table", true, "table")
    options
  }
}

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