
# coding: utf-8
"""xlsx-mobile:
  - 01_highlight_type
  - 01_highlight_hist
  - 01_campaign_highlight_type
"""
from ..xlsx_chart.chart import Chart, chart_add_series, FONT_NAME
from ..utils import filter_by_adtype
import pandas as pd


def table_highlight_type(df):
    """01 Highlight (Search)"""

    def overlap_type(overlap):

        if overlap >= .99:
            return u'full'

        if overlap <= .01:
            return u'none'

        return u'partly'

    df_chart = filter_by_adtype(df, "MOBILE_APP_AD")
    df_chart = df_chart[[
        "BoldedWordsCnt",
        "WordsCnt",
        "ShowsSearch",
        "ClicksSearch",
        "CostSearch",
        "BSPhraseID",
        "CampaignID",
        "DirectBannerID"]].copy()
    df_chart["PhraseBoldShare"] = df_chart.BoldedWordsCnt / df_chart.WordsCnt
    df_chart['PhraseBoldType'] = df_chart.PhraseBoldShare.apply(overlap_type)

    return df_chart


def table_highlight_type_phrases(df, normalize):
    "01_highlight_type"

    df_export = table_highlight_type(df)
    df_export = df_export[df_export.ShowsSearch > 0]
    if df_export.shape[0] == 0:
        return None

    df_export = (
        df_export[[
            "BSPhraseID", "PhraseBoldType",
            "ShowsSearch", "ClicksSearch", "CostSearch"]]
        .groupby('PhraseBoldType')
        .agg({
            'ShowsSearch': pd.np.sum,
            'ClicksSearch': pd.np.sum,
            'CostSearch': pd.np.sum,
            'BSPhraseID': pd.np.count_nonzero}))
    df_export.rename(columns={
        "BSPhraseID": u"Количество фраз",
        "ShowsSearch": u"Показы (поиск)",
        "ClicksSearch": u"Клики (поиск)",
        "CostSearch": u"Затраты (поиск)"},
        inplace=True)
    df_export.rename(index={
        "full": u"Полная",
        "partly": u"Частичная",
        "none": u"Отсутствует"},
        inplace=True)
    df_export.index.name = u"Тип подсветки"
    df_export[u"CPC (поиск)"] = df_export[u"Затраты (поиск)"] / df_export[u"Клики (поиск)"]
    df_export[u"CTR (поиск)"] = df_export[u"Клики (поиск)"] / df_export[u"Показы (поиск)"]

    if normalize:
        cols_sum = [u"Количество фраз", u"Показы (поиск)", u"Клики (поиск)", u"Затраты (поиск)"]
        df_export.loc[:, cols_sum] = df_export.loc[:, cols_sum].apply(lambda x: x / x.sum())
        cols_max = [u"CPC (поиск)", u"CTR (поиск)"]
        df_export.loc[:, cols_max] = df_export.loc[:, cols_max].apply(lambda x: x / x.max())

    return df_export.loc[
        [u"Полная",
         u"Частичная",
         u"Отсутствует"],
        [u"Количество фраз",
         u"Показы (поиск)",
         u"Клики (поиск)",
         u"Затраты (поиск)",
         u"CPC (поиск)",
         u"CTR (поиск)"]].fillna('')


def plot_highlight_type_phrases(writer, sheet_name, cell, df):
    """
    (ExcelWriter, str, DataFrame) -> ExcelWriter
    01_highlight_type
    """

    sheet = writer.book.get_worksheet_by_name(sheet_name)

    # Create chart
    chart = Chart(writer.book, "bar", "percent_stacked", u'Подсветка фраз')

    # Add data series.
    chart_add_series(chart, 0, {
        'values': u"='%s'!B2:E2" % sheet_name,
        "categories": u"='%s'!B1:E1" % sheet_name,
        "name": u"='%s'!A2" % sheet_name})
    chart_add_series(chart, 1, {
        'values': u"='%s'!B3:E3" % sheet_name,
        "categories": u"='%s'!B1:E1" % sheet_name,
        "name": u"='%s'!A3" % sheet_name})
    chart_add_series(chart, 2, {
        'values': u"='%s'!B4:E4" % sheet_name,
        "categories": u"='%s'!B1:E1" % sheet_name,
        "name": u"='%s'!A4" % sheet_name})

    # Insert the chart into the worksheet.
    sheet.insert_chart(cell, chart)

    return writer


