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


import hashlib
import json

import pymysql
import xlwt, datetime
import redis
# 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 meta_base_code.utils.func_from_redis_get_portrait import *


# from pyspark.sql.functions import lit
# import pytispark.pytispark as pti


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

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


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("new_user_has_protratit_rate")

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 = 3

for t in range(2, task_days):
    day_num = 0 - t
    now = (datetime.datetime.now() + datetime.timedelta(days=day_num))
    last_30_day_str = (now + datetime.timedelta(days=-30)).strftime("%Y%m%d")
    tomorrow_str = (datetime.datetime.now() + datetime.timedelta(days=day_num + 1)).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")
    new_urser_device_id_sql = r"""
    SELECT *
                  FROM online.bl_hdfs_maidian_updates
                  WHERE partition_date >= '{partition_day}'
                      AND partition_date < '{end_date}'
                  AND ((action in ('search_result_click_recommend_item','search_result_welfare_click_item')
                      AND page_name in ('search_result_more','search_result_welfare'))
                   or (action = 'goto_welfare_detail' AND params ['from'] = 'search_result_welfare_recommend')
                   or (action = 'on_click_card' AND params['card_content_type'] in ('service') AND page_name in ('search_result_more','search_result_welfare')))
                  UNION ALL
SELECT *  FROM online.bl_hdfs_maidian_updates
                         WHERE partition_date >= '{partition_day}'
                           AND partition_date < '{end_date}'
                           AND ((action in ('on_click_topic_card','on_click_diary_card','search_result_click_infomation_item')
                               AND page_name in ('search_result_more','search_result_diary','search_result_post'))
                               or (action = 'on_click_card' AND params['card_content_type'] in ('answer','diary') AND page_name in ('search_result_more','search_result_diary','search_result_question_answer')))
    """.format(partition_day="20210101", end_date="20210225", tomorrow_str=tomorrow_str)

    #   print(new_urser_device_id_sql)
    new_urser_device_id_df = spark.sql(new_urser_device_id_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()
    res_list = []
    for res in sql_res:
        # print(res)
        query = res.params.get("query","").replace("\r","").replace("\n","")
        card_name = res.params.get("card_name","").replace("\r","").replace("\n","")
        card_id = res.params.get("card_id","")
        cl_id = res.cl_id
        time_str = res.time_str
        page_name = res.page_name
        res_list.append({"query": query,
                         "card_name": card_name,
                         "card_id": card_id,
                         "cl_id": cl_id,
                         "time_str": time_str,
                         "page_name": page_name
                         })
    import pandas

    data = pandas.DataFrame(res_list)
    data.to_csv("data.csv",encoding="gb18030")
    time.sleep(10)
    from maintenance.send_email_with_file_auto_task import *
    import zipfile

    with zipfile.ZipFile("data.zip", 'w',zipfile.ZIP_DEFLATED) as zp:
        zp.write("data.csv")

    send_file_email("",'',sender="litao@igengmei.com",email_group=["litao@igengmei.com"],email_msg_body_str="test",title_str="test",cc_group=["litao@igengmei.com"],file="data.zip")
#   sql_res = new_urser_device_id_df.collect()
#   res_dict = {}
#   portrait_dict = {
#       "first_demands": {},
#       "second_demands": {},
#       "first_solutions": {},
#       "second_solutions": {},
#       "first_positions": {},
#       "second_positions": {},
#       "projects": {},
#       'anecdote_tags':{}
#   }
#   no_portrait_device_id_list = []
#   print("-------------------------------")
#   count_not_has_portratit = 0
#
#   for count_user_count, res in enumerate(sql_res):
#       # print(count, res)
#       portratit_res = get_user_portrait_tag3_from_redis(res.device_id)
#       sql = """select cl_id, projects from kafka_tag3_log
# where cl_id = '%s' and event_cn = 'kyc' """ % res.device_id
#       # print(count_user_count, res, portratit_res)
#       sql_res_list = con_sql(sql)
#       kyc_str_list= []
#       if sql_res_list:
#           print(sql_res_list,type(sql_res_list))
#           kyc_str_list = sql_res_list[0][1].split(",")
#
#       temp_count = 0
#       for demand in portratit_res:
#           if portratit_res[demand]:
#               try:
#                   for tag in portratit_res[demand][0:3]:
#                       if tag in portrait_dict[demand]:
#                          portrait_dict[demand][tag] += 1
#                       else:
#                          portrait_dict[demand][tag] = 1
#                       if tag in kyc_str_list and demand == "projects":
#                           if portrait_dict["projects"].get(tag):
#                               portrait_dict["projects"][tag] -= 1
#               except Exception as e:
#                   print("error ", e)
#
#               temp_count += 1
#       if not temp_count:
#           count_not_has_portratit += 1
#           no_portrait_device_id_list.append(res.device_id)
#
#
#   print(portrait_dict)
#   print(count_user_count+1,count_not_has_portratit)
#   print("-------------------------------")
#
#
#   for protratit_type in portrait_dict["projects"]:
#       partition_date = today_str
#       pid = hashlib.md5((partition_date + protratit_type).encode("utf8")).hexdigest()
#       action_count = portrait_dict["projects"][protratit_type]
#
#       instert_sql = """replace into new_user_project_count(
#                   partition_day,pid,protratit_count,protratit_type) VALUES('{partition_day}','{pid}',{protratit_count},'{protratit_type}');""".format(
#           partition_day=today_str, pid=pid, protratit_count=action_count
#           , protratit_type=protratit_type
#       )
#       print(instert_sql)
#       # cursor.execute("set names 'UTF8'")
#       db = pymysql.connect(host='172.16.30.136', port=3306, user='doris_olap', passwd='bA27hXasdfswuolap',
#                            db='doris_olap')
#       cursor = db.cursor()
#       res = cursor.execute(instert_sql)
#       db.commit()
#       print(res)
#
