import datetime
from datetime import timedelta
import pandas as pd
from common_func import mysql_replace_into
from get_material_and_script.get_script_from_tengxunyun import GetScriptFromTengXunYunServer


class GetMaterialFromHuiChuang(object):
    def __init__(self, query_word, logger, jeecg_boot_db_engine, ai_word_db_engine):
        self.query_word = query_word
        self.logger = logger
        self.jeecg_boot_db_engine = jeecg_boot_db_engine
        self.ai_word_db_engine = ai_word_db_engine
        self.high_material_df = pd.DataFrame()
        self.video_url_df = pd.DataFrame()
        self.video_df = pd.DataFrame()

    def get_video_basic_info(self):
        # 1 依据查询词获取 account_id (只获取快手的素材)
        # `media_id`  '平台类型 1 头条 2快手',
        # `account_status`  '0 启动 1 禁用',
        self.logger.info(f"查询词：{self.query_word}, 获取公司内部优质素材，开始执行... ")
        sql = f"select distinct(account_id) account_id from ctop_user_allocation where project_name like '%%{self.query_word}%%' " \
              f"and media_id = 2"
        account_id_lst = pd.read_sql(sql, self.jeecg_boot_db_engine).account_id.values

        # 2 依据 account_id 获取素材
        if account_id_lst.size > 0:
            # 2-1 获取近7天的高质量素材
            days = 7
            start_date = (datetime.date.today() + timedelta(days=-days)).strftime('%Y-%m-%d')
            full_date_df = pd.DataFrame()
            for date in pd.date_range(start=start_date, freq='D', periods=days):
                stat_date = date.strftime('%Y-%m-%d')
                sql = f"select signature, activation , charge " \
                      f"from ctop_kuaishou_report_daily_material  " \
                      f"where account_id in {tuple(list(account_id_lst) * 2) if account_id_lst.size == 1 else tuple(account_id_lst)} " \
                      f"and stat_date = '{stat_date}'" \
                      f"and signature is not null"
                one_date_df = pd.read_sql(sql, self.jeecg_boot_db_engine)
                full_date_df = full_date_df.append(one_date_df)

            # 2-2 获取高质量素材（近一周累计激活个数>=50）
            g = full_date_df.groupby('signature').agg({'activation': sum, 'charge': sum})
            g.reset_index(drop=False, inplace=True)
            self.high_material_df = g[g['activation'] >= 50]

        # 3 获取高质量素材的 video_url
        if not self.high_material_df.empty:
            signature_lst = self.high_material_df.signature.values
            sql = f"select url video_url, signature from ctop_kuaishou_video_get " \
                  f"where signature in {tuple(list(signature_lst) * 2) if signature_lst.size == 1 else tuple(signature_lst)}" \
                  f"group by signature"
            self.video_url_df = pd.read_sql(sql, self.jeecg_boot_db_engine)

        # 4 dataframe merge
        if not self.high_material_df.empty and not self.video_url_df.empty:
            self.video_df = self.high_material_df.merge(self.video_url_df, on='signature', how='inner')

        self.logger.info(f"查询词：{self.query_word}, 获取公司内部优质素材，共获取到{len(self.video_df)}个")

        # 5 获取到的信息存入数据库
        if not self.video_df.empty:
            self.video_df['query_word'] = self.query_word
            self.video_df['stat_date'] = datetime.date.today().strftime("%Y-%m-%d")

            self.video_df.to_sql(name="ctop_ai_video_info_from_huichuang",
                                 con=self.ai_word_db_engine,
                                 if_exists='append',
                                 index=False,
                                 chunksize=1000,
                                 method=mysql_replace_into)

    def get_script_from_teng_xun_yun(self):
        get_script_ins = GetScriptFromTengXunYunServer(logger=self.logger,
                                                       db_engine=self.ai_word_db_engine,
                                                       task_df=self.video_df[['signature', 'video_url']],
                                                       task_ids=None)
        get_script_ins.submit_task()
        if get_script_ins.task_ids:
            get_script_ins.get_result()
