# -*- coding:utf-8 -*-
from __future__ import print_function
from api.models import SpecialItem, SpecialRelatedTag
from rpc.tool.dict_mixin import to_dict
from django.core.management import BaseCommand


def create_new_special_floor_data(related_dict):
    for k, v in related_dict.iteritems():
        old_special_id, old_child_storey_id, new_special_id, new_child_storey_id = k + v

        # 创建楼层关联tag
        related_tag_objs = []
        tag_ids = list(SpecialRelatedTag.objects.filter(
            special_id=old_special_id, floor_id=old_child_storey_id
        ).values_list('tag_id', flat=True))
        print("start to replication specialrelatetag, "
              "old_special_id: {old_special_id}, new_special_id: {new_special_id}".format(
            old_special_id=old_special_id, new_special_id=new_special_id))
        for tag_id in tag_ids:
            related_tag_objs.append(SpecialRelatedTag(
                special_id=new_special_id, floor_id=new_child_storey_id, tag_id=tag_id)
            )

        SpecialRelatedTag.objects.bulk_create(related_tag_objs)
        print("replication specialrelatetag success!")
        # 创建该楼层下关联的美购列表
        old_special_items = SpecialItem.objects.filter(special_id=old_special_id, floor_id=old_child_storey_id)

        # 创建新的美购列表数据
        print("old_specialitem data count: {count}".format(count=old_special_items.count()))
        for old_special_item in old_special_items:
            new_special_item_data = to_dict(
                old_special_item,
                fields=['name', 'subtitle', 'image_url', 'doctor_id',
                        'topic_id', 'diary_id', 'service_id',
                        'rank', 'position', 'is_recommend', 'serviceitem_id',
                        'doctorseckillapply_id', 'sell_num', 'tip']
            )
            new_special_item_data['floor_id'] = new_child_storey_id
            new_special_item_data['special_id'] = new_special_id
            specialitem = SpecialItem.objects.create(**new_special_item_data)
            specialitem.update_or_create_price_info()
        print("new_specialitem replication success!")


def create_serviceitem_prices(new_special_id):
    specialitems = SpecialItem.objects.filter(special_id=new_special_id, floor_id__null=True)
    print("start to replication outer specialitems: {count}".format(count=specialitems.count()))
    for specialitem in specialitems:
        specialitem.update_or_create_price_info()
    print("replication outer specialitems success!")


def replication_special_floor(
        old_special_id, new_special_id,
        has_child_storey_related_dict=None,
        has_no_child_storey_related_dict=None
):
    """
    复制楼层数据
    :param old_special_id:
    :param new_special_id:
    :param has_child_storey_related_dict:
    :param has_no_child_storey_related_dict:
    :return:
    """
    def replication_parent_service_list(old_special_id, new_special_id):
        """
        复制父级美购列表数据
        :param old_special_id:
        :param new_special_id:
        :return:
        """
        specialitem_objs = []
        specialitems = SpecialItem.objects.filter(special_id=old_special_id, floor_id__isnull=True)

        if not specialitems:
            return
        for specialitem in specialitems:
            new_special_item_data = to_dict(
                specialitem,
                fields=['name', 'subtitle', 'image_url', 'doctor_id',
                        'topic_id', 'diary_id', 'service_id',
                        'rank', 'position', 'is_recommend', 'serviceitem_id',
                        'doctorseckillapply_id', 'sell_num', 'tip']
            )
            new_special_item_data['special_id'] = new_special_id
            specialitem_objs.append(SpecialItem(**new_special_item_data))
        SpecialItem.objects.bulk_create(specialitem_objs)

    def replication_parent_tag(old_special_id, new_special_id):
        """
        复制父级关联的标签数据
        :param old_special_id:
        :param new_special_id:
        :return:
        """
        tag_ids = list(SpecialRelatedTag.objects.filter(
            special_id=old_special_id, floor_id__isnull=True
        ).values_list('tag_id'))

        if not tag_ids:
            return

        objs = [
            SpecialRelatedTag(special_id=new_special_id, tag_id=tag_id)
            for tag_id in tag_ids
        ]
        new_objs = SpecialRelatedTag.objects.bulk_create(objs)
        return [obj.id for obj in new_objs]

    replication_parent_service_list(old_special_id, new_special_id)
    replication_parent_tag(old_special_id, new_special_id)

    # 存在子楼层
    if has_child_storey_related_dict:
        create_new_special_floor_data(has_child_storey_related_dict)

    if has_no_child_storey_related_dict:
        create_new_special_floor_data(has_no_child_storey_related_dict)

    if SpecialItem.objects.filter(special_id=new_special_id, floor_id__isnull=True).exists():
        create_serviceitem_prices(new_special_id)


class Command(BaseCommand):

    def handle(self, *args, **options):
        old_special_id = 123
        new_special_id = 233

        # (old_special_id, old_child_storey.id): (new_special_id, new_child_storey.id)
        has_child_storey_related_dict = {
            (798, 1312): (810, 1413),
        }

        # (old_special_id, old_parent_storey.id): (new_special_id, new_parent_storey.id)
        has_no_child_storey_related_dict = {
            (798, 1312): (810, 1413)
        }

        replication_special_floor(
            old_special_id=old_special_id, new_special_id=new_special_id,
            has_child_storey_related_dict=has_child_storey_related_dict,
            has_no_child_storey_related_dict=has_no_child_storey_related_dict
        )
