# coding=utf8

from helios.rpc import create_default_invoker
from datetime import datetime
from django.core.management.base import BaseCommand
from agile.models import TagMapOldTag
from api.models import ServiceTag, ServiceNewTag, Tag, Service
from agile.models import TagV3
from django.conf import settings
from gm_types.gaia import TAG_V3_TYPE, TAG_TYPE
import math
from itertools import groupby, chain


body_part_dict = {
    u'半永久妆': u'半永久纹眉',
    u'抗衰紧致': u'除皱针',
    u'瘦身美体': u'全身塑形',
}


sub_item_dict = {
    u'V-line瓜子脸手术': u'小V脸',
    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'下颌内缩',
    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'手术祛副乳',
    u'光子脱毛': u'激光脱全身毛发',
    u'祛纹身': u'激光祛纹身',
    u'手臂': u'吸脂瘦手臂',
    u'洗牙': u'洗牙',
    u'开眼角': u'开内眼角,开外眼角',
    u'祛红血丝': u'激光祛红血丝',
    u'眼部综合': u'眼综合',
    u'面部吸脂': u'吸脂瘦脸',
    u'半永久 生活美容': u'半永久纹眉',
    u'唇形': u'M唇',
    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'小v脸',
    u'毛发其他': u'养发护理',
    u'毛发移植': u'植发',
    u'美白嫩肤': u'皮肤综合护理',
    u'美肤 生活美容': u'皮肤综合护理',
    u'美容SPA 生活美容': 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'身体塑形': u'全身塑形',
    u'手术套餐': u'小v脸',
    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'口腔综合治疗',
    u'牙齿美白': u'恒温美白',
    u'牙齿整形': u'牙齿隐形矫正',
    u'眼部修复': u'双眼皮修复',
    u'眼睑': u'上眼睑提肌',
    u'眼科其他': u'眼科检查',
    u'中医减肥': u'中医瘦身',
    u'注射美肤': u'水光针',
    u'胸部套餐': u'乳腺疏通',
    u'胸部形态重塑': u'乳房再造',
    u'胸部修复': u'胸部修复',
    u'药物脱毛': u'药物脱毛',
    u'脂肪其他': u'自体脂肪填充修复',
}


