# -*- coding: utf-8 -*-
from pyspark.sql import HiveContext
from pyspark.context import SparkContext
from pyspark.conf import SparkConf
import pytispark.pytispark as pti
# from pyspark.sql import SQLContext
from pyspark.sql import SparkSession
import datetime


def test():

    sparkConf = SparkConf().set("spark.hive.mapred.supports.subdirectories", "true")\
        .set("spark.hadoop.mapreduce.input.fileinputformat.input.dir.recursive", "true")\
        .set("spark.tispark.plan.allow_index_double_read", "false") \
        .set("spark.tispark.plan.allow_index_read", "true")\
        .set("spark.sql.extensions", "org.apache.spark.sql.TiExtensions")\
        .set("spark.tispark.pd.addresses", "172.16.40.158:2379").set("spark.io.compression.codec", "lzf")


    spark = SparkSession.builder.config(conf= sparkConf).enableHiveSupport().getOrCreate()
    spark.sql("use online")
    spark.sql("ADD JAR hdfs:///user/hive/share/lib/udf/brickhouse-0.7.1-SNAPSHOT.jar")
    spark.sql("ADD JAR hdfs:///user/hive/share/lib/udf/hive-udf-1.0-SNAPSHOT.jar")
    spark.sql("CREATE TEMPORARY FUNCTION json_map AS 'brickhouse.udf.json.JsonMapUDF'")
    spark.sql("CREATE TEMPORARY FUNCTION is_json AS 'com.gmei.hive.common.udf.UDFJsonFormatCheck'")

    sql = "select user_id from online.tl_hdfs_maidian_view where partition_date = '20190412' limit 10"
    spark.sql(sql).show(6)

    # ti = pti.TiContext(spark)
    # ti.tidbMapDatabase("jerry_test")
    #
    # spark.sparkContext.setLogLevel("WARN")
    # df = spark.sql("select max(stat_date) from esmm_train_data")
    # df.show()
    # t = df.rdd.map(lambda x: str(x[0])).collect()
    # print(t)




    # data = [(0, 18.0), (1, 19.0), (2, 8.0), (3, 5.0), (4, 2.2), (5, 9.2), (6, 14.4)]
    # df = spark.createDataFrame(data, ["id", "hour"])
    # df.show(6)
    # t = df.rdd.map(lambda x:x[0]).collect()
    # print(t)

    # validate_date = spark.sql("select max(stat_date) from esmm_train_data").rdd.map(lambda x: str(x[0]))
    # print(validate_date.count())
    # print("validate_date:" + validate_date)
    # temp = datetime.datetime.strptime(validate_date, "%Y-%m-%d")
    # start = (temp - datetime.timedelta(days=10)).strftime("%Y-%m-%d")
    # print(start)


if __name__ == '__main__':
    test()