from functools import reduce

from django.conf import settings
from gm_types.gaia import TOPIC_TYPE, PROBLEM_FLAG_CHOICES, TAG_TYPE

from talos.services import UserService
from talos.models.topic import Problem, Article


REGION_LIST = [u'北京', u'上海', u'广州', u'深圳', u'山东', u'湖南', u'广西', u'香港', u'青海',
               u'江苏', u'宁夏', u'四川', u'辽宁', u'台湾', u'广东', u'吉林', u'陕西', u'安徽',
               u'天津', u'甘肃', u'河北', u'海南', u'内蒙古', u'云南', u'湖北', u'浙江', u'黑龙江',
               u'重庆', u'山西', u'新疆', u'河南', u'贵州', u'福建', u'江西']


def build_topic_title(topic_id, tag_name, user_name):
    last_id = str(topic_id)[-1]
    last_id_dict = {
        '0': (u'', u'_更美'),
        '1': (u'图片', u'_更美'),
        '2': (u'手术', u'_更美'),
        '3': (u'多少钱', u'_更美'),
        '4': (u'价格', u'_更美'),
        '5': (u'效果图', u'_更美'),
        '6': (u'对比图', u'_更美'),
        '7': (u'前后对比照', u'_更美'),
        '8': (u'整形', u'_更美'),
        '9': (u'地区', u'_更美')
    }
    str_extra, str_end = last_id_dict[last_id]

    if last_id not in ['0', '9']:
        title = tag_name + str_extra + u'_' + user_name

    elif last_id in ['9', ]:
        pos = reduce(lambda x, y: int(x) + int(y), str(topic_id))
        region_name = REGION_LIST[pos % len(REGION_LIST)]
        region_name = u'【' + region_name + u'】'
        title = region_name + tag_name + u'_' + user_name

    else:
        title = u'{}的{}分享_{}【图片 价格】'.format(user_name, tag_name, tag_name)

    return title


def build_topics(topics):
    for topic in topics:
        tag_name = None
        for _tag in topic["tags"]:
            if _tag['type'] in [TAG_TYPE.BODY_PART,
                                TAG_TYPE.BODY_PART_SUB_ITEM,
                                TAG_TYPE.ITEM_WIKI]:
                tag_name = _tag['name']
                break
        if tag_name:
            title = build_topic_title(topic["id"], tag_name, topic["user_name"])
        else:
            title = u'{}的整形分享【多图】_更美APP官网'.format(topic["user_name"])
        topic["title"] = title
        topic["type"] = "topic"

        del topic["user_name"]
        del topic["tags"]

    return topics


def get_topic_html_sitemap(offset=0, limit=10000):

    topics = Problem.objects.using(settings.SLAVE_DB_NAME).filter(is_online=True, diary__isnull=False,
                                                                  selected_qa=True, flag=PROBLEM_FLAG_CHOICES.NORMAL). \
        select_related("diary").order_by("-created_time")[offset: limit]

    res = []
    for topic in topics:
        me = UserService.get_user_by_user_id(topic.user_id)
        info = {
            "user_name": me.nickname,
            "tags": topic.diary.tags_new_era,
            "id": topic.id,
            "created_time": topic.created_time.strftime('%Y-%m-%d') if topic.created_time else '',
        }
        res.append(info)

    return build_topics(res)


def get_article_html_sitemap(limit=10000):
    articles = Article.objects.using(settings.SLAVE_DB_NAME).filter(is_online=True, article_type=TOPIC_TYPE.COLUMN_ARTICLE). \
                  extra({'created_time': "DATE_FORMAT(created_time, '%%Y-%%d-%%m')"}).only("article_id", "created_time").order_by("-created_time")[0: limit]

    res = []
    for article in articles:
        topic = Problem.objects.filter(id=article.article_id, is_online=True)
        res.append({
            "title": topic[0].title if topic else "",
            "id": article.article_id,
            "created_time": article.created_time,
            "type": "article",
        })

    return res
