# coding: utf-8
"""xlsx-reports:
  - 01_highlight_hist
  - 01_highlight_type
  - 01_campaign_highlight_type
"""
from ..xlsx_chart.chart import Chart, chart_add_series, FONT_NAME, FONT_SIZE
from ..utils import filter_by_adtype
from .utils import (
    add_cpc_search,
    add_ctr_search
)
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, "TEXT_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_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})
    )
    add_cpc_search(df_chart)
    add_ctr_search(df_chart)

    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"Подсветка"]
    try:
        df_chart = df_chart.loc[range(0, 120, 20), :].fillna(0)
    except KeyError:
        return None

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

    df_chart = df_chart.loc[:, [u"Кол-во объявлений",
                                u"Кол-во фраз",
                                u"Показы (Поиск)",
                                u"Клики (Поиск)",
                                u"Расходы (Поиск)",
                                u"CPC (Поиск)",
                                u"CTR (Поиск)"]]

    if normalize:
        formats = {
            u"Кол-во объявлений": "percent",
            u"Кол-во фраз": "percent",
            u"Показы (Поиск)": "percent",
            u"Клики (Поиск)": "percent",
            u"Расходы (Поиск)": "percent",
            u"CPC (Поиск)": "float",
            u"CTR (Поиск)": "float"}
    else:
        formats = {
            u"Кол-во объявлений": "int",
            u"Кол-во фраз": "int",
            u"Показы (Поиск)": "int",
            u"Клики (Поиск)": "int",
            u"Расходы (Поиск)": "float",
            u"CPC (Поиск)": "float",
            u"CTR (Поиск)": "percent"}

    setattr(df_chart, "formats", formats)

    return df_chart


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_x_axis({"name_font": {"size": FONT_SIZE, "bold": False, "name": FONT_NAME},
                      "num_font": {"size": FONT_SIZE, "bold": False, "name": FONT_NAME},
                      "major_tick_mark": "none",
                      "minor_tick_mark": "none",
                      "line": {"visible": True, "width": 1, "color": "#000000"},
                      "major_gridlines": {"visible": False}
                      })

    chart.set_y_axis({"name": u"Доля от общего",
                      "name_font": {"size": FONT_SIZE, "bold": False, "name": FONT_NAME},
                      "num_font": {"size": FONT_SIZE, "bold": False, "name": FONT_NAME},
                      "num_format": "#0%",
                      "major_tick_mark": "none",
                      "minor_tick_mark": "none",
                      "line": {"none": True},
                      "major_gridlines": {"visible": True,
                                          "line": {"width": 1, "color": "#d9d9d9"}}
                      })

    cols = "BCDEF"
    last_row = df.index.size + 1
    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},
            "gap": 150,
            "overlap": -20
        })

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

    return writer


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

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

    if normalize:
        formats = {
            u"Кол-во фраз": "percent",
            u"Показы (поиск)": "percent",
            u"Клики (поиск)": "percent",
            u"Расходы (поиск)": "percent",
            u"CPC (поиск)": "float",
            u"CTR (поиск)": "float"}
    else:
        formats = {
            u"Кол-во фраз": "int",
            u"Показы (поиск)": "int",
            u"Клики (поиск)": "int",
            u"Расходы (поиск)": "float",
            u"CPC (поиск)": "float",
            u"CTR (поиск)": "percent"}

    setattr(df_export, "formats", formats)

    return df_export


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 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}))

    add_cpc_search(df_export)
    add_ctr_search(df_export)

    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"Тип подсветки"]
    df_export = df_export.loc[:, [u"Кол-во фраз",
                                  u"Показы (поиск)",
                                  u"Клики (поиск)",
                                  u"Расходы (поиск)",
                                  u"CPC (поиск)",
                                  u"CTR (поиск)"]]

    setattr(df_export, "formats", {u"Кол-во фраз": "int",
                                   u"Показы (поиск)": "int",
                                   u"Клики (поиск)": "int",
                                   u"Расходы (поиск)": "float",
                                   u"CPC (поиск)": "float",
                                   u"CTR (поиск)": "percent"})

    return df_export
