# coding=utf-8
# create by oldman at 2017/11/24
from optparse import make_option

import datetime
from django.core.management import BaseCommand
from django.db import transaction
from gm_types.gaia import SERVICE_REVIEW_STATUS, SERVICE_REVIEW_TYPE
from openpyxl import load_workbook

from api.models import AttrOptions, Service
from api.models import ImageRelatedServiceRegister
from api.models import ServiceRegister
from api.models import ServiceRegisterItem
from api.models import ServiceRegisterItemKey
from api.models import add_reviewrecord
from hippo.models import Doctor


def read_excel():
    wb = load_workbook(filename=u'service_copy.xlsx')
    sheetnames = wb.get_sheet_names()
    ws = wb.get_sheet_by_name(sheetnames[0])
    # 读取excel
    doctors = []
    for rx in range(2, ws.get_highest_row() + 1):
        try:
            item = {
                "id": ws.cell(row=rx, column=2).value,
                "name": ws.cell(row=rx, column=5).value,
            }
            doctors.append(item)
        except Exception as e:
            print e
            continue

    print 'Done'
    print doctors
    return doctors


class Command(BaseCommand):
    """
    复制美购 python manage.py update_2017_11_24_copy_service --service_ids 111 --service_ids 222 --doctor_ids 'aa'
    --doctor_ids 'bb'
    """

    # option_list = BaseCommand.option_list + (
    #     make_option('--service_ids',
    #                 action='append',
    #                 default=[],
    #                 dest='service_ids',
    #                 help='service_id list [,]'),
    #     make_option('--doctor_ids',
    #                 action='append',
    #                 default=[],
    #                 dest='doctor_ids',
    #                 help='doctor_id list [,]')
    # )

    def handle(self, *args, **options):
        doctors_excel = read_excel()
        # doctor_ids = []
        service_ids = [5809926, 5809939, 5809941, 5809944, 5809945, 5809974, 5809975, 5810305, 5810306, 5810307]
        # service_ids = [5802316,]

        # for service_id in options['service_ids']:
        #     service_ids.append(service_id)
        # for doctor_id in options['doctor_ids']:
        #     doctor_ids.append(doctor_id)
        services = Service.objects.filter(id__in=service_ids)
        # doctors = Doctor.objects.filter(id__in=doctor_ids)
        print services
        for doctor_info in doctors_excel:
            for service in services:
                try:
                    doctor = Doctor.objects.get(id=doctor_info['id'])
                    self._copy_service(service, doctor, doctor_info['name'])
                except Exception as e:
                    print e
                    continue

    def _copy_service(self, service, doctor, name):
        old_name = u'北京@北京拜博口腔(北京拜博口腔医院)'
        try:
            with transaction.atomic():
                serviceregiseters = service.servicereg.all()
                assert len(serviceregiseters) == 1
                serviceregiseter = serviceregiseters[0]
                kwargs = ['name',
                          'reservation',
                          'start_time',
                          'end_time',
                          'photo_details',
                          'project_type',
                          'short_description',
                          'image_header',
                          'is_specialreview',
                          'review_status',
                          'last_submit_time',
                          'total_num',
                          'is_draft',
                          'is_stage', 'add_num',
                          'have_extra_pay',
                          'extra_pay_info',
                          'image_bigpic',
                          'service_type']
                new_serviceregister = ServiceRegister()
                is_seckill = not service.is_multiattribute  # 多属性是非秒杀，
                for key in kwargs:
                    setattr(new_serviceregister, key, getattr(serviceregiseter, key))
                # print name
                print new_serviceregister.name
                print new_serviceregister.name.find(old_name)
                new_serviceregister.name = new_serviceregister.name.replace(old_name, name)
                new_serviceregister.user = doctor.user
                new_serviceregister.doctor = doctor
                new_serviceregister.review_status = SERVICE_REVIEW_STATUS.UNDER_REVIEW
                new_serviceregister.is_register = True
                new_serviceregister.last_submit_time = datetime.datetime.now()
                new_serviceregister.last_review_time = datetime.datetime.now()
                new_serviceregister.save()
                print new_serviceregister.name
                for item in serviceregiseter.supplement_images.all():
                    ImageRelatedServiceRegister.objects.get_or_create(
                        serviceregister=new_serviceregister,
                        image_url=item.image_url
                    )
                for serviceregisteritem in serviceregiseter.items.all():
                    new_serviceregisteritem = ServiceRegisterItem()
                    for key, value in serviceregisteritem.__dict__.iteritems():
                        if not key.startswith('_'):
                            setattr(new_serviceregisteritem, key, value)
                    new_serviceregisteritem.stock_add_num = 99
                    new_serviceregisteritem.id = None
                    new_serviceregisteritem.service_register = new_serviceregister
                    new_serviceregisteritem.serviceitem = None
                    new_serviceregisteritem.save()

                    tag = new_serviceregister.project_type
                    if tag.tagattr_set.filter(is_online=True).exists():
                        options = tag.tag.tagattr_set.filter(is_online=True)
                        for option in options:
                            ServiceRegisterItemKey.objects.create(
                                serviceregisteritem=new_serviceregisteritem,
                                serviceregisterattroption_id=option)
                    else:
                        # 非标准美购
                        serviceregisteritemkeys = ServiceRegisterItemKey.objects.filter(
                            serviceregisteritem=serviceregisteritem
                        )
                        for serviceregisteritemkey in serviceregisteritemkeys:
                            option = serviceregisteritemkey.serviceregisterattroption
                            new_option = AttrOptions(
                                name=option.name,
                                is_online=option.is_online,
                                created_time=option.created_time,
                                is_doctor_create=option.is_doctor_create,
                                tag_attr=option.tag_attr
                            )
                            new_option.save()
                            ServiceRegisterItemKey.objects.create(
                                serviceregisteritem=new_serviceregisteritem, serviceregisterattroption=new_option)
                add_reviewrecord(new_serviceregister,
                                 doctor.user.person.id,
                                 review_type=SERVICE_REVIEW_TYPE.ORDINARY,
                                 explanation=u'新美购复制美购ID：{}'.format(service.id))
                print u'医生：{} 复制美购：{} 成功！,注册ID: {}'.format(doctor.id, service.id, new_serviceregister.id)
        except Exception as e:
            print e
            raise e