class Command(BaseCommand):
    """
        美购标签清洗
    """

    @staticmethod
    def _get_time_string(time):
        return time.strftime('%Y-%m-%d %H:%M:%S %f')

    @staticmethod
    def _gets_old_tag1(start, size=100):
        qs = ServiceTag.objects.using(settings.SLAVE_DB_NAME).filter(tag__tag_type=TAG_TYPE.BODY_PART)
        total = qs.count()
        if start > total:
            return []
        return qs[start: start + size].values_list('tag__name', 'service_id')

    @staticmethod
    def _gets_old_tag2(start, size=100):
        qs = ServiceTag.objects.using(settings.SLAVE_DB_NAME).filter(tag__tag_type=TAG_TYPE.BODY_PART_SUB_ITEM)
        total = qs.count()
        if start > total:
            return []
        return qs[start: start + size].values_list('tag__name', 'service_id')

    @staticmethod
    def _gets_old_tag3(start, size=100):
        qs = ServiceTag.objects.using(settings.SLAVE_DB_NAME).filter(tag__tag_type=TAG_TYPE.ITEM_WIKI)
        total = qs.count()
        if start > total:
            return []
        return qs[start: start + size].values_list('tag_id', 'service_id')

    def get_tag_id_map_tag_v3_ids_relation(self, num):
        """
        获取美购与标签的映射关系
        :return: {service_id: [old_id, old_id],service_id: [old_id, old_id]}
        """
        tag_dict = {
            1: self._gets_old_tag1,
            2: self._gets_old_tag2,
            3: self._gets_old_tag3,
        }
        old_tag_type = tag_dict[num]
        self.step = 100
        result = {}
        start = 0
        old_tag_list = []
        # 这里是获取全部的新项目标签
        while True:
            get_old_tag = old_tag_type(start)
            if not get_old_tag:
                break
            else:
                old_tag_list += get_old_tag
            start += 100
        for service_id, items in groupby(sorted(old_tag_list, key=lambda x: x[1]), key=lambda j: j[1]):
            result[service_id] = [item[0] for item in items]
        print(len(result))
        return result

    @staticmethod
    def del_content_rel_tag_info():
        """
        删除关联关系
        :param tag_model_:
        :param rel_ids:
        :return:
        """
        ServiceNewTag.objects.all().delete()

    @staticmethod
    def old_new_tag_rel(attr_tag_maps, old_tag_service_rel):
        result = {}
        for service_id in attr_tag_maps:
            old_tag_list = old_tag_service_rel[service_id]
            result[service_id] = set(TagMapOldTag.objects.using(settings.SLAVE_DB_NAME).filter(old_tag_id__in=old_tag_list).values_list('tag_id', flat=True))
            if not result[service_id]:
                del result[service_id]
        return result


    @staticmethod
    def old_new_tag_rel_dict_rel_v2_v1(dict_name, attr_tag_maps, old_tag_service_rel):
        result = {}
        for service_id in attr_tag_maps:
            result[service_id] = set()
            for tag_name in old_tag_service_rel[service_id]:
                if dict_name.get(tag_name, None) is not None:
                    try:
                        new_tag = TagV3.objects.using(settings.SLAVE_DB_NAME).filter(name=dict_name[tag_name], tag_type=TAG_V3_TYPE.NORMAL).first()
                        result[service_id].add(new_tag.id)
                    except:
                        pass
            if not result[service_id]:
                del result[service_id]
        return result

    def add_content_rel_tag_info(self, new_tag_service_rel):
        """
        批量创建
        :param tag_model_:
        :param rel_bulk_list: [{"rel_param": id, "tag_v3_id": 1}]
        :return:
        """
        insert_relation_list = []
        for service_id, new_tag_list in new_tag_service_rel.items():
            service = Service.objects.using(settings.SLAVE_DB_NAME).filter(id=service_id).first()
            if not service:
                continue
            new_tag_list = TagV3.objects.using(settings.SLAVE_DB_NAME).filter(id__in=new_tag_list).values_list('id',
                                                                                                              flat=True)
            for new_tag in new_tag_list:
                insert_relation_list.append(ServiceNewTag(
                    service_id=service_id,
                    tag_id=new_tag,
                ))
        ServiceNewTag.objects.bulk_create(insert_relation_list)


    def add_content_rel_tag_info_v2_v1(self, new_tag_service_rel):
        """
        批量创建
        :param tag_model_:
        :param rel_bulk_list: [{"rel_param": id, "tag_v3_id": 1}]
        :return:
        """
        insert_relation_list = []
        for service_id, new_tag_list in new_tag_service_rel.items():
            service = Service.objects.using(settings.SLAVE_DB_NAME).filter(id=service_id).first()
            if not service:
                continue
            for new_tag in new_tag_list:
                insert_relation_list.append(ServiceNewTag(
                    service_id=service_id,
                    tag_id=new_tag,
                ))
        ServiceNewTag.objects.bulk_create(insert_relation_list)


    def clean_tag_data_v3(self, old_tag_service_rel, size=100):
        start = 0
        end = size
        service_id_list = old_tag_service_rel.keys()
        attr_tag_maps = service_id_list[start: end]
        while attr_tag_maps:
            print 'update_all_tag_map dealing start is {} end is {} at {}'.format(
                start, end, self._get_time_string(datetime.now()))
            new_tag_service_rel = self.old_new_tag_rel(attr_tag_maps, old_tag_service_rel)
            self.add_content_rel_tag_info(new_tag_service_rel)
            start = end
            end = end + size
            attr_tag_maps = service_id_list[start: end]

    def clean_tag_data_v2_v1(self, num, old_tag_service_rel, size=100):
        tag_dict = {
            1: body_part_dict,
            2: sub_item_dict,
        }
        old_tag_type = tag_dict[num]

        start = 0
        end = size
        service_id_list = old_tag_service_rel.keys()
        attr_tag_maps = service_id_list[start: end]
        while attr_tag_maps:
            print 'update_all_tag_map_v1 dealing start is {} end is {} at {}'.format(
                start, end, self._get_time_string(datetime.now()))
            new_tag_service_rel = self.old_new_tag_rel_dict_rel_v2_v1(old_tag_type, attr_tag_maps, old_tag_service_rel)
            self.add_content_rel_tag_info_v2_v1(new_tag_service_rel)
            start = end
            end = end + size
            attr_tag_maps = service_id_list[start: end]


    def handle(self, *args, **options):
        print('start deal at {}'.format(self._get_time_string(datetime.now())))
        old_tag_service_rel_v1 = self.get_tag_id_map_tag_v3_ids_relation(1)
        old_tag_service_rel_v2 = self.get_tag_id_map_tag_v3_ids_relation(2)
        old_tag_service_rel_v3 = self.get_tag_id_map_tag_v3_ids_relation(3)
        self.del_content_rel_tag_info()
        # print('old_tag_service_rel_v1', old_tag_service_rel_v1)
        # print('old_tag_service_rel_v2', old_tag_service_rel_v2)
        # print('old_tag_service_rel_v3', old_tag_service_rel_v3)
        self.clean_tag_data_v3(old_tag_service_rel_v3)
        self.clean_tag_data_v2_v1(1, old_tag_service_rel_v1)
        self.clean_tag_data_v2_v1(2, old_tag_service_rel_v2)

        print('end deal at {}'.format(self._get_time_string(datetime.now())))
