# coding=utf-8
import os
import sys
import sqlite3
import argparse
import time
import traceback
import math
import warnings
from glob import glob

import pandas as pd
import xlsxwriter
from openpyxl import load_workbook


LOG_FILE = '.logerror.log'

warnings.filterwarnings("ignore")
wb_cnt = 0


class Timer:

    def __init__(self, quiet=True):
        self.begin_time_s = time.time()
        self._last_stop_s = self.begin_time_s
        self.is_quiet = quiet
        self.eventlog = []

    def __call__(self, label=''):
        current_time_s = time.time()
        last_call_elapsed = current_time_s - self._last_stop_s
        begin_elapsed = current_time_s - self.begin_time_s
        self._last_stop_s = current_time_s

        if not self.is_quiet:
            print "%s -- call: %.2f; total: %.2f" % (label, last_call_elapsed, begin_elapsed)

        event = label, last_call_elapsed, begin_elapsed
        self.eventlog.append(event)

        return event

    def top(self, n=5):
        return sorted(self.eventlog, key=lambda e: e[1], reverse=True)[:n]


def get_group(x, step):
    if x <= step:
        return 1
    elif step < x <= step * 2:
        return 2
    elif step * 2 < x <= step * 3:
        return 3
    else:
        return 4


def calculate_leader_share(df, cols, client, period):

    cat_df = df.copy()
    cat_df = cat_df.groupby(u'Month').sum()

    client_df = df.copy()
    client_df = client_df[client_df.Client == client]
    client_df = client_df.groupby(u'Month').sum()
    leader_df = pd.DataFrame()
    rating_df = pd.DataFrame()

    for i, col in enumerate(cols):
        tmp = df.groupby('Month').apply(lambda group: group.sort(columns=[col], ascending=False).iloc[0])
        if leader_df.empty:
            leader_df = pd.DataFrame(tmp[u'Client'])
        else:
            leader_df = leader_df.merge(pd.DataFrame(tmp[u'Client']), how='inner', left_index=True, right_index=True)
        leader_df = leader_df.rename(columns={u'Client': u'Leader_%s' % col})
        leader_df['leader_share_%s' % col] = tmp[col] / cat_df[col]
        leader_df['client_share_%s' % col] = client_df[col] / cat_df[col]

        top_ten_df = df.copy()
        top_ten_df = top_ten_df.query('Month >= %i & Month <= %i' % (int(period[:6]), int(period[-6:])))
        top_ten_df = pd.DataFrame(top_ten_df.groupby('Client').sum())
        top_clients = (
            pd.DataFrame(top_ten_df.sort(columns=[col], ascending=False).head(10))
            .reset_index()
            .Client
            .tolist()[:10]
        )
        if client not in top_clients:
            top_clients.insert(0, client)
            top_clients = top_clients[:10]
        else:
            top_clients.insert(0, top_clients.pop(top_clients.index(client)))
        top_ten_df = top_ten_df.ix[top_clients]

        top_ten_df = top_ten_df.reset_index()
        top_ten_df = top_ten_df.sort(columns=[col], ascending=False)

        top_ten_df.loc[10, col] = round(
            float(
                float(
                    df.query(
                        'Month >= %i & Month <= %i' % (int(period[:6]), int(period[-6:]))
                    )[col].sum()
                )
            ) - float(top_ten_df[col].sum()),
            4,
        )
        top_ten_df.loc[10, u'Client'] = u'Прочие'
        if rating_df.empty:
            rating_df = pd.DataFrame(top_ten_df[[u'Client', col]])
            rating_df = rating_df.rename(columns={u'Client': u'Client_%s' % col})
        else:
            rating_df[u'Client_%s' % col] = top_ten_df[u'Client']
            rating_df[col] = top_ten_df[col]

    leader_df = leader_df.reset_index()
    leader_df = leader_df.fillna(0)

    rating_df = rating_df.reset_index()
    rating_df = rating_df.fillna(0)
    del rating_df['index']
    return leader_df, rating_df


def calculate_percentiles(df, criteria, argument, param1, param2, share=95, g_count=4):

    df = df[df[param1] != 0]
    df[argument] = df[param1] / df[param2]

    df = df.replace(to_replace=[pd.np.nan, pd.np.inf, -pd.np.inf], value=0)
    df = df.sort(columns=[criteria], ascending=False)
    df[u'Share'] = df[criteria].cumsum() / df[criteria].sum() * 100
    df = df[df[u'Share'] <= share]
    step = math.ceil(float(len(list(df.Client))) / float(g_count))
    if step < 4:
        return None
    else:
        df.index = range(0, len(list(df.Client)))
        df[u'index'] = df.index
        df['group'] = df.apply(lambda x: get_group(x[u'index'], step), axis=1)

        data = dict()
        i = 0
        for x in set(df.group):
            tmp_df = df[df.group == x]
            tmp_df = tmp_df.replace(to_replace=[pd.np.nan, pd.np.inf, -pd.np.inf], value=0)
            tmp_df = tmp_df.sort(columns=[argument], ascending=False)
            c_amount = len(list(tmp_df.Client))
            if c_amount >= 4:
                i += 1
                data[i] = dict()
                data[i][u'labels'] = tmp_df[criteria].mean()
                data[i][u'25%'] = tmp_df[argument].iloc[c_amount / 4]
                data[i][u'50%'] = tmp_df[argument].iloc[c_amount / 2]
                data[i][u'75%'] = tmp_df[argument].iloc[c_amount / 4 * 3]
                data[i][u'Clients_amount'] = pd.np.int(c_amount)

        res_df = pd.DataFrame.from_dict(data).T
        res_df = res_df.reset_index()
        res_df = res_df.rename(columns={u'index': u'Category'})
        return res_df


def prettify_months(months):
    DIG_IN_MONTH = {
        '01': u'январь',
        '02': u'февраль',
        '03': u'март',
        '04': u'апрель',
        '05': u'май',
        '06': u'июнь',
        '07': u'июль',
        '08': u'август',
        '09': u'сентябрь',
        '10': u'октябрь',
        '11': u'ноябрь',
        '12': u'декабрь',
    }
    pretty_months = []
    for e in sorted(months):
        year, month = str(e)[:4], str(e)[-2:]
        if month == '01':
            month = ''
        else:
            year = ''
            month = DIG_IN_MONTH[month][:3]
        pretty_months.append(''.join([year, month]))
    return pretty_months


def transliterate(string):
    if not isinstance(string, unicode):
        string = unicode(string)

    capital_letters = {
        u'А': u'A',
        u'Б': u'B',
        u'В': u'V',
        u'Г': u'G',
        u'Д': u'D',
        u'Е': u'E',
        u'Ё': u'E',
        u'Ж': u'Zh',
        u'З': u'Z',
        u'И': u'I',
        u'Й': u'Y',
        u'К': u'K',
        u'Л': u'L',
        u'М': u'M',
        u'Н': u'N',
        u'О': u'O',
        u'П': u'P',
        u'Р': u'R',
        u'С': u'S',
        u'Т': u'T',
        u'У': u'U',
        u'Ф': u'F',
        u'Х': u'H',
        u'Ц': u'Ts',
        u'Ч': u'Ch',
        u'Ш': u'Sh',
        u'Щ': u'Sch',
        u'Ъ': u'',
        u'Ы': u'Y',
        u'Ь': u'',
        u'Э': u'E',
        u'Ю': u'Yu',
        u'Я': u'Ya',
    }

    lower_case_letters = {
        u'а': u'a',
        u'б': u'b',
        u'в': u'v',
        u'г': u'g',
        u'д': u'd',
        u'е': u'e',
        u'ё': u'e',
        u'ж': u'zh',
        u'з': u'z',
        u'и': u'i',
        u'й': u'y',
        u'к': u'k',
        u'л': u'l',
        u'м': u'm',
        u'н': u'n',
        u'о': u'o',
        u'п': u'p',
        u'р': u'r',
        u'с': u's',
        u'т': u't',
        u'у': u'u',
        u'ф': u'f',
        u'х': u'h',
        u'ц': u'ts',
        u'ч': u'ch',
        u'ш': u'sh',
        u'щ': u'sch',
        u'ъ': u'',
        u'ы': u'y',
        u'ь': u'',
        u'э': u'e',
        u'ю': u'yu',
        u'я': u'ya',
    }

    translit_string = ""

    for index, char in enumerate(string):
        if char in lower_case_letters.keys():
            char = lower_case_letters[char]
        elif char in capital_letters.keys():
            char = capital_letters[char]
            if len(string) > index + 1:
                if string[index + 1] not in lower_case_letters.keys():
                    char = char.upper()
            else:
                char = char.upper()
        translit_string += char

    return translit_string


def fill_null(conn, months, categories, client, regions, src_tbl='data'):
    u"""Заполнитель сегментов дефолтными значения метрик.

    Note:
    При многократном запуске может сильно увеличить объем базы.

    #todo:
    - записывать только реально отсутствующее
    """
    list_of_null_vals = []
    for month in months:
        for cat in categories:
            for cl in client:
                if len(regions) != 0:
                    for region in regions:
                        list_of_null_vals.append([month, cat, cl, region])
                else:
                    list_of_null_vals.append([month, cat, cl])
    if regions:
        loader = u'INSERT INTO {table} (Month, CustomCategory, Client, Region) VALUES ({values})'.format(
            table=src_tbl, values=u", ".join(u'?' * 4)
        )
    else:
        loader = u'INSERT INTO {table} ("Month", "CustomCategory", "Client") VALUES ({values})'.format(
            table=src_tbl, values=u", ".join(u'?' * 3)
        )
    curs = conn.cursor()
    curs.executemany(loader, list_of_null_vals)
    conn.commit()


def make_tmp_table(
    conn,
    months, competitors, clients, regions, categories,
    tmp_tbl, tmp_tbl_comp_m, tmp_tbl_comp_q, src_tbl='data',
):
    u"""Подготовка общих таблиц для последующего анализа.

    Note:
    tmp_tbl        -- отфильтровано по заданию, добавлен квартал
    tmp_tbl_comp_m -- аггрегаты для tmp_tbl по месяцам, категориям
    tmp_tbl_comp_q --аггрегаты для tmp_tbl по полным кварталам, категориям
    """

    curs = conn.cursor()

    for tbl in (tmp_tbl, tmp_tbl_comp_m, tmp_tbl_comp_q):
        curs.execute(u'DROP TABLE IF EXISTS %s' % tbl)
    conn.commit()

    # отфильтрованное
    elem = u"""
            "Month" TEXT,
            "Client" TEXT,
            "CustomCategory" TEXT,
            "Direct_Shows" INTEGER,
            "Direct_Clicks" INTEGER,
            "Direct_Cost" REAL,
            "RSYA_Shows" INTEGER,
            "RSYA_Clicks" INTEGER,
            "RSYA_Cost" REAL,
            "Shows" INTEGER,
            "Clicks" INTEGER,
            "Cost" REAL,
            "Region" TEXT,
            "Qvartal" TEXT
            """
    curs.execute(
        u'CREATE TEMPORARY TABLE {table} ({fields_type})'.format(
            table=tmp_tbl, fields_type=elem
        )
    )
    fields = u"""
                "Month",
                "Client",
                "CustomCategory",
                "Direct_Shows", "Direct_Clicks", "Direct_Cost",
                "RSYA_Shows", "RSYA_Clicks", "RSYA_Cost",
                "Shows", "Clicks", "Cost",
                "Region" """

    months = join4filter(months)
    competitors = join4filter(set(competitors + clients))
    categories = join4filter(categories)
    if regions:
        regions = join4filter(regions)

    if regions:
        curs.execute(
            u"""INSERT INTO {TMP_TABLE} ({FIELDS}, "Qvartal")
                SELECT {FIELDS}
                , ("Q"||((CAST(SUBSTR(Month, 5, 2) AS INTEGER) + 2) / 3 )||"'"||SUBSTR(Month, 3, 2))
                FROM {SRC_TABLE}
                WHERE Month IN ({MONTHS})
                  AND Client IN ({COMPETITORS})
                  AND CustomCategory IN ({CATEGORIES})
                  AND Region in ({REGIONS})""".format(
                FIELDS=fields, TMP_TABLE=tmp_tbl, SRC_TABLE=src_tbl, MONTHS=months,
                COMPETITORS=competitors, CATEGORIES=categories, REGIONS=regions
            )
        )
    else:
        curs.execute(
            u"""INSERT INTO {TMP_TABLE} ({FIELDS}, "Qvartal")
                SELECT {FIELDS}
                , ("Q"||((CAST(SUBSTR(Month, 5, 2) AS INTEGER) + 2) / 3 )||"'"||SUBSTR(Month, 3, 2))
                FROM {SRC_TABLE}
                WHERE Month IN ({MONTHS})
                  AND Client IN ({COMPETITORS})
                  AND CustomCategory IN ({CATEGORIES})""".format(
                FIELDS=fields, TMP_TABLE=tmp_tbl, SRC_TABLE=src_tbl, MONTHS=months,
                COMPETITORS=competitors, CATEGORIES=categories
            )
        )
    # аггрегаты по месяцам, категориям
    curs.execute(
        u"""CREATE TEMPORARY TABLE %s
              (Month TEXT, CustomCategory TEXT, Cost REAL, Clicks INTEGER, CompCount INTEGER)
        """ % tmp_tbl_comp_m
    )
    curs.execute(
        u"""INSERT INTO """ + tmp_tbl_comp_m + u"""
            SELECT
              Month
            , CustomCategory
            , sum(Cost)
            , sum(Clicks)
            , CAST(count(DISTINCT Client) AS INTEGER)
            FROM """ + tmp_tbl + u"""
            GROUP BY Month, CustomCategory"""
    )
    # аггрегаты по полным кварталам, категориям
    curs.execute(
        u"""CREATE TEMPORARY TABLE %s
              (Qvartal TEXT, Month TEXT, CustomCategory TEXT, Cost REAL, Clicks INTEGER, CompCount INTEGER)
        """ % tmp_tbl_comp_q
    )
    curs.execute(
        u"""INSERT INTO """ + tmp_tbl_comp_q + u"""
            SELECT
              Qvartal
            , Month
            , CustomCategory
            , sum(Cost)
            , sum(Clicks)
            , CAST(count(DISTINCT Client) AS INTEGER)
            FROM """ + tmp_tbl + u"""
            GROUP BY Qvartal, CustomCategory
            HAVING COUNT(DISTINCT Month) = 3"""
    )
    conn.commit()


