package mobvista.dmp.datasource.taobao

import java.net.{InetAddress, URI}
import java.util.concurrent.{Callable, CopyOnWriteArrayList, ExecutionException, ExecutorService, Executors, Future}
import java.util

import mobvista.dmp.common.CommonSparkJob
import org.apache.commons.cli.Options
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.SparkEnv
import org.apache.spark.sql.{Row, SaveMode, SparkSession}

import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConverters._
import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}

import scala.collection.mutable

class UCLaHuoDaily extends CommonSparkJob with Serializable  {

//  def buildRes(iterator: Iterator[Row]): Iterator[String] = {
//    val array = new ArrayBuffer[String]()
//    println("executorId=="+SparkEnv.get.executorId)
//    println("threadname=="+Thread.currentThread().getName())
//    var ip: String = null
//    var host: String = null
//    val ia: InetAddress = InetAddress.getLocalHost
//    host = ia.getHostName //获取计算机名字
//    ip = ia.getHostAddress //获取IP
//    println("host=="+host)
//    println("ip=="+ip)
//
//    var tmpresult = ArrayBuffer[String]()
//    while(iterator.hasNext) {
//      if (tmpresult.length < 5) {
//        val device_id_md5= iterator.next().getAs[String]("device_id_md5")
//        tmpresult +=device_id_md5
//      }
//      if (tmpresult.length == 5) {
//        array += UCActivitionHttpPostRequest.PostJSON(tmpresult.asJava, "IMEI_MD5")
//        tmpresult.clear()
//      }
//      if (!iterator.hasNext) {
//        if (tmpresult.nonEmpty) {
//          array += UCActivitionHttpPostRequest.PostJSON(tmpresult.asJava,"IMEI_MD5")
//          tmpresult.clear()
//        }
//      }
//    }
//    array.iterator
//  }
//
//
//  def buildResWithMultiThread(iterator: Iterator[Row]): Iterator[String] = {
//    println("executorId=="+SparkEnv.get.executorId)
//    println("threadname=="+Thread.currentThread().getName())
//    var ip: String = null
//    var host: String = null
//    val ia: InetAddress = InetAddress.getLocalHost
//    host = ia.getHostName //获取计算机名字
//    ip = ia.getHostAddress //获取IP
//    println("host=="+host)
//    println("ip=="+ip)
//
//    val tasks: util.List[Callable[String]] = new util.ArrayList[Callable[String]]
//    var tmpresult = ArrayBuffer[String]()
//    while(iterator.hasNext) {
//      if (tmpresult.length < 5) {
//        val device_id_md5= iterator.next().getAs[String]("device_id_md5")
//        tmpresult +=device_id_md5
//      }
//      if (tmpresult.length == 5) {
//        val callable: Callable[String] = new Callable[String]() {
//          @throws[Exception]
//          override def call: String = {
//            UCActivitionHttpPostRequest.PostJSON(tmpresult.asJava,"IMEI_MD5")
//          }
//        }
//        tasks.add(callable)
//        tmpresult.clear()
//      }
//      if (!iterator.hasNext) {
//        if (tmpresult.nonEmpty) {
//          println("tmpresult.length=="+tmpresult.length)
//          val callable: Callable[String] = new Callable[String]() {
//            @throws[Exception]
//            override def call: String = {
//              UCActivitionHttpPostRequest.PostJSON(tmpresult.asJava,"IMEI_MD5")
//            }
//          }
//          tasks.add(callable)
//          tmpresult.clear()
//        }
//      }
//    }
//    val executorService: ExecutorService = Executors.newFixedThreadPool(4)
//    var futures: util.List[Future[String]] = null
//
//    try futures = executorService.invokeAll(tasks)
//    catch {
//      case e: InterruptedException =>
//        e.printStackTrace()
//    }
//
//    val res = new CopyOnWriteArrayList[String]()
//    import scala.collection.JavaConversions._
//    for (future <- futures) {
//      try {val value: String = future.get
//        res.add(value)}
//      catch {
//        case e: InterruptedException =>
//          e.printStackTrace()
//        case e: ExecutionException =>
//          println("fail===")
//          e.printStackTrace()
//      }
//    }
//    executorService.shutdown
//    res.iterator().asScala
//  }

  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("imeioutput", true, "[must] imeioutput")
    options.addOption("oaidoutput", true, "[must] oaidoutput")
    options.addOption("today", true, "[must] today")
    options.addOption("last_req_day", true, "[must] last_req_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 imeioutput = commandLine.getOptionValue("imeioutput")
    val oaidoutput = commandLine.getOptionValue("oaidoutput")
    val today = commandLine.getOptionValue("today")
    val last_req_day = commandLine.getOptionValue("last_req_day")


    val spark = SparkSession.builder()
      .appName("EtlAliActivitionDaily")
      .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()

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

    try {

      val sql1=
        s"""
           |select XX.device_id_md5,XX.device_id,XX.device_type
           |FROM (select X.device_id_md5,X.device_id,X.device_type,
           |row_number() over(partition by X.device_id_md5 order by X.device_type asc) rk
           |from ( select device_id,device_type,
           |case when device_type = 'imei' then MD5(device_id) when device_type = 'imeimd5' then device_id end as device_id_md5
           |from dwh.ods_dmp_user_info where dt ='${today}'
           | and device_type in ('imei','imeimd5')
           | and last_req_day >='${last_req_day}'
           | and  upper(country) = 'CN' ) X ) XX
           | WHERE XX.rk= 1
        """.stripMargin

      val sql2=
        s"""
           |select XX.device_id_md5,XX.device_id,XX.device_type
           |FROM (select X.device_id_md5,X.device_id,X.device_type,
           |row_number() over(partition by X.device_id_md5 order by X.device_type asc) rk
           |from ( select device_id,device_type,
           |case when device_type = 'oaid' then MD5(device_id) when device_type = 'oaidmd5' then device_id end as device_id_md5
           |from dwh.ods_dmp_user_info where dt ='${today}'
           | and device_type in ('oaid','oaidmd5')
           | and last_req_day >='${last_req_day}'
           | and  upper(country) = 'CN' ) X ) XX
           | WHERE XX.rk= 1
        """.stripMargin

//      spark.sql(sql1).repartition(100).rdd.mapPartitions(rows => { buildRes(rows)}).
//        coalesce(100).saveAsTextFile(imeioutput)

      val partitions01 = spark.sql(sql1).rdd.getNumPartitions
      val partitions02 = spark.sql(sql2).rdd.getNumPartitions
      println("partitions01====="+partitions01)
      println("partitions02====="+partitions02)

      val eachRowPartitionNum01 = 400000000 / partitions01
      val eachRowPartitionNum02 = 50000000 / partitions02
      println("eachRowPartitionNum01==="+eachRowPartitionNum01)
      println("eachRowPartitionNum02==="+eachRowPartitionNum02)

      spark.sql(sql1).rdd.mapPartitions(rs => {
        val array = new ArrayBuffer[String]()
        var devidSet = new mutable.HashSet[String]()
        val rows: Iterator[Row] = rs.take(eachRowPartitionNum01)
        while (rows.hasNext) {
          devidSet.add(rows.next().getAs[String]("device_id_md5"))
          if (devidSet.size == 100) {
            array += devidSet.mkString(",")
            devidSet = new mutable.HashSet[String]()
          } else if (devidSet.size < 100 && !rows.hasNext) {
            array += devidSet.mkString(",")
          }
        }
        array.iterator
      }).
        coalesce(200).saveAsTextFile(imeioutput)



      spark.sql(sql2).rdd.mapPartitions(rs => {
        val array = new ArrayBuffer[String]()
        var devidSet = new mutable.HashSet[String]()
        val rows: Iterator[Row] = rs.take(eachRowPartitionNum02)
        while (rows.hasNext) {
          devidSet.add(rows.next().getAs[String]("device_id_md5"))
          if (devidSet.size == 100) {
            array += devidSet.mkString(",")
            devidSet = new mutable.HashSet[String]()
          } else if (devidSet.size < 100 && !rows.hasNext) {
            array += devidSet.mkString(",")
          }
        }
        array.iterator
      }).
        coalesce(200).saveAsTextFile(oaidoutput)


    } finally {
      spark.stop()
    }
    0

  }
}


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