def plot_highlight_type_phrases_p(writer, sheet_name, cell, df):
    """
    (ExcelWriter, str, DataFrame) -> ExcelWriter
    01_highlight_type
    """

    sheet = writer.book.get_worksheet_by_name(sheet_name)

    # Create chart
    chart = Chart(writer.book, "bar", "percent_stacked", u'Подсветка фраз')

    # Add data series.
    label_fmt = {'value': True, 'num_format': '0.0%'}
    chart_add_series(chart, 0, {
        'values': u"='%s'!K2:N2" % sheet_name,
        'data_labels': label_fmt,
        "categories": u"='%s'!K1:N1" % sheet_name,
        "name": "=%s!J2" % sheet_name})
    chart_add_series(chart, 1, {
        'values': u"='%s'!K3:N3" % sheet_name,
        'data_labels': label_fmt,
        "categories": u"='%s'!K1:N1" % sheet_name,
        "name": u"='%s'!J3" % sheet_name})
    chart_add_series(chart, 2, {
        'values': u"='%s'!K4:N4" % sheet_name,
        'data_labels': label_fmt,
        "categories": u"='%s'!K1:N1" % sheet_name,
        "name": u"='%s'!J4" % sheet_name})

    # Insert the chart into the worksheet.
    sheet.insert_chart(cell, chart)

    return writer


def plot_highlight_type_phrases_cpc_ctr(writer, sheet_name, df):
    """(ExcelWriter, str, DataFrame) -> ExcelWriter"""

    sheet = writer.book.get_worksheet_by_name(sheet_name)
    chart = Chart(writer.book, "column", None, u"Показатели для различной подсветки")

    chart.set_y_axis({
        "visible": True,
        "name": u"",  # CPC
        'name_font': {
            "size": 16,
            "bold": False,
            "name": FONT_NAME
        },
        'num_font': {
            "size": 14,
            "bold": False,
            "name": FONT_NAME
        },
        'num_format': '#0.0',
        'major_tick_mark': 'none',
        'minor_tick_mark': 'none',
        'line': {
            'none': True
        },
        "label_position": "none",
        "min": 0,
    })
    chart.set_y2_axis({
        "visible": True,
        "name": u"",  # CTR
        'name_font': {
            "size": 16,
            "bold": False,
            "name": FONT_NAME
        },
        'num_font': {
            "size": 14,
            "bold": False,
            "name": FONT_NAME
        },
        'num_format': '#0.0%',
        'major_tick_mark': 'none',
        'minor_tick_mark': 'none',
        'line': {
            'none': True
        },
        "label_position": "none",
        "min": 0,
    })

    last_row = df.index.size + 1
    # CPC (поиск)
    chart_add_series(chart, 0, {
        'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, "F", last_row),
        "categories": u"='{}'!A2:A{}".format(sheet_name, last_row),
        "name": u"='{0}'!{1}1".format(sheet_name, "F"),
        "data_labels": {
            "num_format": "#0.0"
        },
        "overlap": 0,  # The range is +/- 100. The default is 0
        "gap": 340  # The range is 0 to 500. The default is 150
    })
    # fake series for a margin
    chart_add_series(chart, 1, {
        'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, "H", last_row),
        "categories": u"='{}'!A2:A{}".format(sheet_name, last_row),
        "name": u"='{0}'!{1}1".format(sheet_name, "H"),
        "data_labels": {
            "num_format": "#0.0%"
        },
        "y2_axis": 1
    })
    # CTR (поиск)
    chart_add_series(chart, 1, {
        'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, "G", last_row),
        "categories": u"='{}'!A2:A{}".format(sheet_name, last_row),
        "name": u"='{0}'!{1}1".format(sheet_name, "G"),
        "data_labels": {
            "num_format": "#0.0%"
        },
        "overlap": -100,
        "gap": 150,
        "y2_axis": 1
    })
    chart.set_legend({
        'position': 'bottom',
        "font": {'size': 14,
                 'bold': False,
                 'name': FONT_NAME},
        'delete_series': [1, 1]})
    sheet.insert_chart("A40", chart)

    return writer


