# -*- coding:UTF-8 -*-
# @Time  : 2020/9/9 17:16
# @File  : func_get_pv_card_id.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 pyspark.sql.functions import lit
# import pytispark.pytispark as pti


def get_card_id():
    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")

    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").appName(
            "LR PYSPARK TEST").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

    for t in range(1, 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")
        today_str = now.strftime("%Y%m%d")
        yesterday_str = (now + datetime.timedelta(days=-1)).strftime("%Y%m%d")
        one_week_age_str = (now + datetime.timedelta(days=-3)).strftime("%Y%m%d")
        sql = r"""
    SELECT * FROM
        (--精准曝光，卡片id和session_id去重
            SELECT  partition_date,
                    card_content_type,
                    cl_id,
                    recommend_type,
                    card_id
            FROM
            (
               SELECT partition_date,
                      cl_id,
                      case when card_content_type in ('qa','answer') then 'qa' else card_content_type end as card_content_type,
                      CASE when transaction_type in ('fmctr') then 'fmctr'
                           WHEN transaction_type like '%ctr' THEN 'ctr预估'
                           WHEN transaction_type like '%cvr' THEN 'cvr预估'
                           WHEN transaction_type in ('-1','smr') THEN 'smr'
                           when transaction_type in ('pgc','hotspot') then '热点卡片'
                           when transaction_type in ('newdata') then '保量卡片'
                           when transaction_type in ('hotspot_feed') then 'hotspot_feed'
                      END AS recommend_type,
                      card_id,
                      app_session_id
               from online.ml_community_precise_exposure_detail
               WHERE partition_date='{partition_day}'
               AND action in ('page_precise_exposure','home_choiceness_card_exposure') --7745版本action改为page_precise_exposure
               AND is_exposure = '1'  ----精准曝光
               AND page_name ='home'
               AND tab_name = '精选'
               AND (transaction_type in ('-1','smr','hotspot','pgc','newdata','hotspot_feed')
                    or transaction_type like '%ctr' or transaction_type like '%cvr')
               AND card_content_type in ('qa','diary','user_post','answer')
               group by partition_date,
                      case when card_content_type in ('qa','answer') then 'qa' else card_content_type end,
                      cl_id,
                      CASE when transaction_type in ('fmctr') then 'fmctr'
                           WHEN transaction_type like '%ctr' THEN 'ctr预估'
                           WHEN transaction_type like '%cvr' THEN 'cvr预估'
                           WHEN transaction_type in ('-1','smr') THEN 'smr'
                           when transaction_type in ('pgc','hotspot') then '热点卡片'
                           when transaction_type in ('newdata') then '保量卡片'
                           when transaction_type in ('hotspot_feed') then 'hotspot_feed' END,
                      card_id,
                      app_session_id
            )a
            group by partition_date,card_content_type,cl_id,recommend_type,card_id
          )t2
       
            LEFT JOIN
        (
            select distinct device_id
            from ml.ml_d_ct_dv_devicespam_d  --去除机构刷单设备，即作弊设备（浏览和曝光事件去除）
            WHERE partition_day='{partition_day}'
    
            union all
    
            select distinct device_id
            from dim.dim_device_user_staff   --去除内网用户
        )spam_pv
        on spam_pv.device_id=t2.cl_id
            LEFT JOIN
        (
            SELECT partition_date,device_id
            FROM
                (--找出user_id当天活跃的第一个设备id
              SELECT user_id,partition_date,
                      if(size(device_list) > 0, device_list [ 0 ], '') AS device_id
                FROM online.ml_user_updates
                WHERE partition_date='{partition_day}'
            )t1
                    JOIN
                (  --医生账号
              SELECT distinct user_id
              FROM online.tl_hdfs_doctor_view
              WHERE partition_date = '{partition_day}'
    
              --马甲账号/模特用户
              UNION ALL
              SELECT user_id
              FROM ml.ml_c_ct_ui_user_dimen_d
              WHERE partition_day = '{partition_day}'
              AND (is_puppet = 'true' or is_classifyuser = 'true')
    
              UNION ALL
              --公司内网覆盖用户
              select distinct user_id
              from dim.dim_device_user_staff
    
              UNION ALL
              --登陆过医生设备
              SELECT distinct t1.user_id
                FROM
                (
                    SELECT user_id, v.device_id as device_id
                    FROM online.ml_user_history_detail
                        LATERAL VIEW EXPLODE(device_history_list) v AS device_id
                    WHERE partition_date = '{partition_day}'
                ) t1
                JOIN
                (
                    SELECT device_id
                    FROM online.ml_device_history_detail
                    WHERE partition_date = '{partition_day}'
                    AND is_login_doctor = '1'
                ) t2
                    ON t1.device_id = t2.device_id
            )t2
                on t1.user_id=t2.user_id
            group by partition_date,device_id
        )dev
        on t2.partition_date=dev.partition_date and t2.cl_id=dev.device_id
    WHERE spam_pv.device_id IS NULL
      and dev.device_id is null
    """.format(partition_day=yesterday_str)
        device_df = spark.sql(sql)

        device_df.show(1, False)
        sql_res = device_df.collect()
        res_dict = {
            "diary": [],
            "user_post": [],
            "qa": []
        }
        for res in sql_res:
            # print(res)
            card_content_type = res.card_content_type
            card_id = res.card_id
            if card_content_type in res_dict:
                res_dict[card_content_type].append(card_id)
        return res_dict
