# -*- coding:UTF-8 -*-
# @Time  : 2020/9/17 16:26
# @File  : output_article_distribution_0917.py
# @email : litao@igengmei.com
# @author : litao


# -*- coding:UTF-8 -*-
# @Time  : 2020/9/11 10:59
# @File  : portary_article_distribution.py
# @email : litao@igengmei.com
# @author : litao


import hashlib
import json

import pymysql
import xlwt, datetime
import redis
from meta_base_code.utils.func_from_redis_get_portrait import user_portrait_scan_info,get_user_portrait_tag3_from_redis
from meta_base_code.utils.func_from_es_get_article import get_es_article_num,get_user_post_from_mysql
# from pyhive import hive
from maintenance.func_send_email_with_file import send_file_email
from typing import Dict, List
from elasticsearch_7 import Elasticsearch
from elasticsearch_7.helpers import scan
import sys
import time
from pyspark import SparkConf
from pyspark.sql import SparkSession, DataFrame


# from pyspark.sql.functions import lit
# import pytispark.pytispark as pti
startTime = time.time()
sparkConf = SparkConf()
sparkConf.set("spark.sql.crossJoin.enabled", True)
sparkConf.set("spark.debug.maxToStringFields", "100")
sparkConf.set("spark.tispark.plan.allow_index_double_read", False)
sparkConf.set("spark.tispark.plan.allow_index_read", True)
sparkConf.set("spark.hive.mapred.supports.subdirectories", True)
sparkConf.set("spark.hadoop.mapreduce.input.fileinputformat.input.dir.recursive", True)
sparkConf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
sparkConf.set("mapreduce.output.fileoutputformat.compress", False)
sparkConf.set("mapreduce.map.output.compress", False)
sparkConf.set("prod.gold.jdbcuri",
              "jdbc:mysql://172.16.30.136/doris_prod?user=doris&password=o5gbA27hXHHm&rewriteBatchedStatements=true")
sparkConf.set("prod.mimas.jdbcuri",
              "jdbc:mysql://172.16.30.138/mimas_prod?user=mimas&password=GJL3UJe1Ck9ggL6aKnZCq4cRvM&rewriteBatchedStatements=true")
sparkConf.set("prod.gaia.jdbcuri",
              "jdbc:mysql://172.16.30.143/zhengxing?user=work&password=BJQaT9VzDcuPBqkd&rewriteBatchedStatements=true")
sparkConf.set("prod.tidb.jdbcuri",
              "jdbc:mysql://172.16.40.158:4000/eagle?user=st_user&password=aqpuBLYzEV7tML5RPsN1pntUzFy&rewriteBatchedStatements=true")
sparkConf.set("prod.jerry.jdbcuri",
              "jdbc:mysql://172.16.40.158:4000/jerry_prod?user=st_user&password=aqpuBLYzEV7tML5RPsN1pntUzFy&rewriteBatchedStatements=true")
sparkConf.set("prod.tispark.pd.addresses", "172.16.40.158:2379")
sparkConf.set("prod.tispark.pd.addresses", "172.16.40.170:4000")
sparkConf.set("prod.tidb.database", "jerry_prod")
sparkConf.setAppName("test")

spark = (SparkSession.builder.config(conf=sparkConf).config("spark.sql.extensions", "org.apache.spark.sql.TiExtensions")
         .config("spark.tispark.pd.addresses", "172.16.40.170:2379").enableHiveSupport().getOrCreate())

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'")
spark.sql("CREATE TEMPORARY FUNCTION arrayMerge AS 'com.gmei.hive.common.udf.UDFArryMerge'")

task_list = []
task_days = 2


def con_sql(sql):
    # 从数据库的表里获取数据

    db = pymysql.connect(host='172.16.40.158', port=4000, user='st_user', passwd='aqpuBLYzEV7tML5RPsN1pntUzFy',
                         db='jerry_prod')
    cursor = db.cursor()
    cursor.execute(sql)
    result = cursor.fetchall()
    db.close()
    return result


second_demands_zero_dict = {
    # "answer":{},
    "tractate":{},
    # "diary":{},
}
project_zero_dict = {
    # "answer":{},
    "tractate":{},
    # "diary":{},
}
t = 1
day_num = 0 - t
now = (datetime.datetime.now() + datetime.timedelta(days=day_num))
last_30_day_str = (now + datetime.timedelta(days=-31)).strftime("%Y%m%d")
today_str = now.strftime("%Y%m%d")
today_str_format = now.strftime("%Y-%m-%d")
yesterday_str = (now + datetime.timedelta(days=-1)).strftime("%Y%m%d")
yesterday_str_format = (now + datetime.timedelta(days=-1)).strftime("%Y-%m-%d")
one_week_age_str = (now + datetime.timedelta(days=-7)).strftime("%Y%m%d")
sql = """select first_device from online.ml_user_history_detail where partition_date = {today_str} and last_active_date >= {last_30_day_str}
""".format(today_str=today_str,last_30_day_str=last_30_day_str)
print(sql)
new_urser_device_id_df = spark.sql(sql)
new_urser_device_id_df.createOrReplaceTempView("device_id_view")
new_urser_device_id_df.show(1)
sql_res = new_urser_device_id_df.collect()

bulk_dict = {
    0: [0, 0, 0],
    10: [0, 0, 0],
    50: [0, 0, 0],
    100: [0, 0, 0],
    200: [0, 0, 0],
    500: [0, 0, 0],
    1000: [0, 0, 0],
}


task_list = []
second_demands_count_dict,tags_v3_count_dict=get_user_post_from_mysql()
print(second_demands_count_dict,tags_v3_count_dict)
time.sleep(10)

user_portrait_scan = user_portrait_scan_info()
for redis_count,spark_res in enumerate(sql_res):
    # if redis_count >= 50:break
    second_demands = []
    projects = []
    total_answer_content_num = 0
    total_tractate_content_num = 0
    total_diary_content_num = 0
    res = get_user_portrait_tag3_from_redis(spark_res.device_id)
    if res.get("second_demands"):
        second_demands = res.get("second_demands")
        # print(count_res)
        for tag in second_demands:
            if tag in tags_v3_count_dict:
                total_tractate_content_num += second_demands_count_dict[tag]
    if res.get("projects"):
        projects = res.get("projects")
        # print(count_res)
        for tag in projects:
            if tag in tags_v3_count_dict:
                total_tractate_content_num += tags_v3_count_dict[tag]
    # print(total_answer_content_num, total_tractate_content_num, total_diary_content_num)
    tmp_count_num = 0


    if 0 <= total_tractate_content_num < 10:
        bulk_dict[0][1] += 1
    elif 10 <= total_tractate_content_num < 50:
        bulk_dict[10][1] += 1
    elif 50 <= total_tractate_content_num < 100:
        bulk_dict[50][1] += 1
    elif 100 <= total_tractate_content_num < 200:
        bulk_dict[100][1] += 1
    elif 200 <= total_tractate_content_num < 500:
        bulk_dict[200][1] += 1
    elif 500 <= total_tractate_content_num < 1000:
        bulk_dict[500][1] += 1
    else:
        bulk_dict[1000][1] += 1

    if redis_count % 5000 == 0:
        print(bulk_dict)


print(bulk_dict)



