package mobvista.dmp.clickhouse.feature

import java.text.SimpleDateFormat

import mobvista.dmp.util.MySQLUtil
import mobvista.dmp.utils.clickhouse.ClickHouseConnectionFactory
import mobvista.dmp.utils.clickhouse.ClickHouseSparkExt._
import org.apache.commons.cli.{BasicParser, Options}
import org.apache.spark.sql.SparkSession
import ru.yandex.clickhouse.ClickHouseDataSource

/**
  * @package: mobvista.dmp.clickhouse.feature
  * @author: wangjf
  * @date: 2019-08-30
  * @time: 16:02
  * @email: jinfeng.wang@mobvista.com
  * @phone: 152-1062-7698
  */
class UserInfo extends Serializable {
  def commandOptions(): 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
  }

  protected def run(args: Array[String]) {
    val parser = new BasicParser()
    val options = commandOptions()
    val commandLine = parser.parse(options, args)
    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("UserInfo")
      .config("spark.rdd.compress", "true")
      .config("spark.io.compression.codec", "lz4")
      .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()
    try {

      val sc = spark.sparkContext

      val map = sc.broadcast(spark.sql(Constant.old2new_sql).rdd.map(r => {
        (r.getAs("new_second_id").toString, r.getAs("new_first_id").toString)
      }).collectAsMap())
      val sdf1 = new SimpleDateFormat("yyyy-MM-dd")
      val sdf2 = new SimpleDateFormat("yyyyMMdd")

      // clickhouse params
      val clusterName = Some(cluster): Option[String]

      spark.udf.register("checkDevice", Constant.checkDeviceId _)

      implicit val clickhouseDataSource: ClickHouseDataSource = ClickHouseConnectionFactory.get(host)

      val update_date = sdf1.format(sdf2.parse(date))

      val tdf = spark.emptyDataFrame
      //  drop curr partition
      tdf.dropPartition(database, table, date, clusterName)

      val userSql = Constant.user_feature_sql.replace("@date", date)

      /*
      val userDF = spark.sql(userSql).rdd.map(r => {
        val jsonObject = new JSONObject()
        val frequencyEntity = FrequencyEntity(r.getAs("frequency"))
        import scala.collection.JavaConversions._
        if (frequencyEntity.frequency != null && frequencyEntity.frequency.nonEmpty) {
          for (i <- frequencyEntity.frequency.indices) {
            val tag = frequencyEntity.frequency.get(i).asInstanceOf[GenericRowWithSchema].getAs("tag").toString
            val cnt = Integer.parseInt(frequencyEntity.frequency.get(i).asInstanceOf[GenericRowWithSchema].getAs("cnt").toString)
            jsonObject.put(tag, cnt)
          }
        }
        val interestArr = r.getAs("interest").asInstanceOf[mutable.WrappedArray[String]]
        val interest: mutable.HashSet[String] = new mutable.HashSet[String]()
        interestArr.foreach(i => {
          interest.add(map.value(i))
          interest.add(i)
        })

        val tag_week_jsonObject = new JSONObject()
        if (r.getAs("tag_week") != null && StringUtils.isNotBlank(r.getAs("tag_week"))) {
          val jsonArray = GsonUtil.String2JsonArray(r.getAs("tag_week"))
          for (json <- jsonArray) {
            val j = json.getAsJsonObject
            val tag_id = j.get("tag_id").getAsString
            val cntJson = new JSONObject()
            val cnt = j.get("cnt").getAsInt
            cntJson.put("cnt", cnt)
            val count = j.get("count").getAsInt
            cntJson.put("count", count)
            tag_week_jsonObject.put(tag_id, cntJson)
          }
        }
        val tag_month_jsonObject = new JSONObject()
        if (r.getAs("tag_month") != null && StringUtils.isNotBlank(r.getAs("tag_month"))) {
          val jsonArray = GsonUtil.String2JsonArray(r.getAs("tag_month"))
          for (json <- jsonArray) {
            val j = json.getAsJsonObject
            val tag_id = j.get("tag_id").getAsString
            val cntJson = new JSONObject()
            val cnt = j.get("cnt").getAsInt
            cntJson.put("cnt", cnt)
            val count = j.get("count").getAsInt
            cntJson.put("count", count)
            tag_month_jsonObject.put(tag_id, cntJson)
          }
        }

        DmUserInfo(r.getAs("device_id").toString.toUpperCase, r.getAs("platform"), r.getAs("model"), r.getAs("os_version"),
          r.getAs("country"), r.getAs("age"), r.getAs("gender"), r.getAs("install"), mutable.WrappedArray.make(interest.toArray[String]),
          r.getAs("behavior"), jsonObject.toJSONString, tag_week_jsonObject.toJSONString, tag_month_jsonObject.toJSONString, r.getAs("update_date"),
          r.getAs("publish_date"))
      }).toDF
     */
      import spark.implicits._
      val userDF = spark.sql(userSql).rdd.map(r => {
        DmUserInfo(r.getAs("device_id").toString.toUpperCase, r.getAs("platform"), r.getAs("model"), r.getAs("os_version"),
          r.getAs("country"), r.getAs("age"), r.getAs("gender"), r.getAs("install"), r.getAs("interest"),
          r.getAs("behavior"), r.getAs("frequency"), r.getAs("tag_week"), r.getAs("tag_month"), if (r.getAs("region") != null) {
            r.getAs("region")
          } else {
            Array.empty[String]
          },
          r.getAs("update_date"), r.getAs("publish_date"))
      }).toDF

      Thread.sleep(120000)
      /**
        * user_info save
        */
      //  userDF.createClickHouseDb(database, clusterName)
      //  userDF.createClickHouseTable(database, table, Seq("dt"), Constant.indexColumn, Constant.orderColumn, clusterName)
      userDF.saveToClickHouse(database, table, Seq(update_date), Seq("dt"), clusterName, batchSize = 200000)

      MySQLUtil.update(database, table, date)
      //  val lastDate = DateUtil.getDayByString(date, "yyyyMMdd", -1)
      //  drop last partition
      //  tdf.dropPartition(database, table, lastDate, clusterName)

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


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