# coding=utf-8
from django.core.management import BaseCommand
from django.db import transaction
from api.models.service import AttrOptions
from api.models.service import Service, ServiceItem,ServiceItemKey, ServiceRegister, ServiceAttrOption
from api.models.service import ServiceRegisterItem, ServiceRegisterItemKey
from gm_types.gaia import SERVICE_REVIEW_STATUS
from datetime import datetime
from django.conf import settings


class Command(BaseCommand):
    def handle(self, *args, **options):
        result_log = open('serviceregister.txt', 'a')
        service_log = open('success_service.txt', 'a')
        error_log = open('error_service.txt', 'a')
        services = Service.objects.all()
        bgn = 0
        step = 1000
        cnt = services.count()
        while bgn <= cnt:
            for service in services[bgn: bgn+step].iterator():
                try:
                    with transaction.atomic():
                        self.update_service(service)
                        serviceregister_id = self.create_serviceregister(service)
                        items = ServiceItem.objects.filter(service_id=service.id)
                        serviceregisteritems = ServiceRegisterItem.objects.filter(service_register_id=serviceregister_id)\
                            .update(is_delete=True)
                        not_create_items = True
                        if not items.exists():
                            not_create_items = False
                            attroptions_id = self.create_attroptions(service.name)
                            self.create_serviceitem(service, attroptions_id, False)
                        new_items = ServiceItem.objects.filter(service_id=service.id)
                        count = 0
                        for new_item in new_items:
                            if not service.is_multiattribute:
                                new_item = self.update_serviceitem(new_item, service, count)
                            if not_create_items:
                                keys = new_item.key.split('-')
                                name = ''
                                for key in keys:
                                    name += ServiceAttrOption.objects.get(id=key).name
                                attroptions_id = self.create_attroptions(name)
                            serviceregisteritem_id = self.create_serviceregisteritem(new_item, serviceregister_id)
                            item_data = self.create_itemkey(new_item.id, serviceregisteritem_id, attroptions_id)
                            message = u'%s,%s,%s,%s,%s,%s,%s\n' \
                                      % (service.id, serviceregister_id, attroptions_id, new_item.id,
                                         serviceregisteritem_id, item_data['serviceitemkey'],
                                         item_data['serviceregisteritemkey'])
                            result_log.writelines(message)
                            count += 1
                        print service.id
                        service_log.write(str(service.id) + '\n')
                except Exception as e:
                    message = str(service.id) + ':' + e.message
                    print message
                    error_log.writelines(message + '\n')
                    import traceback;traceback.print_exc(error_log)
                    continue
            bgn += step
        print u'DONE!'

    def update_service(self, service):
        project_types = service.tags.filter(tag_type__in=[2, 3])
        service.project_type = project_types[0] if project_types else None
        service.save()

    def create_serviceregister(self, service):
        serviceregister_data = {
            'name': service.name,
            'doctor_id': service.doctor_id,
            'short_description': service.short_description,
            'reservation': service.reservation,
            'start_time': service.start_time,
            'end_time': service.end_time,
            'image_header': service.image_header,
            'total_num': service.total_num,
            'is_register': False,
            'review_status': SERVICE_REVIEW_STATUS.PASS,
            'last_review_time': datetime.now(),
            'service_id': service.id,
            'user_id': service.doctor.user.id,
            'project_type_id': service.project_type_id
        }
        if service.servicereg.exists():
            serviceregister = service.servicereg.all()[0]
            for k, v in serviceregister_data.iteritems():
                setattr(serviceregister, k, v)
            serviceregister.save()
        else:
            serviceregister_data['online_time'] = datetime.now()
            serviceregister = ServiceRegister.objects.create(**serviceregister_data)
        return serviceregister.id

    def create_attroptions(self, name):
        attroptions_data = {
            'name': name,
            'is_online': True,
            'created_time': datetime.now(),
            'is_doctor_create': True,
            'tag_attr_id': settings.DEFAULT_TAG_ATTR_ID,
        }
        attroptions = AttrOptions.objects.create(**attroptions_data)
        return attroptions.id

    def create_serviceitem(self, service, attroptions_id, is_item):
        serviceitem_data = {
            'service_id': service.service_id if is_item else service.id,
            'key': attroptions_id,
            'cash_back_fee': service.cash_back_fee,
            'cash_back_rate': service.cash_back_rate,
            'discount': service.discount,
            'gengmei_price': service.gengmei_price,
            'original_price': service.original_price,
            'pre_payment_price': service.pre_payment_price,
            'points_deduction_percent': service.points_deduction_percent,
            'self_support_discount': service.self_support_discount,
            'sort': service.sort if is_item else service.ordering,
        }
        serviceitem = ServiceItem.objects.create(**serviceitem_data)
        return serviceitem.id

    def update_serviceitem(self, item, service, count):
        service_item = ServiceItem.objects.get(id=item.id)
        serviceitem_date={
            'cash_back_fee': service.cash_back_fee,
            'cash_back_rate': service.cash_back_rate,
            'discount': service.discount,
            'gengmei_price': service.gengmei_price,
            'original_price': service.original_price,
            'pre_payment_price': service.pre_payment_price,
            'points_deduction_percent': service.points_deduction_percent,
            'self_support_discount': service.self_support_discount,
            'sort': service.ordering,
            'is_delete': False,
        }
        if count:
            serviceitem_date['is_delete'] = True

        for k, v in serviceitem_date.iteritems():
            setattr(service_item, k, v)
        service_item.save()
        return service_item

    def create_serviceregisteritem(self, item, serviceregister_id):
        serviceregisteritem_data = {
            'key': item.key,
            'discount': item.discount,
            'pre_payment_price_int': item.pre_payment_price,
            'original_price': item.original_price,
            'gengmei_price': item.gengmei_price,
            'cash_back_fee': item.cash_back_fee,
            'cash_back_rate': item.cash_back_rate,
            'points_deduction_percent': item.points_deduction_percent,
            'sort': item.sort,
            'is_online': True,
            'service_register_id': serviceregister_id,
            'serviceitem_id': item.id,
            'is_delete': item.is_delete
        }
        serviceregisteritem = ServiceRegisterItem.objects.create(**serviceregisteritem_data)
        return serviceregisteritem.id

    def create_itemkey(self, serviceitem_id, serviceregisteritem_id, attroptions_id):
        ServiceItemKey.objects.filter(serviceitem_id=serviceitem_id).delete()
        ServiceRegisterItemKey.objects.filter(serviceregisteritem_id=serviceregisteritem_id).delete()
        serviceitemkey = ServiceItemKey.objects.create(serviceitem_id=serviceitem_id,
                                                       serviceattroption_id=attroptions_id)
        serviceregisteritemkey = ServiceRegisterItemKey.objects.create(
            serviceregisteritem_id=serviceregisteritem_id, serviceregisterattroption_id=attroptions_id)
        return {
            'serviceitemkey': serviceitemkey.id,
            'serviceregisteritemkey': serviceregisteritemkey.id
        }
