#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: vv
# Date: 2019/10/28

import json
import datetime
from django.core.management import BaseCommand
from gm_types.gaia import DOCTOR_SECKILL_APPLY_STATUS, ACTIVITY_TYPE_ENUM
from api.models import SpecialStock, ServiceItemPrice, Special, SpecialItem, SKUPriceRule, DoctorSeckillApply


class Command(BaseCommand):

    def handle(self, *args, **options):
        print("开始处理!")
        rule_to_specialitems, doctorseckillapply_2_price_ids = {}, {}
        special_ids = Special.objects.filter(
            end_time__gte=datetime.datetime(2019, 9, 1, 0, 0, 0),
            is_new_special=True).values_list('id', flat=True)

        for special_id in special_ids:
            skuprice_rule = SKUPriceRule.objects.filter(
                activity_id=special_id, activity_type=ACTIVITY_TYPE_ENUM.SPECIAL
            ).first()
            if not skuprice_rule:
                continue
            specialitems = list(SpecialItem.objects.filter(
                special_id=special_id,
                doctorseckillapply__isnull=False
            ).distinct().values('doctorseckillapply_id', 'special_id', 'serviceitem_id'))
            if not specialitems:
                continue
            rule_to_specialitems[skuprice_rule.id] = specialitems
        print("价格规则总量: %d" % len(rule_to_specialitems))
        for rule_id, specialitems in rule_to_specialitems.iteritems():
            print("开始处理价格规则: %d, 数据共计: %d" %(rule_id, len(specialitems)))
            for serviceitem_info in specialitems:
                service_item_id = serviceitem_info.get('serviceitem_id')
                doctorseckillapply_id = serviceitem_info.get('doctorseckillapply_id')
                price_obj = ServiceItemPrice.objects.filter(
                    selling_rule_id=rule_id, service_item_id=service_item_id).first()

                if not price_obj or not doctorseckillapply_id:
                    continue

                if doctorseckillapply_id not in doctorseckillapply_2_price_ids:
                    doctorseckillapply_2_price_ids[doctorseckillapply_id] = [price_obj.id]
                else:
                    doctorseckillapply_2_price_ids[doctorseckillapply_id].append(price_obj.id)

        print("开始写入数据, 总计: %d" % len(doctorseckillapply_2_price_ids))
        for doctorseckillapply_id, price_ids in doctorseckillapply_2_price_ids.iteritems():
            dsa = DoctorSeckillApply.objects.get(id=doctorseckillapply_id)
            specialstock, created = SpecialStock.objects.get_or_create(
                doctorseckillapply_id=doctorseckillapply_id,
            )
            price_id = specialstock.price_id
            if price_id:
                price_id = json.loads(specialstock.price_id)
            else:
                price_id = price_ids

            sip = ServiceItemPrice.objects.filter(id__in=price_id).last()
            if sip:
                specialstock.stock = sip.sale_limit
                dsa.stock = sip.sale_limit
                dsa.save()
            else:
                specialstock.stock = dsa.stock
            specialstock.price_id = json.dumps(price_id)
            specialstock.save()
        print("同步完毕!")

