# -*- coding:utf-8 -*-

import os
import multiprocessing
from django.core.management import BaseCommand
from gm_types.gaia import TAG_TYPE

from api.tool.user_tool import get_user_city_tagid
from api.models.service import Service
from api.models.order import Order
from talos.models.diary.diary import Diary

areas_types = (
    TAG_TYPE.CITY,
    TAG_TYPE.PROVINCE,
    TAG_TYPE.COUNTRY,
)

file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "updateTag.log")


def _get_city_tag(diary):

    try:
        order = Order.objects.get(id=diary.order_id)
        if order and order.service.doctor.hospital:
            return order.service.doctor.hospital.city.tag.id
    except Exception:

        try:
            service = Service.objects.get(id=diary.service_id)
            if service and service.doctor.hospital:
                return service.doctor.hospital.city.tag.id
        except Exception:

            return get_user_city_tagid(diary.user_id)


def _tag_logic_ratio(item, new, old, flog):
    if new:
        if old:
            if new in old and len(old) == 1:
                pass
            else:
                item.del_tags(list(set(old)))
                item.add_tags([new, ])
                with open(file_path, "ab+") as f:
                    f.write("update {0} Tag,id:{1}\n".format(flog, item.id))
        else:
            item.add_tags([new, ])
            with open(file_path, "ab+") as f:
                f.write("update {0} Tag,id:{1}\n".format(flog, item.id))
    else:
        if old:
            item.del_tags(list(set(old)))
            with open(file_path, "ab+") as f:
                f.write("update {0} Tag,id:{1}\n".format(flog, item.id))


def _update_city_tag(diary, old_tags=None):
    city_tag_id = _get_city_tag(diary)
    _tag_logic_ratio(item=diary, new=city_tag_id, old=old_tags, flog="diary")

    if diary.topics.count() > 0:
        for topic in diary.topics.all().iterator():
            try:
                topic_tag_ids = [tag.id for tag in topic.tags if tag.tag_type in areas_types]
                _tag_logic_ratio(item=topic, new=city_tag_id, old=topic_tag_ids, flog="topic")
            except Exception as e:
                print e
                print "Error topic_id: {0}".format(topic.id)


def _async_filter_tag(diary):
    try:
        city_tags = list(filter(lambda x: x.tag_type in areas_types, diary.all_tags))
        if city_tags:
            old_city_tag = [tag.id for tag in city_tags]
            _update_city_tag(diary=diary, old_tags=old_city_tag)
        else:
            _update_city_tag(diary=diary)
    except Exception as e:
        print e
        print "Error diary_id: {0}".format(diary.id)


class Command(BaseCommand):
    """
        日记本地域性标签 清洗

        美购日记本: 绑定订单城市;非美购日记本:绑定用户设置城市
    """

    def handle(self, *args, **kwargs):
        print "start work"
        
        pool = multiprocessing.Pool(processes=4)
        diaries = Diary.objects.all().iterator()

        for diary in diaries:
            pool.apply_async(_async_filter_tag, (diary,))
        pool.close()
        pool.join()

        print 'end work'