def _make_report(
    conn,
    cl, cat,
    categories, industry, months, competitors, regions,
    tgt_region, period_1, period_2, share, cur,
    TMP_TBL, TMP_TABLE_COMP_MONTHS, TMP_TABLE_COMP_QVART, DST_DIR
):

    stopwatch = Timer(quiet=not os.path.exists(LOG_FILE))
    stopwatch("\n## %s, %s" % (cl, cat))
    DIG_IN_MONTH = {
        '01': u'январь',
        '02': u'февраль',
        '03': u'март',
        '04': u'апрель',
        '05': u'май',
        '06': u'июнь',
        '07': u'июль',
        '08': u'август',
        '09': u'сентябрь',
        '10': u'октябрь',
        '11': u'ноябрь',
        '12': u'декабрь',
    }
    global wb_cnt

    # необходимо путь /Users/leroy/Desktop/Builder-new/CastomsZA/Result/26символов.xlsx уместить в 81 символ.
    # workbook_fullName = 'Result/' + transliterate(cl) + '_' + transliterate(cat) + '.xlsx'
    max_wbName = 60 - len(os.path.realpath('Result'))
    workbook_shortName = '{dst_dir}/{client}_{category}_{cnt}.xlsx' \
        .format(
            dst_dir=DST_DIR,
            client=transliterate(cl)[:max_wbName / 2],
            category=transliterate(cat)[:max_wbName / 2],
            cnt=str(wb_cnt + 1)
        )
    if not os.path.exists(workbook_shortName):
        workbook = xlsxwriter.Workbook(workbook_shortName, {'nan_inf_to_errors': True})
        wb_cnt += 1

    cell_str_format = workbook.add_format(
        {
            'font_name': 'Textbook New',
            'font_size': '10',
            'bold': False,
            'align': 'left',
            'valign': 'vcenter',
            'text_wrap': False,
            'num_format': '0.00',
        })

    cell_str_format_bold = workbook.add_format(
        {
            'font_name': 'Textbook New',
            'color': 'red',
            'font_size': '10',
            'bold': True,
            'align': 'left',
            'valign': 'vcenter',
            'text_wrap': False,
            'num_format': '0.00',
        })

    merge_format = workbook.add_format(
        {
            'font_name': 'Textbook New',
            'font_size': '12',
            'bold': True,
            'align': 'center',
            'valign': 'vcenter',
            'text_wrap': True,
            'bg_color': '#a5a5a5',
        })

    title1_format = workbook.add_format(
        {
            'font_name': 'Textbook New',
            'font_size': '24',
            'bold': True,
            'align': 'center',
            'valign': 'vcenter',
            'text_wrap': True,
        })

    title2_format = workbook.add_format(
        {
            'font_name': 'Textbook New',
            'font_size': '14',
            'bold': True,
            'align': 'center',
            'valign': 'vcente',
            'text_wrap': True,
        })

    str_format = workbook.add_format(
        {
            'font_name': 'Textbook New',
            'font_size': '12',
            'bold': False,
            'align': 'center',
            'valign': 'vcenter',
            'text_wrap': True,
        })
    ########
    # Info #
    ########
    worksheet_info = workbook.add_worksheet(u'Info')
    worksheet_info.merge_range(0, 0, 3, 5, u'Клиентская аналитика', title1_format)
    worksheet_info.merge_range(5, 1, 7, 4, u'Сборная категория', title2_format)
    worksheet_info.merge_range(10, 1, 11, 4, u'Отчет построен для:', title2_format)
    worksheet_info.merge_range(13, 1, 13, 4, cl, str_format)
    worksheet_info.merge_range(16, 1, 17, 4, u'В категории:', title2_format)
    worksheet_info.merge_range(19, 0, 19, 5, cat, str_format)
    worksheet_info.merge_range(21, 1, 22, 4, u'На месяц', title2_format)
    worksheet_info.merge_range(24, 1, 24, 4, " ".join([DIG_IN_MONTH[months[-1][-2:]], months[-1][:4]]), str_format)

    worksheet_info.merge_range(36, 1, 37, 4, u'Валюта:', title2_format)
    worksheet_info.merge_range(39, 1, 39, 4, cur, str_format)

    worksheet_info.merge_range(41, 1, 42, 2, u'Период 1:', title2_format)
    worksheet_info.merge_range(41, 3, 42, 4, u'Период 2:', title2_format)

    stopwatch("Info")

    ########
    # Meta #
    ########
    worksheet_meta = workbook.add_worksheet(u'Meta')
    worksheet_meta.write_row(0, 0, (u'Месяца', u'Конкуренты', u'Регионы', u'Целевые регионы'))
    worksheet_meta.write_column(1, 0, months)
    worksheet_meta.write_column(1, 1, competitors)
    worksheet_meta.write_column(1, 2, regions)
    worksheet_meta.write_column(1, 3, tgt_region.replace('"', '').split(', '))

    stopwatch("Meta")

    ###########
    # DataCat #
    ###########
    worksheet_datacat = workbook.add_worksheet(u'DataCat')
    worksheet_datacat.set_column(2, 12, 16)
    worksheet_datacat.write_row(0, 0, (u'Month', u'Qvartal', u'CustomCategory', u'Region', u'Direct_Shows',
                                       u'Direct_Clicks', u'Direct_Cost', u'RSYA_Shows', u'RSYA_Clicks',
                                       u'RSYA_Cost', u'Shows', u'Clicks', u'Cost'), str_format)
    curs = conn.cursor()
    curs.execute(
        u"""SELECT
              Month
            , Qvartal
            , CustomCategory
            , Region
            , sum(Direct_Shows)
            , sum(Direct_Clicks)
            , sum(Direct_Cost)
            , sum(RSYA_Shows)
            , sum(RSYA_Clicks)
            , sum(RSYA_Cost)
            , sum(Shows)
            , sum(Clicks)
            , sum(Cost)
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Month, Region
            ORDER BY Month, Region ASC"""
    )

    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_datacat.write_row(1 + n, 0, data_frame[n])

    stopwatch("DataCat")

    ##############
    # DataClient #
    ##############
    worksheet_dataclient = workbook.add_worksheet(u'DataClient')
    worksheet_dataclient.set_column(2, 12, 17)
    worksheet_dataclient.write_row(0, 0,
                                   (u'Month', u'Qvartal', u'Client', u'CustomCategory', u'Region', u'Direct_Shows',
                                    u'Direct_Clicks', u'Direct_Cost', u'RSYA_Shows', u'RSYA_Clicks',
                                    u'RSYA_Cost', u'Shows', u'Clicks', u'Cost'), str_format)

    curs.execute(
        u"""SELECT
              Month
            , Qvartal
            , Client
            , CustomCategory
            , Region
            , sum(Direct_Shows)
            , sum(Direct_Clicks)
            , sum(Direct_Cost)
            , sum(RSYA_Shows)
            , sum(RSYA_Clicks)
            , sum(RSYA_Cost)
            , sum(Shows)
            , sum(Clicks)
            , sum(Cost)
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            AND Client IN (\"""" + cl + u"""\")
            GROUP BY Month, Region, Client
            ORDER BY Month, Client, Region ASC"""
    )

    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_dataclient.write_row(1 + n, 0, data_frame[n])

    stopwatch("DataClient")

    ######################
    # Вкладки про Показы #
    ######################
    # По месяцам
    worksheet_shows = workbook.add_worksheet(u'Показы')
    worksheet_shows.merge_range(0, 1, 0, 3, cat, merge_format)
    worksheet_shows.merge_range(0, 4, 0, 6, cl, merge_format)
    worksheet_shows.write_row(
        1, 0,
        (u'Месяц', u'Поиск', u'РСЯ', u'Всего', u'Поиск', u'РСЯ', u'Всего'),
        cell_str_format,
    )

    competitors = "\"" + "\", \"".join(competitors) + "\""
    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month,1,4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
                END AS "Месяц"
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Shows ELSE 0 END))
            ,""".format(COMPETITORS=competitors) + """
                ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Shows ELSE 0 END))
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Month
            ORDER BY Month ASC""".format(COMPETITORS=competitors)
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_shows.write_row(2 + n, 0, data_frame[n])

    # По кварталам
    worksheet_shows.merge_range(0, 9, 0, 11, cat, merge_format)
    worksheet_shows.merge_range(0, 12, 0, 14, cl, merge_format)
    worksheet_shows.write_row(
        1, 8,
        (u'Квартал', u'Поиск', u'РСЯ', u'Всего', u'Поиск', u'РСЯ', u'Всего'),
        cell_str_format
    )

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Shows ELSE 0 END))
            ,""".format(COMPETITORS=competitors) + """
            ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Shows ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Shows ELSE 0 END))
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )

    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_shows.write_row(2 + n, 8, data_frame[n])

    stopwatch("Показы")

    #####################
    # Вкладки про Клики #
    #####################
    # По месяцам
    worksheet_clicks = workbook.add_worksheet(u'Клики')

    worksheet_clicks.merge_range(0, 1, 0, 3, cat, merge_format)
    worksheet_clicks.merge_range(0, 4, 0, 6, cl, merge_format)
    worksheet_clicks.write_row(
        1, 0,
        (u'Месяц', u'Поиск', u'РСЯ', u'Всего', u'Поиск', u'РСЯ', u'Всего'),
        cell_str_format
    )

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END))
            ,""".format(COMPETITORS=competitors) + """
              ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END))
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Month
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_clicks.write_row(2 + n, 0, data_frame[n])

    # По кварталам
    worksheet_clicks.merge_range(0, 9, 0, 11, cat, merge_format)
    worksheet_clicks.merge_range(0, 12, 0, 14, cl, merge_format)
    worksheet_clicks.write_row(1, 8, (u'Квартал', u'Поиск', u'РСЯ', u'Всего', u'Поиск', u'РСЯ', u'Всего'),
                               cell_str_format)

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END))
            , """.format(COMPETITORS=competitors) + """
              ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END))
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )

    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_clicks.write_row(2 + n, 8, data_frame[n])

    stopwatch("Клики")

    ########################
    # Вкладки про Открутки #
    ########################
    # По месяцам
    worksheet_cost = workbook.add_worksheet(u'Открутки')

    worksheet_cost.merge_range(0, 1, 0, 3, cat, merge_format)
    worksheet_cost.merge_range(0, 4, 0, 6, cl, merge_format)
    worksheet_cost.write_row(
        1, 0,
        (u'Месяц', u'Поиск', u'РСЯ', u'Всего', u'Поиск', u'РСЯ', u'Всего'),
        cell_str_format
    )

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month, 5, 2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Cost ELSE 0 END))
            , """.format(COMPETITORS=competitors) + """
              ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Cost ELSE 0 END))
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Month
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_cost.write_row(2 + n, 0, data_frame[n])

    # По кварталам
    worksheet_cost.merge_range(0, 9, 0, 11, cat, merge_format)
    worksheet_cost.merge_range(0, 12, 0, 14, cl, merge_format)
    worksheet_cost.write_row(1, 8, (u'Квартал', u'Поиск', u'РСЯ', u'Всего', u'Поиск', u'РСЯ', u'Всего'),
                             cell_str_format)

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Cost ELSE 0 END))
            , """.format(COMPETITORS=competitors) + """
              ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Cost ELSE 0 END))
            , ROUND(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Cost ELSE 0 END))
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )

    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_cost.write_row(2 + n, 8, data_frame[n])

    stopwatch("Открутки")

    ##################
    # Средний бюджет #
    ##################
    worksheet_avgcost = workbook.add_worksheet(u'Средний бюджет')
    # По месяцам
    worksheet_avgcost.merge_range(0, 1, 0, 9, cat, merge_format)
    worksheet_avgcost.write_row(1, 0, (u'Месяц', u'Min_dir', u'Max_dir', u'Avg_dir', u'Min_rsya', u'Max_rsya',
                                       u'Avg_rsya', u'Min', u'Max', u'Avg'))

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(tmp_month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(tmp_month,1,4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , CAST(ROUND(MIN(tmp_dir_cost)) AS INTEGER)
            , CAST(ROUND(MAX(tmp_dir_cost)) AS INTEGER)
            , CAST(ROUND(AVG(tmp_dir_cost)) AS INTEGER)
            , CAST(ROUND(MIN(tmp_rsya_cost)) AS INTEGER)
            , CAST(ROUND(MAX(tmp_rsya_cost)) AS INTEGER)
            , CAST(ROUND(AVG(tmp_rsya_cost)) AS INTEGER)
            , CAST(ROUND(MIN(tmp_cost)) AS INTEGER)
            , CAST(ROUND(MAX(tmp_cost)) AS INTEGER)
            , CAST(ROUND(AVG(tmp_cost)) AS INTEGER)
            FROM (
                SELECT
                  sum(Direct_Cost) AS tmp_dir_cost
                , sum(RSYA_Cost) AS tmp_rsya_cost
                , sum(Cost) AS tmp_cost
                , Month AS tmp_month
                FROM """ + TMP_TBL + u"""
                WHERE Client In ({COMPETITORS})""".format(COMPETITORS=competitors) + """
                  AND CustomCategory IN (\"""" + cat + u"""\")
                GROUP BY Month, Client
            )
            GROUP BY tmp_month
            ORDER BY tmp_month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_avgcost.write_row(2 + n, 0, data_frame[n])

    # По кварталам
    worksheet_avgcost.merge_range(0, 13, 0, 21, cat, merge_format)
    worksheet_avgcost.write_row(
        1, 12,
        (
            u'Квартал',
            u'Min_dir', u'Max_dir', u'Avg_dir',
            u'Min_rsya', u'Max_rsya', u'Avg_rsya',
            u'Min', u'Max', u'Avg',
        )
    )

    curs.execute(
        u"""SELECT
              tmp_qvart
            , CAST(ROUND(MIN(tmp_dir_cost)) AS INTEGER)
            , CAST(ROUND(MAX(tmp_dir_cost)) AS INTEGER)
            , CAST(ROUND(AVG(tmp_dir_cost)) AS INTEGER)
            , CAST(ROUND(MIN(tmp_rsya_cost)) AS INTEGER)
            , CAST(ROUND(MAX(tmp_rsya_cost)) AS INTEGER)
            , CAST(ROUND(AVG(tmp_rsya_cost)) AS INTEGER)
            , CAST(ROUND(MIN(tmp_cost)) AS INTEGER)
            , CAST(ROUND(MAX(tmp_cost)) AS INTEGER)
            , CAST(ROUND(AVG(tmp_cost)) AS INTEGER)
            FROM (
                    SELECT
                      sum(Direct_Cost) AS tmp_dir_cost
                    , sum(RSYA_Cost) AS tmp_rsya_cost
                    , sum(Cost) AS tmp_cost
                    , Month AS tmp_month
                    , Qvartal AS tmp_qvart
                    FROM """ + TMP_TBL + u"""
                    WHERE Client In ({COMPETITORS})""".format(COMPETITORS=competitors) + """
                      AND CustomCategory IN (\"""" + cat + u"""\")
                    GROUP BY Qvartal, Client
                    HAVING COUNT(DISTINCT Month) = 3
                )
            GROUP BY tmp_qvart
            ORDER BY tmp_month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_avgcost.write_row(2 + n, 12, data_frame[n])

    stopwatch("Средний бюджет")

    #################################
    # Рейтинг бюджетов по кварталам #
    #################################
    worksheet_reiting = workbook.add_worksheet(u'Рейтинг по кварталам (бюджеты)')
    worksheet_reiting.write(0, 0, u'Ранг')
    worksheet_reiting.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT Qvartal
            FROM """ + TMP_TBL + u"""
            GROUP BY Qvartal
            HAVING count(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    list_full_qvart = curs.fetchall()
    worksheet_reiting.set_column(1, len(list_full_qvart), 20)

    for i, q in enumerate(list_full_qvart):
        worksheet_reiting.write(0, i + 1, q[0], str_format)
        curs.execute(
            u"""SELECT Client
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal in (\"""" + q[0] + u"""\")
                    AND CustomCategory IN (\"""" + cat + u"""\")
                GROUP BY Qvartal, Client
                HAVING sum(Cost) != 0
                ORDER BY sum(Cost) DESC
                LIMIT 30"""
        )
        data_frame = curs.fetchall()
        for n, c in enumerate(data_frame):
            if c[0] != cl:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format)
            else:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format_bold)

    worksheet_reiting = workbook.add_worksheet(u'Рейтинг по кварталам (б, поиск)')
    worksheet_reiting.write(0, 0, u'Ранг')
    worksheet_reiting.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT Qvartal
            FROM """ + TMP_TBL + u"""
            GROUP BY Qvartal
            HAVING count(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    list_full_qvart = curs.fetchall()
    worksheet_reiting.set_column(1, len(list_full_qvart), 20)

    for i, q in enumerate(list_full_qvart):
        worksheet_reiting.write(0, i + 1, q[0], str_format)
        curs.execute(
            u"""SELECT Client
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal in (\"""" + q[0] + u"""\")
                    AND CustomCategory IN (\"""" + cat + u"""\")
                GROUP BY Qvartal, Client
                HAVING sum(Direct_Cost) != 0
                ORDER BY sum(Direct_Cost) DESC
                LIMIT 30"""
        )
        data_frame = curs.fetchall()
        for n, c in enumerate(data_frame):
            if c[0] != cl:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format)
            else:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format_bold)

    worksheet_reiting = workbook.add_worksheet(u'Рейтинг по кварталам (б, РСЯ)')
    worksheet_reiting.write(0, 0, u'Ранг')
    worksheet_reiting.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT Qvartal
            FROM """ + TMP_TBL + u"""
            GROUP BY Qvartal
            HAVING count(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    list_full_qvart = curs.fetchall()
    worksheet_reiting.set_column(1, len(list_full_qvart), 20)

    for i, q in enumerate(list_full_qvart):
        worksheet_reiting.write(0, i + 1, q[0], str_format)
        curs.execute(
            u"""SELECT Client
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal in (\"""" + q[0] + u"""\")
                    AND CustomCategory IN (\"""" + cat + u"""\")
                GROUP BY Qvartal, Client
                HAVING sum(RSYA_Cost) != 0
                ORDER BY sum(RSYA_Cost) DESC
                LIMIT 30"""
        )
        data_frame = curs.fetchall()
        for n, c in enumerate(data_frame):
            if c[0] != cl:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format)
            else:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format_bold)

    stopwatch("Рейтинг по кварталам (бюджеты)")

    #################################
    # Рейтинг кликов по кварталам #
    #################################
    worksheet_reiting = workbook.add_worksheet(u'Рейтинг по кварталам (клики)')
    worksheet_reiting.write(0, 0, u'Ранг')
    worksheet_reiting.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT Qvartal
            FROM """ + TMP_TBL + u"""
            GROUP BY Qvartal
            HAVING count(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    list_full_qvart = curs.fetchall()
    worksheet_reiting.set_column(1, len(list_full_qvart), 20)

    for i, q in enumerate(list_full_qvart):
        worksheet_reiting.write(0, i + 1, q[0], str_format)
        curs.execute(
            u"""SELECT Client
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal in (\"""" + q[0] + u"""\")
                    AND CustomCategory IN (\"""" + cat + u"""\")
                GROUP BY Qvartal, Client
                HAVING sum(Clicks) != 0
                ORDER BY sum(Clicks) DESC
                LIMIT 30"""
        )
        data_frame = curs.fetchall()
        for n, c in enumerate(data_frame):
            if c[0] != cl:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format)
            else:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format_bold)

    worksheet_reiting = workbook.add_worksheet(u'Рейтинг по кварталам (к, поиск)')
    worksheet_reiting.write(0, 0, u'Ранг')
    worksheet_reiting.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT Qvartal
            FROM """ + TMP_TBL + u"""
            GROUP BY Qvartal
            HAVING count(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    list_full_qvart = curs.fetchall()
    worksheet_reiting.set_column(1, len(list_full_qvart), 20)

    for i, q in enumerate(list_full_qvart):
        worksheet_reiting.write(0, i + 1, q[0], str_format)
        curs.execute(
            u"""SELECT Client
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal in (\"""" + q[0] + u"""\")
                    AND CustomCategory IN (\"""" + cat + u"""\")
                GROUP BY Qvartal, Client
                HAVING sum(Direct_Clicks) != 0
                ORDER BY sum(Direct_Clicks) DESC
                LIMIT 30"""
        )
        data_frame = curs.fetchall()
        for n, c in enumerate(data_frame):
            if c[0] != cl:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format)
            else:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format_bold)

    worksheet_reiting = workbook.add_worksheet(u'Рейтинг по кварталам (к, РСЯ)')
    worksheet_reiting.write(0, 0, u'Ранг')
    worksheet_reiting.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT Qvartal
            FROM """ + TMP_TBL + u"""
            GROUP BY Qvartal
            HAVING count(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    list_full_qvart = curs.fetchall()
    worksheet_reiting.set_column(1, len(list_full_qvart), 20)

    for i, q in enumerate(list_full_qvart):
        worksheet_reiting.write(0, i + 1, q[0], str_format)
        curs.execute(
            u"""SELECT Client
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal in (\"""" + q[0] + u"""\")
                    AND CustomCategory IN (\"""" + cat + u"""\")
                GROUP BY Qvartal, Client
                HAVING sum(RSYA_Clicks) != 0
                ORDER BY sum(RSYA_Clicks) DESC
                LIMIT 30"""
        )
        data_frame = curs.fetchall()
        for n, c in enumerate(data_frame):
            if c[0] != cl:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format)
            else:
                worksheet_reiting.write(1 + n, i + 1, c[0], cell_str_format_bold)

    stopwatch("Рейтинг по кварталам (клики)")

    ############################
    # Вкладка про динамику СРС #
    ############################
    worksheet_cpc_dyn = workbook.add_worksheet(u'Динамика СРС')
    # По месяцам
    worksheet_cpc_dyn.merge_range(0, 1, 0, 3, cat, merge_format)
    worksheet_cpc_dyn.merge_range(0, 4, 0, 6, cl, merge_format)
    worksheet_cpc_dyn.write_row(
        1, 0,
        (u'Месяц', u'CPC (поиск)', u'CPC (РСЯ)', u'CPC', u'CPC (поиск)', u'CPC (РСЯ)', u'CPC'),
        cell_str_format,
    )
    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month, 5, 2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(
                sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Clicks ELSE 0 END),
                2
              ) AS "CPC (поиск)"
            , ROUND(
                sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END),
                2
              ) AS "CPC (РСЯ)"
            , ROUND(
                sum(CASE WHEN (Client IN({COMPETITORS})) THEN Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END),
                2
              ) AS "CPC"
            , """.format(COMPETITORS=competitors) + """
              ROUND(
                  sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Cost ELSE 0 END) /
                     sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Clicks ELSE 0 END),
                  2
              )
            , ROUND(
                sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END),
                2
              )
            , ROUND(
                sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END),
                2
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Month
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_cpc_dyn.write_row(2 + n, 0, data_frame[n], cell_str_format)

    # По Кварталам
    worksheet_cpc_dyn.merge_range(0, 9, 0, 11, cat, merge_format)
    worksheet_cpc_dyn.merge_range(0, 12, 0, 14, cl, merge_format)
    worksheet_cpc_dyn.write_row(1, 8, (u'Квартал', u'CPC (поиск)', u'CPC (РСЯ)', u'CPC',
                                       u'CPC (поиск)', u'CPC (РСЯ)', u'CPC'), cell_str_format)

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(
                sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Cost ELSE 0 END) /
                   sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Clicks ELSE 0 END),
                2
              ) AS "CPC (поиск)"
            , ROUND(
                sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END),
                2
              ) AS "CPC (РСЯ)"
            , ROUND(
                sum(CASE WHEN (Client IN({COMPETITORS})) THEN Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END), 2
              ) AS "CPC"
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                  sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Cost ELSE 0 END) /
                    sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Clicks ELSE 0 END),
                  2
              )
            , ROUND(
                sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END),
                2
              )
            , ROUND(
                sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Cost ELSE 0 END) /
                  sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END),
                2
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (\"""" + cat + u"""\")
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )

    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_cpc_dyn.write_row(2 + n, 8, data_frame[n], cell_str_format)

    stopwatch("Динамика СРС")

    #########################################################################################
    # Вкладка про использование тематических площадок в помесячной и поквартальной динамике #
    #########################################################################################
    # По месяцам
    worksheet_rsy_use_by_months = workbook.add_worksheet(u'Динамика исп-я РСЯ')

    worksheet_rsy_use_by_months.merge_range(0, 1, 0, 3, cat, merge_format)
    worksheet_rsy_use_by_months.merge_range(0, 4, 0, 6, cl, merge_format)
    header = [
        u'Месяц',
        u'Доля показов (РСЯ)', u'Доля кликов (РСЯ)', u'Доля расходов (РСЯ)',
        u'Доля показов (РСЯ)', u'Доля кликов (РСЯ)', u'Доля расходов (РСЯ)',
    ]
    worksheet_rsy_use_by_months.write_row(1, 0, header, cell_str_format)

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month,1,4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Shows ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Shows ELSE 0 END) AS REAL)),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END) AS REAL)),
                2
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Cost ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Cost ELSE 0 END) AS REAL)),
                2
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Shows ELSE 0 END) AS REAL) /
                    (CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Shows ELSE 0 END) AS REAL)),
                  4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END) AS REAL)),
                2
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Cost ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Cost ELSE 0 END) AS REAL)),
                2
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN('""" + cat + u"""')
            GROUP BY Month
            ORDER BY Month ASC"""
    )

    data1 = curs.fetchall()
    for n in range(len(data1)):
        worksheet_rsy_use_by_months.write_row(2 + n, 0, data1[n])

    # По кварталам
    header[0] = u'Квартал'
    worksheet_rsy_use_by_months.write_row(1, 8, header, cell_str_format)
    worksheet_rsy_use_by_months.merge_range(0, 9, 0, 11, cat, merge_format)
    worksheet_rsy_use_by_months.merge_range(0, 12, 0, 14, cl, merge_format)

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Shows ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Shows ELSE 0 END) AS REAL)),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END) AS REAL)),
                2
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Cost ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Cost ELSE 0 END) AS REAL)),
                2
              )
            , """.format(COMPETITORS=competitors) + """
              ROUND(
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Shows ELSE 0 END) AS REAL) /
                    (CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Shows ELSE 0 END) AS REAL)),
                  4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END) AS REAL)),
                2
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Cost ELSE 0 END) AS REAL) /
                  (CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Cost ELSE 0 END) AS REAL)),
                2
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN('""" + cat + u"""')
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )

    data1 = curs.fetchall()
    for n in range(len(data1)):
        worksheet_rsy_use_by_months.write_row(2 + n, 8, data1[n])

    stopwatch("Динамика исп-я РСЯ")

    ###################
    # Вкладка про CTR #
    ###################
    # По месяцам
    worksheet_ctr = workbook.add_worksheet(u'CTR')

    worksheet_ctr.merge_range(0, 1, 0, 3, cat, merge_format)
    worksheet_ctr.merge_range(0, 4, 0, 6, cl, merge_format)
    header = [u'Месяц', u'CTR', u'CTR (Поиск)', u'CTR (РСЯ)', u'CTR', u'CTR (Поиск)', u'CTR (РСЯ)', ]
    worksheet_ctr.write_row(1, 0, header, cell_str_format)

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month,1,4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Shows ELSE 0 END) AS REAL),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Shows ELSE 0 END) AS REAL),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Shows ELSE 0 END) AS REAL),
                4
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END) AS REAL) /
                    CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Shows ELSE 0 END) AS REAL),
                  4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Shows ELSE 0 END) AS REAL),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Shows ELSE 0 END) AS REAL),
                4
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN('""" + cat + u"""')
            GROUP BY Month
            ORDER BY Month ASC"""
    )

    data1 = curs.fetchall()
    for n in range(len(data1)):
        worksheet_ctr.write_row(2 + n, 0, data1[n], cell_str_format)

    # По кварталам
    header[0] = u'Квартал'
    worksheet_ctr.write_row(1, 8, header, cell_str_format)
    worksheet_ctr.merge_range(0, 9, 0, 11, cat, merge_format)
    worksheet_ctr.merge_range(0, 12, 0, 14, cl, merge_format)

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Shows ELSE 0 END) AS REAL),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN Direct_Shows ELSE 0 END) AS REAL),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN({COMPETITORS})) THEN RSYA_Shows ELSE 0 END) AS REAL),
                4
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Clicks ELSE 0 END) AS REAL) /
                    CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Shows ELSE 0 END) AS REAL),
                  4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN Direct_Shows ELSE 0 END) AS REAL),
                4
              )
            , ROUND(
                CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Clicks ELSE 0 END) AS REAL) /
                  CAST(sum(CASE WHEN (Client IN('""" + cl + u"""')) THEN RSYA_Shows ELSE 0 END) AS REAL),
                4
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN('""" + cat + u"""')
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )

    data1 = curs.fetchall()
    for n in range(len(data1)):
        worksheet_ctr.write_row(2 + n, 8, data1[n], cell_str_format)

    stopwatch("CTR")

    ################################
    # Вкладка "Динамика категории" #
    ################################
    worksheet_cat_dyn = workbook.add_worksheet(u"Динамика категории")
    worksheet_cat_dyn.set_row(0, 30)

    # По месяцам
    # Получение коэффициента для приведения количества рекламодателей к уровню расходов
    curs.execute(
        u"""SELECT max(Cost) / max(CompCount) * 0.9
            FROM """ + TMP_TABLE_COMP_MONTHS + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')"""
    )
    try:
        corr_factor = curs.fetchone()[0]
    except:
        # sys.stderr.write('FYI - corr_factor for competitors in tmp_tbl_com_count_M = 1\n')
        corr_factor = 1

    # Получение коэффициента для приведения СРС к уровню расходов
    curs.execute(
        u"""SELECT (max(Cost) / (sum(Cost) / sum(Clicks))) * 0.7
            FROM """ + TMP_TABLE_COMP_MONTHS + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')"""
    )
    try:
        corr_cpc_factor = curs.fetchone()[0]
    except:
        # sys.stderr.write('FYI - corr_factor for cpc in tmp_tbl_com_count_M = 1\n')
        corr_cpc_factor = 1

    worksheet_cat_dyn.set_column(0, 0, 11)
    worksheet_cat_dyn.set_column(1, 5, 8.5)

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(sum(Cost), 2)
            , ROUND((sum(Cost) / sum(Clicks)), 2)
            , CompCount
            FROM """ + TMP_TABLE_COMP_MONTHS + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
            GROUP BY Month
            ORDER BY Month ASC"""
    )

    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_cat_dyn.write_row(1 + n, 0, data_frame[n])
        try:
            worksheet_cat_dyn.write(1 + n, 4, round(data_frame[n][2] * corr_cpc_factor), 0)
        except TypeError:

            # sys.stderr.write(
            #  'FYI - cpc by months (tmp_tbl_com_count_M) in data_frame[n][2]: %s\n' % str(data_frame[n][2])
            # )
            worksheet_cat_dyn.write(1 + n, 4, 0, 0)
        try:
            worksheet_cat_dyn.write(1 + n, 5, round(data_frame[n][3] * corr_factor), 0)
        except TypeError:
            # sys.stderr.write(
            #  'FYI - competitors count by months (tmp_tbl_com_count_M) in data_frame[n][3]: %s\n' % \
            #     str(data_frame[n][3])
            # )
            worksheet_cat_dyn.write(1 + n, 5, 0, 0)

    # По кварталам
    # Получение коэффициента для приведения количества рекламодателей к уровню расходов
    curs.execute(
        u"""SELECT max(Cost) / max(CompCount) * 0.8
            FROM """ + TMP_TABLE_COMP_QVART + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')"""
    )
    try:
        corr_factor = curs.fetchone()[0]
    except:
        # sys.stderr.write('FYI - corr_factor for competitors in tmp_tbl_com_count_Q = 1 \t %s\n' % cat)
        corr_factor = 1

    # Получение коэффициента для приведения СРС к уровню расходов
    curs.execute(
        u"""SELECT (max(Cost) / (sum(Cost) / sum(Clicks))) * 0.7
            FROM """ + TMP_TABLE_COMP_QVART + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')"""
    )
    try:
        corr_cpc_factor = curs.fetchone()[0]
    except:
        # sys.stderr.write('FYI - corr_factor for cpc in tmp_tbl_com_count_Q = 1 \t %s\n' % cat)
        corr_cpc_factor = 1

    worksheet_cat_dyn.write_row(
        0, 0,
        (
            u'Месяц', u'Расходы',
            u'Цена клика (raw)', u'Количество рекламодателей (raw)',
            u'Цена клика', u'Количество рекламодателей'
        ),
        str_format
    )
    worksheet_cat_dyn.set_column(0, 0, 11)
    worksheet_cat_dyn.set_column(1, 5, 8.5)
    worksheet_cat_dyn.write_row(
        0, 7,
        (
            u'Квартал', u'Расходы',
            u'Цена клика (raw)', u'Количество рекламодателей (raw)',
            u'Цена клика', u'Количество рекламодателей'
        ),
        str_format
    )
    worksheet_cat_dyn.set_column(7, 7, 9)
    worksheet_cat_dyn.set_column(8, 11, 9)
    worksheet_cat_dyn.set_column(12, 12, 18)

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(sum(Cost), 2)
            , ROUND((sum(Cost)/sum(Clicks)), 2)
            , CompCount
            FROM """ + TMP_TABLE_COMP_QVART + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
            GROUP BY Qvartal
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_cat_dyn.write_row(1 + n, 7, data_frame[n])
        try:
            worksheet_cat_dyn.write(1 + n, 11, round(data_frame[n][2] * corr_cpc_factor), 0)
        except:
            # sys.stderr.write(
            #   'FYI - cpc by qvart (tmp_tbl_com_count_Q) in data_frame[n][2]: %s\n' % str(data_frame[n][2])
            # )
            worksheet_cat_dyn.write(1 + n, 11, 0)
        try:
            worksheet_cat_dyn.write(1 + n, 12, round(data_frame[n][3] * corr_factor), 0)
        except:
            # sys.stderr.write(
            #   'FYI - comp_count by qvart (tmp_tbl_com_count_Q) in data_frame[n][3]: %s\n' % str(data_frame[n][3])
            # )
            worksheet_cat_dyn.write(1 + n, 12, 0)

    stopwatch("Динамика категории")

    #################################
    # Использование регионов деньги #
    #################################
    worksheet_region_cost = workbook.add_worksheet(u'Регионы деньги')
    # По месяцам
    worksheet_region_cost.merge_range(0, 1, 0, 2, cat, merge_format)
    worksheet_region_cost.merge_range(0, 3, 0, 4, cl, merge_format)
    worksheet_region_cost.write_row(
        1, 0,
        (u'Месяц', tgt_region.replace('"', ''), u'Остальные', tgt_region.replace('"', ''), u'Остальные')
    )

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Cost ELSE 0.00 END)
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Cost ELSE 0.00 END)
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Cost ELSE 0.00 END)
              )
            , ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Cost ELSE 0.00 END)
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
            GROUP BY Month
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_region_cost.write_row(2 + n, 0, data_frame[n])

    # По кварталам
    worksheet_region_cost.merge_range(0, 9, 0, 10, cat, merge_format)
    worksheet_region_cost.merge_range(0, 11, 0, 12, cl, merge_format)
    worksheet_region_cost.write_row(1, 8, (
        u'Квартал', tgt_region.replace('"', ''), u'Остальные', tgt_region.replace('"', ''), u'Остальные'))

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Cost ELSE 0.00 END)
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Cost ELSE 0.00 END)
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Cost ELSE 0.00 END)
              )
            , ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Cost ELSE 0.00 END)
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_region_cost.write_row(2 + n, 8, data_frame[n])

    stopwatch("Регионы деньги")

    #################################
    # Использование регионов клики #
    #################################
    worksheet_region_clicks = workbook.add_worksheet(u'Регионы клики')
    # По месяцам
    worksheet_region_clicks.merge_range(0, 1, 0, 2, cat, merge_format)
    worksheet_region_clicks.merge_range(0, 3, 0, 4, cl, merge_format)
    worksheet_region_clicks.write_row(
        1, 0,
        (u'Месяц', tgt_region.replace('"', ''), u'Остальные', tgt_region.replace('"', ''), u'Остальные')
    )

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month,5,2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            , ROUND(sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Clicks ELSE 0.00 END))
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Clicks ELSE 0.00 END)
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Clicks ELSE 0.00 END)
              )
            , ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Clicks ELSE 0.00 END)
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
            GROUP BY Month
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_region_clicks.write_row(2 + n, 0, data_frame[n])

    # По кварталам
    worksheet_region_clicks.merge_range(0, 9, 0, 10, cat, merge_format)
    worksheet_region_clicks.merge_range(0, 11, 0, 12, cl, merge_format)
    worksheet_region_clicks.write_row(
        1, 8,
        (u'Квартал', tgt_region.replace('"', ''), u'Остальные', tgt_region.replace('"', ''), u'Остальные')
    )

    curs.execute(
        u"""SELECT
              Qvartal
            , ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Clicks ELSE 0.00 END)
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                  sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ({COMPETITORS}) THEN Clicks ELSE 0.00 END)
              )
            ,""".format(COMPETITORS=competitors) + """
              ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Clicks ELSE 0.00 END)
              )
            , ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") AND Client IN ('""" + cl + u"""') THEN Clicks ELSE 0.00 END)
              )
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
            GROUP BY Qvartal
            HAVING COUNT(DISTINCT Month) = 3
            ORDER BY Month ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_region_clicks.write_row(2 + n, 8, data_frame[n])

    stopwatch("Регионы клики")

    ##################################
    # Распределение долей в регионах #
    ##################################
    # Последний полный месяц
    worksheet_geo_share = workbook.add_worksheet(u'Доля в регионах')
    worksheet_geo_share.write_row(0, 0, (u'Ранг', u'Клиент ({})'.format(tgt_region.replace('"', '')),
                                         u'Клики ({})'.format(tgt_region.replace('"', '')),
                                         u'Клиент (остальные)', u'Клики (остальные)', u'Клиент', u'Клики'))
    worksheet_geo_share.write_column(1, 0, xrange(1, 31), str_format)
    last_month = sorted(months)[-1]
    curs.execute(
        u"""SELECT
              Client
            , ROUND(sum(CASE WHEN Region IN (""" + tgt_region + u""") THEN Clicks ELSE 0.00 END)) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month IN ('""" + last_month + u"""')
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_geo_share.write_row(1 + n, 1, data_frame[n])

    worksheet_geo_share.write_row(
        34, 0,
        (last_month, tgt_region.replace('"', ''), u'Остальные')
    )

    curs.execute(
        u"""SELECT
              Client
            , ROUND(sum(CASE WHEN Region IN (""" + tgt_region + u""") THEN Clicks ELSE 0.00 END)) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month IN ('""" + last_month + u"""')
              AND Client IN ('""" + cl + u"""')
            GROUP BY Client"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_geo_share.write_row(35, 0, data_frame[n])

    curs.execute(
        u"""SELECT
              ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") THEN Clicks ELSE 0.00 END)
              ) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month IN ('""" + last_month + u"""')
              AND Client IN ('""" + cl + u"""')
            GROUP BY Client"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_geo_share.write_row(35, 2, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") THEN Clicks ELSE 0.00 END)
              ) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""') AND Month IN ('""" + last_month + u"""')
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_geo_share.write_row(1 + n, 3, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , ROUND(sum(Clicks)) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month IN ('""" + last_month + u"""')
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_geo_share.write_row(1 + n, 5, data_frame[n])

    curs.execute(
        u"""SELECT
              CustomCategory
            , ROUND(
                sum(CASE WHEN Region IN (""" + tgt_region + u""") THEN Clicks ELSE 0.00 END)
              ) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month IN ('""" + last_month + u"""')
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_geo_share.write_row(36, 0, data_frame[n])

    curs.execute(
        u"""SELECT
              ROUND(
                sum(CASE WHEN Region NOT IN (""" + tgt_region + u""") THEN Clicks ELSE 0.00 END)
              ) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month IN ('""" + last_month + u"""')
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_geo_share.write_row(36, 2, data_frame[n])

    # Последний полный квартал Y-1
    try:
        last_full_qvart = list_full_qvart[-1][0]
        last_full_qvart_y_min_1 = list_full_qvart[-1][0][:-1] + str(int(list_full_qvart[-1][0][-1]) - 1)
    except IndexError:
        last_full_qvart = 'None'
        last_full_qvart_y_min_1 = 'None'

    if period_1 == '':
        period_1 = last_full_qvart_y_min_1

    if period_2 == '':
        period_2 = last_full_qvart
    if 'Q' in period_1:
        worksheet_info.write_row(44, 1, [period_1, '', '', period_2], str_format)
        dyn_months = pd.read_sql_query(
            u"""SELECT Month
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal IN (\"""" + period_1 + u"""\")
                GROUP BY Month
                ORDER BY "Month" ASC""",
            conn
        )
        period_1 = dyn_months.Month.tolist()
        period_1 = list(set(period_1))
        period_1.sort()
        period_1 = period_1[0] + '-' + period_1[2]

        dyn_months = pd.read_sql_query(
            u"""SELECT Month
                FROM """ + TMP_TBL + u"""
                WHERE Qvartal IN (\"""" + period_2 + u"""\")
                GROUP BY Month
                ORDER BY "Month" ASC""",
            conn
        )

        period_2 = dyn_months.Month.tolist()
        period_2 = list(set(period_2))
        period_2.sort()

        period_2 = period_2[0] + '-' + period_2[2]

    else:
        worksheet_info.write_row(44, 1, [period_1[:6], period_1[-6:], period_2[:6], period_2[-6:]], str_format)

    stopwatch("Доля в регионах")

    ##################################################
    # Доля кликов по типу площадок к году для ТОП-30 #
    ##################################################
    worksheet_share_top_clicks = workbook.add_worksheet(u'Top-30 Clicks_Share')
    worksheet_share_top_clicks.write_row(0, 0, (u'Ранг', u'Клиент (Поиск)', u'Клики (Поиск)',
                                                u'Клиент (РСЯ)', u'Клики (РСЯ)',
                                                u'Клиент (всего)', u'Клики (всего)', str(period_1)))

    worksheet_share_top_clicks.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "sumClicks"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(1 + n, 1, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Clicks) AS "sumClicks"
             FROM """ + TMP_TBL + u"""
             WHERE CustomCategory IN ('""" + cat + u"""')
               AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
             GROUP BY Client
             HAVING sumClicks != 0
             ORDER BY "sumClicks" DESC
             LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(1 + n, 3, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Clicks) AS "sumClicks"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(1 + n, 5, data_frame[n])

    data = [str(period_1), u'Поисковые площадки', u'Тематические площадки', u'Все площадки']
    worksheet_share_top_clicks.write_row(34, 0, data)
    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "sumClicks"
            , sum(RSYA_Clicks) AS "sumClicks"
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Client IN ('""" + cl + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(35 + n, 0, data_frame[n])
    curs.execute(
        u"""SELECT
              CustomCategory
            , sum(Direct_Clicks) AS "sumClicks"
            , sum(RSYA_Clicks) AS "sumClicks"
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(36 + n, 0, data_frame[n])

    # Последний полный квартал
    worksheet_share_top_clicks.write_row(
        0, 10,
        (
            u'Ранг',
            u'Клиент (Поиск)', u'Клики (Поиск)',
            u'Клиент (РСЯ)', u'Клики (РСЯ)',
            u'Клиент (всего)', u'Клики (всего)',
            str(period_2)
        )
    )
    worksheet_share_top_clicks.write_column(1, 10, xrange(1, 31), str_format)
    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "sumClicks"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(1 + n, 11, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Clicks) AS "sumClicks"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(1 + n, 13, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(1 + n, 15, data_frame[n])

    data = [str(period_2), u'Поисковые площадки', u'Тематические площадки', u'Все площадки']
    worksheet_share_top_clicks.write_row(34, 10, data)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "sumClicks"
            , sum(RSYA_Clicks) AS "sumClicks"
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Client IN ('""" + cl + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(35 + n, 10, data_frame[n])

    curs.execute(
        u"""SELECT
              CustomCategory
            , sum(Direct_Clicks) AS "sumClicks"
            , sum(RSYA_Clicks) AS "sumClicks"
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_clicks.write_row(36 + n, 10, data_frame[n])

    stopwatch("Top-30 Clicks_Share")

    ####################################
    # Эффективность выкупа в категории #
    ####################################
    worksheet_delta_bub = workbook.add_worksheet(u'Cat_delta_bub')

    worksheet_delta_bub.merge_range(1, 1, 1, 2, period_1, merge_format)
    worksheet_delta_bub.merge_range(1, 3, 1, 4, period_2, merge_format)
    worksheet_delta_bub.write_row(
        2, 0,
        [u'Client', u'Direct_Clicks', u'Direct_Cost', u'Direct_Clicks', u'Direct_Cost']
    )
    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "DirectCost"
            FROM (""" + TMP_TBL + u""")
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
            AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            HAVING
              "DirectCost" >= (
                  SELECT sum(Direct_Cost) AS max_cost
                  FROM (""" + TMP_TBL + u""")
                  WHERE CustomCategory IN ('""" + cat + u"""')
                    AND Month >= """ + period_2[:6] + u"""
                    AND Month <= """ + period_2[-6:] + u"""
                  GROUP BY Client
                  ORDER BY max_cost DESC
                  LIMIT 1
                ) * 0.1
            ORDER BY Client ASC"""
    )
    clients_2 = curs.fetchall()

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "DirectCost"
            FROM (""" + TMP_TBL + u""")
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
              AND Client <> ('""" + cl + u"""')
            GROUP BY Client
            ORDER BY Client ASC"""
    )
    clients_1 = curs.fetchall()
    clients = set(r[0] for r in clients_1) & set(r[0] for r in clients_2)
    clients = u"\"" + u"\", \"".join(clients) + u"\""

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "DirectClicks"
            , sum(Direct_Cost) AS "DirectCost"
            FROM (""" + TMP_TBL + u""")
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
              AND Client IN ({CLIENTS})""".format(CLIENTS=clients) + u"""
            GROUP BY Client
            ORDER BY Client ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_delta_bub.write_row(4 + n, 0, data_frame[n])

    curs.execute(
        u"""SELECT
              sum(Direct_Clicks) AS "DirectClicks"
            , sum(Direct_Cost) AS "DirectCost"
            FROM (""" + TMP_TBL + u""")
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
              AND Client IN ({CLIENTS})""".format(CLIENTS=clients) + u"""
            GROUP BY Client
            ORDER BY Client ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_delta_bub.write_row(4 + n, 3, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "DirectClicks"
            , sum(Direct_Cost) AS "DirectCost"
            FROM (""" + TMP_TBL + u""")
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Client IN ('""" + cl + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client
            ORDER BY Client ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_delta_bub.write_row(3 + n, 0, data_frame[n])
    curs.execute(
        u"""SELECT
              sum(Direct_Clicks) AS "DirectClicks"
            , sum(Direct_Cost) AS "DirectCost"
            FROM (""" + TMP_TBL + u""")
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
              AND Client IN ('""" + cl + u"""')
            GROUP BY Client
            ORDER BY Client ASC"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_delta_bub.write_row(3 + n, 3, data_frame[n])

    stopwatch("Cat_delta_bub")

    ####################################################
    # Доля откруток по типу площадок к году для ТОП-30 #
    ####################################################
    # Последний полный квартал Y-1
    worksheet_share_top_cost = workbook.add_worksheet(u'Top-30 Cost_Share')
    worksheet_share_top_cost.write_row(
        0, 0,
        (
            u'Ранг',
            u'Клиент (Поиск)', u'Открутки (Поиск)',
            u'Клиент (РСЯ)', u'Открутки (РСЯ)',
            u'Клиент (всего)', u'Открутки (всего)',
            str(period_1)
        )
    )

    worksheet_share_top_cost.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "sumCost"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(1 + n, 1, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Cost) AS "sumCost"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(1 + n, 3, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(1 + n, 5, data_frame[n])

    data = [str(period_1), u'Поисковые площадки', u'Тематические площадки', u'Все площадки']
    worksheet_share_top_cost.write_row(34, 0, data)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "sumCost"
            , sum(RSYA_Cost) AS "sumCost"
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Client IN ('""" + cl + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY Client"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(35 + n, 0, data_frame[n])

    curs.execute(
        u"""SELECT
              CustomCategory
            , sum(Direct_Cost) AS "sumCost"
            , sum(RSYA_Cost) AS "sumCost"
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_1[-6:] + u"""
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(36 + n, 0, data_frame[n])

    # Последний полный квартал
    worksheet_share_top_cost.write_row(
        0, 10,
        (
            u'Ранг',
            u'Клиент (Поиск)', u'Открутки (Поиск)',
            u'Клиент (РСЯ)', u'Открутки (РСЯ)',
            u'Клиент (всего)', u'Открутки (всего)',
            str(period_2)
        )
    )

    worksheet_share_top_cost.write_column(1, 10, xrange(1, 31), str_format)
    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(1 + n, 11, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Cost) AS "sumCost"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(1 + n, 13, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(1 + n, 15, data_frame[n])

    data = [str(period_2), u'Поисковые площадки', u'Тематические площадки', u'Все площадки']
    worksheet_share_top_cost.write_row(34, 10, data)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "sumCost"
            , sum(RSYA_Cost) AS "sumCost"
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Client IN ('""" + cl + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(35 + n, 10, data_frame[n])

    curs.execute(
        u"""SELECT
              CustomCategory
            , sum(Direct_Cost) AS "sumCost"
            , sum(RSYA_Cost) AS "sumCost"
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_top_cost.write_row(36 + n, 10, data_frame[n])

    stopwatch("Top-30 Cost_Share")

    ###############################
    # Клики и расходы в индустрии #
    ###############################
    # второй период
    worksheet_ind_clicks_cost = workbook.add_worksheet(u'Ind_clicks_cost')
    worksheet_ind_clicks_cost.merge_range(0, 0, 0, 2, industry, merge_format)
    worksheet_ind_clicks_cost.merge_range(0, 3, 0, 5, cl, merge_format)
    worksheet_ind_clicks_cost.write(0, 6, str(period_2))
    worksheet_ind_clicks_cost.write_row(
        1, 0,
        (
            u'CustomCategory', u'Clicks', u'Cost',
            u'CustomCategory', u'Clicks', u'Cost',
        )
    )
    top_cat_df = pd.read_sql_query(
        u"""SELECT
              CustomCategory, sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + '\', \''.join(categories) + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY CustomCategory
            ORDER BY "sumCost" DESC""", conn
    )
    top_cats = top_cat_df.CustomCategory.tolist()

    curs.execute(
        u"""SELECT
              CustomCategory AS CustomCategory
            , sum(Clicks) AS "sumClicks"
            , ROUND(sum(Cost)) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + '\', \''.join(top_cats) + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
              AND Client in ({COMPETITORS})""".format(COMPETITORS=competitors) + """
            GROUP BY CustomCategory
            ORDER BY
              CASE "CustomCategory" """ + ' '.join(
            [u"WHEN '" + x + "'" + u' THEN ' + str(top_cats.index(x) + 1) for x in top_cats]) + u""" END"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_ind_clicks_cost.write_row(2 + n, 0, data_frame[n])

    curs.execute(
        u"""SELECT
              CustomCategory AS CustomCategory
            , sum(Clicks) AS "sumClicks"
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + '\', \''.join(top_cats) + u"""')
               AND Client IN ('""" + cl + u"""')
               AND Month >= """ + period_2[:6] + u"""
               AND Month <= """ + period_2[-6:] + u"""
            GROUP BY CustomCategory
            ORDER BY
              CASE "CustomCategory" """ + ' '.join(
            [u"WHEN '" + x + "'" + u' THEN ' + str(top_cats.index(x) + 1) for x in top_cats]) + u""" END"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_ind_clicks_cost.write_row(2 + n, 3, data_frame[n])

    worksheet_clicks.merge_range(0, 17, 0, 19, cat, merge_format)
    worksheet_clicks.merge_range(0, 20, 0, 22, cl, merge_format)
    worksheet_clicks.write_row(
        1, 16,
        (u'Period_2', u'Поиск', u'РСЯ', u'Всего', u'Поиск', u'РСЯ', u'Всего'),
        cell_str_format,
    )
    worksheet_clicks.write(2, 16, str(period_2))

    curs.execute(
        u"""SELECT
              sum(Direct_Clicks) AS "sumDirectClicks"
            , sum(RSYA_Clicks) AS "sumRSYAClicks"
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
              AND Client in ({COMPETITORS})""".format(COMPETITORS=competitors) + u"""
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_clicks.write_row(2 + n, 17, data_frame[n])

    curs.execute(
        u"""SELECT
              sum(Direct_Clicks) AS "sumDirectClicks"
            , sum(RSYA_Clicks) AS "sumRSYAClicks"
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Client IN ('""" + cl + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY CustomCategory"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_clicks.write_row(2 + n, 20, data_frame[n])

    stopwatch("Ind_clicks_cost")

    ########################
    # Эффективность выкупа #
    ########################
    # второй период
    # worksheet_delta_bub = workbook.add_worksheet(u'Cat_delta_bub')
    # worksheet_delta_bub.write_row(
    #   0, 0,
    #   (u'Competitors', u'delta_Direct_Clicks', u'delta_Direct_Cost', u'sum_Direct_Cost')
    # )
    ####################
    # Клики в индустрии #
    ####################
    # второй период
    worksheet_ind_clicks = workbook.add_worksheet(u'Ind_clicks')
    if len(top_cats) != 1:
        worksheet_ind_clicks.merge_range(0, 1, 0, len(top_cats), industry, merge_format)
        worksheet_ind_clicks.merge_range(0, len(top_cats) + 1, 0, len(top_cats) * 2, cl, merge_format)
    else:
        worksheet_ind_clicks.write_row(0, 1, [industry, cl], merge_format)

    worksheet_ind_clicks.write(0, len(top_cats) * 2 + 1, str(period_2))

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month, 5, 2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (""" + join4filter(top_cats) + u""")
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Month
            ORDER BY Month ASC"""
    )
    worksheet_ind_clicks.write_column(1, 0, [u'Месяц'] + [item[0] for item in curs.fetchall()])

    for i, tmp_cat in enumerate(top_cats, 1):
        curs.execute(
            u"""SELECT sum(Clicks)
                FROM """ + TMP_TBL + u"""
                WHERE CustomCategory IN ('""" + tmp_cat + u"""')
                  AND Month >= """ + period_2[:6] + u"""
                  AND Month <= """ + period_2[-6:] + u"""
                  AND Client in ({COMPETITORS})""".format(COMPETITORS=competitors) + """
                GROUP BY Month
                ORDER BY Month ASC"""
        )
        worksheet_ind_clicks.write_column(
            1, i,
            [tmp_cat] + [item[0] for item in curs.fetchall()]
        )

        curs.execute(
            u"""SELECT sum(Clicks)
                FROM """ + TMP_TBL + u"""
                WHERE CustomCategory IN ('""" + tmp_cat + u"""')
                  AND Month >= """ + period_2[:6] + u"""
                  AND Month <= """ + period_2[-6:] + u"""
                  AND Client IN ('""" + cl + u"""')
                GROUP BY Month
                ORDER BY Month ASC"""
        )
        worksheet_ind_clicks.write_column(
            1, len(categories) + i,
            [tmp_cat] + [item[0] for item in curs.fetchall()]
        )

    stopwatch("Ind_clicks")

    #######################
    # Расходы в индустрии #
    #######################
    # второй период
    worksheet_ind_cost = workbook.add_worksheet(u'Ind_cost')
    if len(top_cats) != 1:
        worksheet_ind_cost.merge_range(0, 1, 0, len(top_cats), industry, merge_format)
        worksheet_ind_cost.merge_range(0, len(top_cats) + 1, 0, len(top_cats) * 2, cl, merge_format)
    else:
        worksheet_ind_cost.write_row(0, 1, [industry, cl], merge_format)

    worksheet_ind_cost.write(0, len(top_cats) * 2 + 1, str(period_2))

    curs.execute(
        u"""SELECT
              CASE CAST(SUBSTR(Month, 5, 2) AS INTEGER)
                WHEN 1 THEN SUBSTR(Month, 1, 4)
                WHEN 2 THEN "Фев"
                WHEN 3 THEN "Мар"
                WHEN 4 THEN "Апр"
                WHEN 5 THEN "Май"
                WHEN 6 THEN "Июн"
                WHEN 7 THEN "Июл"
                WHEN 8 THEN "Авг"
                WHEN 9 THEN "Сен"
                WHEN 10 THEN "Окт"
                WHEN 11 THEN "Ноя"
                WHEN 12 THEN "Дек"
                ELSE "NAN"
              END AS "Месяц"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN (""" + join4filter(top_cats) + u""")
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Month
            ORDER BY Month ASC"""
    )
    worksheet_ind_cost.write_column(1, 0, [u'Месяц'] + [item[0] for item in curs.fetchall()])

    for i, tmp_cat in enumerate(top_cats, 1):
        curs.execute(
            u"""SELECT sum(Cost)
                FROM """ + TMP_TBL + u"""
                WHERE CustomCategory IN ('""" + tmp_cat + u"""')
                  AND Month >= """ + period_2[:6] + u"""
                  AND Month <= """ + period_2[-6:] + u"""
                  AND Client in ({COMPETITORS})""".format(COMPETITORS=competitors) + """
                GROUP BY Month
                ORDER BY Month ASC"""
        )
        worksheet_ind_cost.write_column(1, i, [tmp_cat] + [item[0] for item in curs.fetchall()])

        curs.execute(
            u"""SELECT sum(Cost)
                FROM """ + TMP_TBL + u"""
                WHERE CustomCategory IN ('""" + tmp_cat + u"""')
                  AND Month >= """ + period_2[:6] + u"""
                  AND Month <= """ + period_2[-6:] + u"""
                  AND Client IN ('""" + cl + u"""')
                GROUP BY Month
                ORDER BY Month ASC"""
        )
        worksheet_ind_cost.write_column(
            1, len(categories) + i,
            [tmp_cat] + [item[0] for item in curs.fetchall()]
        )

    stopwatch("Ind_cost")

    ###########################################################
    # Доля кликов по типу площадок накопленный год для ТОП-30 #
    ###########################################################
    # Последний накопленный год - 1
    last_full_year = [y[0] for y in list_full_qvart if y[0].endswith(list_full_qvart[-1][0][-2:])]
    last_full_year_min_1 = map(lambda e: e[:-1] + str(int(e[-1]) - 1), last_full_year)

    last_full_year = '\"' + "\", \"".join(last_full_year) + '\"'
    last_full_year_min_1 = '\"' + "\", \"".join(last_full_year_min_1) + '\"'

    worksheet_share_by_year_top_clicks = workbook.add_worksheet(u'Top-30 Year_Clicks_Share')
    worksheet_share_by_year_top_clicks.write_row(
        0, 0,
        (
            u'Ранг',
            u'Клиент (Поиск)', u'Клики (Поиск)',
            u'Клиент (РСЯ)', u'Клики (РСЯ)',
            u'Клиент (всего)', u'Клики (всего)',
            last_full_year_min_1
        )
    )

    worksheet_share_by_year_top_clicks.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year_min_1 + u""")
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_clicks.write_row(1 + n, 1, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year_min_1 + u""")
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_clicks.write_row(1 + n, 3, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year_min_1 + u""")
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_clicks.write_row(1 + n, 5, data_frame[n])

    # Последний накопленый год
    worksheet_share_by_year_top_clicks.write_row(
        0, 10,
        (
            u'Ранг',
            u'Клиент (Поиск)', u'Клики (Поиск)',
            u'Клиент (РСЯ)', u'Клики (РСЯ)',
            u'Клиент (всего)', u'Клики (всего)',
            last_full_year
        )
    )

    worksheet_share_by_year_top_clicks.write_column(1, 10, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year + u""")
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_clicks.write_row(1 + n, 11, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year + u""")
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_clicks.write_row(1 + n, 13, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Clicks) AS "sumClicks"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year + u""")
            GROUP BY Client
            HAVING sumClicks != 0
            ORDER BY "sumClicks" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_clicks.write_row(1 + n, 15, data_frame[n])

    stopwatch("Top-30 Year_Clicks_Share")

    ##################################################################
    # Доля откруток по типу площадок для накопленного года по ТОП-30 #
    ##################################################################
    # Последний накопленный год - 1
    worksheet_share_by_year_top_cost = workbook.add_worksheet(u'Top-30 Year_Cost_Share')
    worksheet_share_by_year_top_cost.write_row(
        0, 0,
        (
            u'Ранг',
            u'Клиент (Поиск)', u'Открутки (Поиск)',
            u'Клиент (РСЯ)', u'Открутки (РСЯ)',
            u'Клиент (всего)', u'Открутки (всего)',
            last_full_year_min_1,
        )
    )

    worksheet_share_by_year_top_cost.write_column(1, 0, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year_min_1 + u""")
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_cost.write_row(1 + n, 1, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year_min_1 + u""")
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_cost.write_row(1 + n, 3, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year_min_1 + u""")
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_cost.write_row(1 + n, 5, data_frame[n])

    # Последний накопленный год
    worksheet_share_by_year_top_cost.write_row(
        0, 10,
        (
            u'Ранг',
            u'Клиент (Поиск)', u'Открутки (Поиск)',
            u'Клиент (РСЯ)', u'Открутки (РСЯ)',
            u'Клиент (всего)', u'Открутки (всего)',
            last_full_year,
        )
    )

    worksheet_share_by_year_top_cost.write_column(1, 10, xrange(1, 31), str_format)

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year + u""")
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_cost.write_row(1 + n, 11, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(RSYA_Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year + u""")
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_cost.write_row(1 + n, 13, data_frame[n])

    curs.execute(
        u"""SELECT
              Client
            , sum(Cost) AS "sumCost"
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Qvartal IN (""" + last_full_year + u""")
            GROUP BY Client
            HAVING sumCost != 0
            ORDER BY "sumCost" DESC
            LIMIT 30"""
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_share_by_year_top_cost.write_row(1 + n, 15, data_frame[n])

    stopwatch("Top-30 Year_Cost_Share")

    ############################
    # Доля клиента по регионам #
    ############################
    if cl != 'None' and regions != 'None':
        worksheet_share_by_region = workbook.add_worksheet(u'Share by regions')
        worksheet_share_by_region.write(0, 0, u'Регион')
        worksheet_share_by_region.write_row(0, 1, prettify_months(months))
        cell_percent_format = workbook.add_format(
            {
                'font_name': 'Textbook New',
                'font_size': '7',
                'bold': False,
                'align': 'center',
                'valign': 'vcenter',
                'font_color': '#808080',
                'text_wrap': True,
                'num_format': '0%',
            }
        )
        curs.execute(
            u"""SELECT
                  Region
                , ROUND(
                    sum(CASE WHEN Client = '{client}' THEN Clicks ELSE 0 END)/CAST(sum(Clicks) AS REAL),
                    4
                  ) AS Share
                , Month
                FROM {tbl}
                WHERE CustomCategory = '{category}'
                GROUP BY Region, Month
                ORDER BY Region, Month;""".format(client=cl, tbl=TMP_TBL, category=cat)
        )
        data_frame = curs.fetchall()

        pivot = [[r, ] for r in regions]
        for reg in pivot:
            for month in sorted(months):
                filtered_value = filter(lambda x: x[0] == reg[0] and int(x[2]) == int(month), data_frame)[0][1]
                if filtered_value is None:
                    filtered_value = 0
                reg.append(filtered_value)

        for n in range(len(pivot)):
            current_row = n + 1
            worksheet_share_by_region.write_row(current_row, 0, pivot[n])
            worksheet_share_by_region.set_row(current_row, 20)
            worksheet_share_by_region.conditional_format(
                current_row, 1,
                current_row, 1 + len(months),
                {u'type': u'3_color_scale'}
            )

        worksheet_share_by_region.set_column(1, len(months), 3, cell_percent_format)
        worksheet_share_by_region.set_column(0, 0, 20, cell_str_format)
        worksheet_share_by_region.set_row(0, 20, cell_str_format)

        stopwatch("Share by regions")

    ###########################
    # Bubble CPC, CTR, Clicks #
    ###########################
    worksheet_bubble = workbook.add_worksheet(u'Bubble_Direct')
    worksheet_bubble.write_row(
        0, 0,
        [u'Client', u'Direct_CTR', u'Direct_CPC', u'Direct_Clicks', last_month],
        cell_str_format,
    )

    curs.execute(
        u"""SELECT
              Client
            , CAST(sum(Direct_Clicks) AS REAL) / sum(Direct_Shows) AS Direct_CTR
            , sum(Direct_Cost) / sum(Direct_Clicks) AS Direct_CPC
            , sum(Direct_Clicks) AS Direct_Clicks
            FROM {tbl}
            WHERE CustomCategory = '{category}' AND Month = '{month}'
            GROUP BY Client
            HAVING Direct_Clicks >= 100
            ORDER BY Direct_Clicks DESC
            LIMIT 10000;""".format(tbl=TMP_TBL, category=cat, month=last_month)
    )
    data_frame = curs.fetchall()
    for n in range(len(data_frame)):
        worksheet_bubble.write_row(1 + n, 0, data_frame[n], cell_str_format)

    stopwatch("Bubble_Direct")

    ##################
    # Boxes CPC, CTR #
    ##################
    df = pd.read_sql_query(
        u"""SELECT
              Client
            , Direct_Cost
            , RSYA_Cost
            , Cost
            , Direct_Clicks
            , RSYA_Clicks
            , Clicks
            , Direct_Shows
            , RSYA_Shows
            , Shows
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            ORDER BY "sumCost" ASC""",
        conn
    )
    df = df.replace(to_replace=['0.', ], value=0)
    df[u'Direct_Cost'] = df[u'Direct_Cost'].astype(pd.np.float64)
    df[u'Cost'] = df[u'Cost'].astype(pd.np.float64)

    # CPC по откруткам
    direct_cpc_df = calculate_percentiles(df, u'Direct_Cost', u'Direct_CPC', u'Direct_Cost', u'Direct_Clicks', share)
    rsya_cpc_df = calculate_percentiles(df, u'RSYA_Cost', u'RSYA_CPC', u'RSYA_Cost', u'RSYA_Clicks', share)
    cpc_df = calculate_percentiles(df, u'Cost', u'CPC', u'Cost', u'Clicks', share)

    if (direct_cpc_df is not None) and (rsya_cpc_df is not None) and (cpc_df is not None):
        direct_cpc_df[u'platform'] = u'Direct'
        rsya_cpc_df[u'platform'] = u'RSYA'
        cpc_df[u'platform'] = u'Direct + RSYA'
        cpc_all = pd.concat([direct_cpc_df, rsya_cpc_df, cpc_df], axis=0)
        worksheet_boxes_cpc = workbook.add_worksheet(u'CPC_by_Cost')
        worksheet_boxes_cpc.write_row(0, 0, list(cpc_all.columns), cell_str_format)
        r = 0
        for x in cpc_all.as_matrix():
            worksheet_boxes_cpc.write_row(1 + r, 0, x, cell_str_format)
            r += 1

    # CTR по откруткам
    direct_ctr_df = calculate_percentiles(df, u'Direct_Cost', u'Direct_CTR', u'Direct_Clicks', u'Direct_Shows', share)
    rsya_ctr_df = calculate_percentiles(df, u'RSYA_Cost', u'RSYA_CTR', u'RSYA_Clicks', u'RSYA_Shows', share)
    ctr_df = calculate_percentiles(df, u'Cost', u'CTR', u'Clicks', u'Shows', share)

    if (direct_ctr_df is not None) and (rsya_ctr_df is not None) and (ctr_df is not None):
        direct_ctr_df[u'platform'] = u'Direct'
        rsya_ctr_df[u'platform'] = u'RSYA'
        ctr_df[u'platform'] = u'Direct + RSYA'
        ctr_all = pd.concat([direct_ctr_df, rsya_ctr_df, ctr_df], axis=0)
        worksheet_boxes_ctr = workbook.add_worksheet(u'CTR_by_Cost')
        worksheet_boxes_ctr.write_row(0, 0, list(ctr_all.columns), cell_str_format)
        r = 0
        for x in ctr_all.as_matrix():
            worksheet_boxes_ctr.write_row(1 + r, 0, x, cell_str_format)
            r += 1

    # CPM по откруткам
    direct_cpm_df = calculate_percentiles(df, u'Direct_Cost', u'Direct_CPM', u'Direct_Cost', u'Direct_Shows', share)
    rsya_cpm_df = calculate_percentiles(df, u'RSYA_Cost', u'RSYA_CPM', u'RSYA_Cost', u'RSYA_Shows', share)
    cpm_df = calculate_percentiles(df, u'Cost', u'CPM', u'Cost', u'Shows', share)

    if (direct_cpm_df is not None) and (rsya_cpm_df is not None) and (cpm_df is not None):
        direct_cpm_df[u'platform'] = u'Direct'
        rsya_cpm_df[u'platform'] = u'RSYA'
        cpm_df[u'platform'] = u'Direct + RSYA'
        cpm_all = pd.concat([direct_cpm_df, rsya_cpm_df, ctr_df], axis=0)
        worksheet_boxes_cpm = workbook.add_worksheet(u'CPM_by_Cost')
        worksheet_boxes_cpm.write_row(0, 0, list(cpm_all.columns), cell_str_format)
        r = 0
        for x in cpm_all.as_matrix():
            worksheet_boxes_cpm.write_row(1 + r, 0, x, cell_str_format)
            r += 1

    top_df = pd.read_sql_query(
        u"""SELECT
              Client
            , sum(Cost) AS "sumCost"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_2[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            ORDER BY "sumCost" DESC
            LIMIT 30""",
        conn
    )
    top_clients = top_df.Client.tolist()
    if cl not in top_clients:
        top_clients.append(cl)
    top_clients = u"\"" + u"\", \"".join(top_clients) + u"\""
    df = pd.read_sql_query(
        u"""SELECT
              Month
            , Client
            , Direct_Cost
            , RSYA_Cost
            , Cost
            , Direct_Clicks
            , RSYA_Clicks
            , Clicks
            , Direct_Shows
            , RSYA_Shows
            , Shows
            FROM """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Client IN (""" + top_clients + u""")""",
        conn
    )
    df[u'Month'] = df[u'Month'].astype(pd.np.int32)
    df = df.replace(to_replace=['0.', ], value=0)
    df[u'Direct_Cost'] = df[u'Direct_Cost'].astype(pd.np.float64)
    df[u'Cost'] = df[u'Cost'].astype(pd.np.float64)

    df = df.groupby(['Client', 'Month'], as_index=False).sum()

    stopwatch("CTR_by_Cost")

    ####################################################
    # Сравнение доли клиента с долей лидера по показам #
    ####################################################

    shows_df, shows_rating = calculate_leader_share(df, [u'Shows', u'Direct_Shows', u'RSYA_Shows'], cl, period_2)
    shows_share_dyn = workbook.add_worksheet(u'Shows_Share_dyn')
    shows_share_dyn.merge_range(0, 1, 0, 3, u'Суммарно', merge_format)
    shows_share_dyn.merge_range(0, 4, 0, 6, u'Поиск', merge_format)
    shows_share_dyn.merge_range(0, 7, 0, 9, u'РСЯ', merge_format)
    shows_share_dyn.write_row(
        1, 0,
        [
            u'Месяц',
            u'Лидер', u'Доля лидера', u'Доля клиента',
            u'Лидер', u'Доля лидера', u'Доля клиента',
            u'Лидер', u'Доля лидера', u'Доля клиента'
        ],
        cell_str_format
    )
    r = 1
    for x in shows_df.as_matrix():
        try:
            shows_share_dyn.write_row(1 + r, 0, x)
        except:
            pass
        r += 1

    shows_share = workbook.add_worksheet(u'Shows_Share')
    shows_share.write_row(
        0, 0,
        [
            u'Клиент', u'Показы (суммарно)',
            u'Клиент', u'Показы (поиск)',
            u'Клиент', u'Показы (РСЯ)',
            period_2
        ],
        cell_str_format
    )
    r = 0
    for x in shows_rating.as_matrix():
        shows_share.write_row(1 + r, 0, x)
        r += 1

    stopwatch("Shows_Share_dyn")

    ###################################################
    # Сравнение доли клиента с долей лидера по кликам #
    ###################################################
    clicks_df, clicks_rating = calculate_leader_share(df, [u'Clicks', u'Direct_Clicks', u'RSYA_Clicks'], cl, period_2)

    clicks_share_dyn = workbook.add_worksheet(u'Clicks_Share_dyn')
    clicks_share_dyn.merge_range(0, 1, 0, 3, u'Суммарно', merge_format)
    clicks_share_dyn.merge_range(0, 4, 0, 6, u'Поиск', merge_format)
    clicks_share_dyn.merge_range(0, 7, 0, 9, u'РСЯ', merge_format)
    clicks_share_dyn.write_row(
        1, 0,
        [
            u'Месяц',
            u'Лидер', u'Доля лидера', u'Доля клиента',
            u'Лидер', u'Доля лидера', u'Доля клиента',
            u'Лидер', u'Доля лидера', u'Доля клиента'
        ],
        cell_str_format
    )
    r = 1
    for x in clicks_df.as_matrix():
        clicks_share_dyn.write_row(1 + r, 0, x)
        r += 1

    clicks_share = workbook.add_worksheet(u'Clicks_Share')
    clicks_share.write_row(
        0, 0,
        [
            u'Клиент', u'Клики (суммарно)',
            u'Клиент', u'Клики (поиск)',
            u'Клиент', u'Клики (РСЯ)',
            period_2
        ],
        cell_str_format
    )
    r = 0
    for x in clicks_rating.as_matrix():
        clicks_share.write_row(1 + r, 0, x)
        r += 1

    stopwatch("Clicks_Share_dyn")

    #####################################################
    # Сравнение доли клиента с долей лидера по расходам #
    #####################################################
    cost_df, cost_rating = calculate_leader_share(df, [u'Cost', u'Direct_Cost', u'RSYA_Cost'], cl, period_2)

    cost_share_dyn = workbook.add_worksheet(u'Cost_Share_dyn')
    cost_share_dyn.merge_range(0, 1, 0, 3, u'Суммарно', merge_format)
    cost_share_dyn.merge_range(0, 4, 0, 6, u'Поиск', merge_format)
    cost_share_dyn.merge_range(0, 7, 0, 9, u'РСЯ', merge_format)
    cost_share_dyn.write_row(
        1, 0,
        [
            u'Месяц',
            u'Лидер', u'Доля лидера', u'Доля клиента',
            u'Лидер', u'Доля лидера', u'Доля клиента',
            u'Лидер', u'Доля лидера', u'Доля клиента'
        ],
        cell_str_format
    )
    r = 1
    for x in cost_df.as_matrix():
        cost_share_dyn.write_row(1 + r, 0, x, cell_str_format)
        r += 1

    cost_share = workbook.add_worksheet(u'Cost_Share')
    cost_share.write_row(
        0, 0,
        [
            u'Клиент', u'Расходы (суммарно)',
            u'Клиент', u'Расходы (поиск)',
            u'Клиент', u'Расходы (РСЯ)',
            period_2
        ],
        cell_str_format
    )
    r = 0
    for x in cost_rating.as_matrix():
        cost_share.write_row(1 + r, 0, x, cell_str_format)
        r += 1

    stopwatch("Cost_Share_dyn")

    ########
    # PSPI #
    ########
    # PSPI = category_cost * client_cost^-1 * client_clicks^2 * category_clicks^-2
    worksheet_pspi = workbook.add_worksheet(u'PSPI_Direct')
    worksheet_pspi.write(0, 0, u'PSPI_Direct')
    worksheet_pspi.write_row(0, 1, prettify_months(months))

    cell_percent_format = workbook.add_format(
        {
            'font_name': 'Textbook New',
            'font_size': '7',
            'bold': False,
            'align': 'center',
            'valign': 'vcenter',
            'font_color': '#808080',
            'text_wrap': True,
            'num_format': '0%',
        }
    )

    curs.execute(
        u"""SELECT
              Client
            , sum(Direct_Clicks) * sum(Direct_Clicks) / sum(Direct_Cost) PSPI
            , Month
            FROM {tbl}
            WHERE CustomCategory = '{category}'
            GROUP BY Client, Month
            ORDER BY PSPI DESC, Month;""".format(tbl=TMP_TBL, category=cat)
    )
    pspi_clients = curs.fetchall()

    curs.execute(
        u"""SELECT
              sum(Direct_Cost) / sum(Direct_Clicks) / sum(Direct_Clicks) PSPI
            , Month
            FROM {tbl}
            WHERE CustomCategory = '{category}'
            GROUP BY Month
            ORDER BY Month;""".format(tbl=TMP_TBL, category=cat)
    )
    pspi_category = curs.fetchall()

    # pivot = [[client, ] for client in {x[0] for x in pspi_clients}]
    top_df = pd.read_sql_query(
        u"""SELECT
              Client
            , sum(Cost) AS "sumCost"
            FROM    """ + TMP_TBL + u"""
            WHERE CustomCategory IN ('""" + cat + u"""')
              AND Month >= """ + period_1[:6] + u"""
              AND Month <= """ + period_2[-6:] + u"""
            GROUP BY Client
            ORDER BY "sumCost" DESC
            LIMIT 30""",
        conn
    )
    top_clients2 = top_df.Client.tolist()

    if cl not in top_clients2:
        top_clients2.insert(0, cl)
        top_clients2 = top_clients2[:30]

    pivot = [[client, ] for client in top_clients2]

    for month in sorted(months):
        filtered_pspi_category = filter(lambda x: int(x[1]) == int(month), pspi_category)[0][0]
        if filtered_pspi_category is None:
            filtered_pspi_category = 0.0
        filtered_pspi_clients_month = filter(lambda x: int(x[2]) == int(month), pspi_clients)
        for client in pivot:
            try:
                filtered_pspi_client = filter(lambda x: x[0] == client[0], filtered_pspi_clients_month)[0][1]
            except IndexError:
                filtered_pspi_client = 0.0
            finally:
                if filtered_pspi_client is None:
                    filtered_pspi_client = 0.0
            client.append(filtered_pspi_category * filtered_pspi_client)

    pivot.sort(key=lambda x: x[-1], reverse=True)

    for n in range(len(pivot)):
        current_row = n + 1
        worksheet_pspi.write_row(current_row, 0, pivot[n])
        worksheet_pspi.set_row(current_row, 20)

    worksheet_pspi.conditional_format(
        1, 1,
        len(pivot), 1 + len(months),
        {u'type': u'3_color_scale'},
    )
    worksheet_pspi.set_column(1, len(months), 3, cell_percent_format)
    worksheet_pspi.set_column(0, 0, 20, cell_str_format)
    worksheet_pspi.set_row(0, 20, cell_str_format)

    stopwatch("PSPI_Direct")

    if not stopwatch.is_quiet:
        print u"\n>>TOP-5 вкладок<<"
        for label, call_s, tot_s in stopwatch.top(5):
            print label, call_s, tot_s

    workbook.close()


def _read_column(sheet, col_idx, skip_nrows=0):
    assert 1 <= col_idx <= sheet.max_column
    # в excel нумерация с 1
    vals = [x[0].value for x in sheet.get_squared_range(col_idx, skip_nrows + 1, col_idx, sheet.max_row)
            if x[0].value is not None]

    return vals


def join4filter(xs):
    return '"' + '", "'.join(xs) + '"'


def make_reports(conn, task, dst_dir):
    C_TIME = str(int(time.time()))[:]  # Префикс для создания временных таблиц
    TMP_TBL = 'tmpdata_%s' % C_TIME
    TMP_TABLE_COMP_MONTHS = 'tmp_comp_months_%s' % C_TIME
    TMP_TABLE_COMP_QVART = 'tmp_comp_qvart_%s' % C_TIME

    # условия для фильтрации
    wb = load_workbook(task, read_only=True)
    ws = wb.get_sheet_by_name("Info")

    task = dict()
    task["months"] = [str(int(x)) for x in _read_column(ws, col_idx=1, skip_nrows=1)]
    task["competitors"] = [x.strip() for x in _read_column(ws, col_idx=2, skip_nrows=1)]
    task["regions"] = [x for x in _read_column(ws, col_idx=4, skip_nrows=1)]
    task["cats"] = [x.strip() for x in _read_column(ws, col_idx=5, skip_nrows=1)]
    task["period_1"] = ws.cell(row=2, column=9).value or ''
    task["period_2"] = ws.cell(row=2, column=10).value or ''
    task["industry"] = ws.cell(row=2, column=11).value or ''
    task["share"] = ws.cell(row=2, column=12).value or ''
    task["cur"] = ws.cell(row=2, column=13).value or ''
    # целевые клиенты для отчетов
    task["clients"] = [x.strip() for x in _read_column(ws, col_idx=7, skip_nrows=1)]
    if not task["clients"]:
        task["clients"] = ['None', ]
    # для вкладки про использование регионов, статистика и заголовок
    task["tgt_regions"] = [x.strip() for x in _read_column(ws, col_idx=8, skip_nrows=1)]
    if not task["tgt_regions"]:
        task["tgt_regions"] = ['None', ]

    if os.path.exists(LOG_FILE):
        with open(LOG_FILE, "a") as f:
            f.write("\nPARSED TASK\n:%r\n" % task)

    task["tgt_regions"] = join4filter(task["tgt_regions"])

    fill_null(conn, task["months"], task["cats"], task["clients"], task["regions"])
    make_tmp_table(
        conn,
        task["months"], task["competitors"], task["clients"], task["regions"], task["cats"],
        TMP_TBL, TMP_TABLE_COMP_MONTHS, TMP_TABLE_COMP_QVART
    )

    if os.path.exists(dst_dir):
        old_results = glob("%s/*" % dst_dir)
        for x in old_results:
            os.remove(x)
    else:
        os.mkdir(dst_dir)

    for cl in task["clients"]:
        for cat in task["cats"]:
            _make_report(
                conn,
                cl, cat,
                task["cats"], task["industry"],
                task["months"], task["competitors"],
                task["regions"], task["tgt_regions"],
                task["period_1"], task["period_2"],
                task["share"],
                task["cur"],
                TMP_TBL, TMP_TABLE_COMP_MONTHS, TMP_TABLE_COMP_QVART,
                dst_dir,
            )


def pars_argv():
    parser = argparse.ArgumentParser(
        description=u'Модуль для автоматического создания xlsx-отчетов.'
    )
    parser.add_argument(
        '--base',
        default='source.db', metavar='',
        help=u'Имя используемой базы данных. (default: %(default)s). '
        u'В базе дожна быть таблица data. '
    )
    return parser.parse_args(sys.argv[1:])


def main(src, task, dst_dir):

    if not os.path.exists(src):
        err_msg = "There are no file with data: %s" % src
        raise ValueError(err_msg)
    TASK = "%s.xlsx" % task
    if not os.path.exists(TASK):
        err_msg = "There are no file with task: %s" % TASK
        raise ValueError(err_msg)
    disk_conn = sqlite3.connect(src)
    make_reports(disk_conn, TASK, dst_dir)
    disk_conn.close()


if __name__ == '__main__':
    DESC_FNAME = 'info'
    DB_NAME = 'source.db'
    DST_DIR = 'Result'

    opt = pars_argv()

    with open(LOG_FILE, 'a') as f:
        f.write('start avtograf\n')
    try:
        main(opt.base, DESC_FNAME, DST_DIR)
    except Exception as exc:
        with open(LOG_FILE, 'a') as f:
            traceback.print_exc(file=f)
    else:
        with open(LOG_FILE, 'a') as f:
            f.write('done avtograf\n')