def table_highlight_hist(df, normalize):
    """01_highlight_hist"""

    df_chart = table_highlight_type(df)
    df_chart = df_chart[(df_chart.ShowsSearch > 0)]
    if df_chart.shape[0] == 0:
        return None

    df_chart.PhraseBoldShare = (df_chart.PhraseBoldShare * 100).round(-1).astype(int).values
    df_chart = (df_chart[["DirectBannerID", "BSPhraseID", "ShowsSearch", "ClicksSearch", "CostSearch", "PhraseBoldShare"]]
                .groupby(["PhraseBoldShare"], as_index=True)
                .agg({"ShowsSearch": pd.np.sum,
                      "ClicksSearch": pd.np.sum,
                      "CostSearch": pd.np.sum,
                      "BSPhraseID": lambda x: x.unique().size,
                      "DirectBannerID": lambda x: x.unique().size}))

    df_chart["CTRSearch"] = df_chart["ClicksSearch"] / df_chart["ShowsSearch"]
    df_chart["CPCSearch"] = df_chart["CostSearch"] / df_chart["ClicksSearch"]

    df_chart.rename(columns={
        "BSPhraseID": u"Кол-во фраз",
        "DirectBannerID": u"Кол-во баннеров",
        "ShowsSearch": u"Показы (Поиск)",
        "ClicksSearch": u"Клики (Поиск)",
        "CostSearch": u"Затраты (Поиск)",
        "CPCSearch": u"CPC (Поиск)",
        "CTRSearch": u"CTR (Поиск)"},
        inplace=True)
    df_chart.index.names = [u"Подсветка"]
    df_chart = df_chart.loc[range(0, 120, 20)].fillna(0)

    if normalize:
        sum_cols = [u"Кол-во фраз", u"Кол-во баннеров",
                    u"Показы (Поиск)", u"Клики (Поиск)", u"Затраты (Поиск)"]
        max_cols = [u"CPC (Поиск)", u"CTR (Поиск)"]
        df_chart.loc[:, sum_cols] = df_chart.loc[:, sum_cols].apply(lambda x: x / x.sum())
        df_chart.loc[:, max_cols] = df_chart.loc[:, max_cols].apply(lambda x: x / x.max())

    return df_chart.loc[:, [u"Кол-во баннеров",
                            u"Кол-во фраз",
                            u"Показы (Поиск)",
                            u"Клики (Поиск)",
                            u"Затраты (Поиск)",
                            u"CPC (Поиск)",
                            u"CTR (Поиск)"]]


def plot_highlight_hist(writer, sheet_name, df):
    """
    (ExcelWriter, str, DataFrame) -> ExcelWriter
    01_highlight_hist
    """

    sheet = writer.book.get_worksheet_by_name(sheet_name)
    chart = Chart(writer.book, "column", None, u'Подсветка ключевых фраз')
    chart.set_y_axis({"name": u"Доля от общего",
                      'name_font': {"size": 16, "bold": False, "name": FONT_NAME},
                      'num_font': {"size": 14, "bold": False, "name": FONT_NAME},
                      'num_format': '#0%',
                      'major_tick_mark': 'none',
                      'minor_tick_mark': 'none',
                      'line': {'none': True}})
    cols = "BCDEF"
    last_row = df.index.size + 2
    for n, col in enumerate(cols):
        chart_add_series(chart, n, {
            'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, col, last_row),
            "categories": u"='{}'!A2:A{}".format(sheet_name, last_row),
            "name": u"='{0}'!{1}1".format(sheet_name, col),
            "data_labels": {"value": False}})

    sheet.insert_chart('A%s' % (last_row + 2), chart)

    return writer


def table_highlight_type_campaign(df):
    "01_campaign_highlight_type"

    df_export = table_highlight_type(df)
    df_export = df_export[df_export.ShowsSearch > 0]
    if df_export.shape[0] == 0:
        return None

    df_export = (df_export[[
        'CampaignID', 'BSPhraseID', 'PhraseBoldType', "ShowsSearch", "ClicksSearch", "CostSearch"]]
        .groupby(['CampaignID', 'PhraseBoldType'], as_index=True)
        .agg({
            'ShowsSearch': pd.np.sum,
            'ClicksSearch': pd.np.sum,
            'CostSearch': pd.np.sum,
            'BSPhraseID': pd.np.count_nonzero}))

    df_export["CTRSearch"] = df_export["ClicksSearch"] / df_export["ShowsSearch"]
    df_export["CPCSearch"] = df_export["CostSearch"] / df_export["ClicksSearch"]

    df_export.rename(columns={
        "BSPhraseID": u"Количество фраз",
        "ShowsSearch": u"Показы (поиск)",
        "ClicksSearch": u"Клики (поиск)",
        "CostSearch": u"Затраты (поиск)",
        "CTRSearch": u"CTR (поиск)",
        "CPCSearch": u"CPC (поиск)"},
        inplace=True)

    df_export.rename(index={
        "full": u"Полная",
        "partly": u"Частичная",
        "none": u"Отсуствует"},
        inplace=True)
    df_export.index.names = [u"Кампания №", u"Тип подсветки"]

    return df_export.loc[:, [u"Количество фраз",
                             u"Показы (поиск)",
                             u"Клики (поиск)",
                             u"Затраты (поиск)",
                             u"CPC (поиск)",
                             u"CTR (поиск)"]]
