# -*- 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
from meta_base_code.utils.func_from_es_get_article import get_es_article_num
# 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


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


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 = []
user_portrait_scan = user_portrait_scan_info()
for res in user_portrait_scan:
    second_demands = []
    projects = []
    total_answer_content_num = 0
    total_tractate_content_num = 0
    total_diary_content_num = 0
    if res.get("second_demands"):
        second_demands = res.get("second_demands")
        count_res = get_es_article_num({"second_demands": second_demands[0:3]}, allow_tag=["second_demands"])
        print(count_res)
        for article_type in count_res:
            for tag in count_res[article_type]:
                total_answer_content, total_tractate_content, total_diary_content, sum_num = \
                    count_res[article_type][tag]
                total_answer_content_num += total_answer_content
                total_tractate_content_num += total_tractate_content
                total_diary_content_num += total_diary_content
    if res.get("projects"):
        projects = res.get("projects")
        count_res = get_es_article_num({"tags_v3": projects[0:3]}, allow_tag=["tags_v3"])
        print(count_res)
        for article_type in count_res:
            for tag in count_res[article_type]:
                total_answer_content, total_tractate_content, total_diary_content, sum_num = \
                    tag.values()
                total_answer_content_num += total_answer_content
                total_tractate_content_num += total_tractate_content
                total_diary_content_num += total_diary_content
    tmp_count_num = 0
    for count_num in bulk_dict:
        if tmp_count_num > total_answer_content_num:
            pass
        elif count_num <= total_answer_content_num:
            bulk_dict[tmp_count_num][0] += 1

        if tmp_count_num > total_tractate_content_num:
            pass
        elif count_num <= total_tractate_content_num:
            bulk_dict[tmp_count_num][1] += 1

        if tmp_count_num > total_diary_content_num:
            pass
        elif count_num <= total_diary_content_num:
            bulk_dict[tmp_count_num][2] += 1
    print(bulk_dict)
#     for active_type in res_dict:
#         for device_os_type in res_dict[active_type]:
#             partition_date = yesterday_str
#             pid = hashlib.md5((partition_date + device_os_type + active_type).encode("utf8")).hexdigest()
#             click_num = res_dict[active_type][device_os_type]["click_num"]
#             exposure = res_dict[active_type][device_os_type]["exposure"]
#             try:
#                 search_ctr = round(click_num / exposure, 5)
#             except:
#                 search_ctr = 0
#             instert_sql = """replace into search_tractate_ctr(
#             partition_date,device_os_type,active_type,pid,click_num,exposure,search_ctr) VALUES('{partition_date}','{device_os_type}','{active_type}','{pid}',{click_num},{exposure},{search_ctr});""".format(
#                 partition_date=partition_date, device_os_type=device_os_type, active_type=active_type, pid=pid, click_num=click_num,
#                 exposure=exposure, search_ctr=search_ctr
#             )
#             print(instert_sql)
#             # cursor.execute("set names 'UTF8'")
#             db = pymysql.connect(host='172.16.40.158', port=4000, user='st_user', passwd='aqpuBLYzEV7tML5RPsN1pntUzFy',
#                                  db='jerry_prod')
#             cursor = db.cursor()
#             res = cursor.execute(instert_sql)
#             db.commit()
#             print(res)
# # cursor.executemany()
# db.close()
