#!/usr/bin/env python
# coding=utf-8

from rpc.decorators import bind_context
from api.tool.user_tool import get_doctor_from_context
from rpc.tool.error_code import gen, CODES
from django.db.models import Q, Max
from api.models import Service, ServiceItemKey, AttrOptions, CommodityCategoryRelation, \
    CommodityCategoryPropertyRelation, \
    ServiceRegister, ServiceRegisterVideo, ServiceItem, ServiceRegisterItem, ServiceItemPrice, ServiceReviewRecord, F,\
    ServiceRegisterItemKey,AuditAttrOptions, ServiceRegisterTag, ServiceTag, Tag, TagRelation
from api.tool.datetime_tool import get_timestamp, get_timestamp_epoch
from doctor.views.service import get_tag_template
from rpc.tool.dict_mixin import to_dict
from gm_upload.upload import get_video_upload_token
from django.conf import settings
from django.db import transaction
from gaia.routers import thread_local
from gm_types.gaia import SERVICE_REVIEW_STATUS,SERVICE_REVIEW_TYPE, TAG_TYPE
from rpc.all import get_rpc_remote_invoker
from rpc.tool.log_tool import info_logger


@bind_context('doctor/servicedetail/list', login_required=True)
@thread_local(DB_FOR_READ_OVERRIDE=settings.SLAVE_DB_NAME)
def get_doctor_service_detail_list(ctx, count=10,
            is_online=None,
            start_num=0,
            doctor_ids=None,
            service_id=None,
            serviceitem_id=None,
            service_name=None,
            project_type=None,
            extra_filter_choice=None
            ):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    q = Q(is_delete=False,servicereg__is_register=False, servicereg__doctor_can_see=True)

    if doctor_ids:
        q &= Q(doctor__in=doctor_ids)
    else:
        q &= Q(doctor__in=[doctor])

    if service_id:
        q &=Q(id=service_id)

    if serviceitem_id:
        q &=Q(items__id=serviceitem_id)

    if service_name:
        q &=Q(name__contains=service_name)

    if project_type:
        filter_tag = Tag.objects.filter(id=project_type).first()
        if not filter_tag:
            return {
                'size':count,
                'total':0,
                'counts':[0,0,0,0,0],
                'services':[]
            }
        if filter_tag.tag_type != TAG_TYPE.ITEM_WIKI:
            all_tag_id = TagRelation.objects.filter(parent=filter_tag, is_deleted=False).values_list('child_id', flat=True)
        else:
            all_tag_id = [filter_tag.id]

        filter_service_id_list = ServiceTag.objects.filter(tag_id__in=all_tag_id, tag__is_online=True).values_list('service_id', flat=True)
        if not filter_service_id_list:
            return {
                'size':count,
                'total':0,
                'counts':[0,0,0,0,0],
                'services':[]
            }
        q &= Q(id__in=filter_service_id_list)

    # 获得总数
    def get_counts(query):
        """获取总数的辅助方法"""
        all = Service.objects.filter(query).count()
        is_online_count = Service.objects.filter(query&Q(is_online=True)).count()
        not_online_count = Service.objects.filter(query&Q(is_online=False)).count()

        if is_online == 0:
            # 离线需要升级的
            unupgrade = Service.objects.filter(query&Q(is_online=False, upgrade=False)).count()
            # 离线需要更改类目的
            is_move = Service.objects.filter(query&Q(is_online=False, project_type__is_move=True)).count()

        elif is_online == 1:
            # 在线需要升级的
            unupgrade = Service.objects.filter(query&Q(is_online=True, upgrade=False)).count()
            # 在线需要更改类目的
            is_move = Service.objects.filter(query&Q(is_online=True, project_type__is_move=True)).count()

        else:
            # 全部需要升级的
            unupgrade = Service.objects.filter(query&Q(upgrade=False)).count()
            # 全部需要更改类目的
            is_move = Service.objects.filter(query & Q(project_type__is_move=True)).count()

        return [all, is_online_count, not_online_count, unupgrade, is_move]

    counts = get_counts(q)
    if extra_filter_choice == 1:
        total = counts[-1]
        q &= Q(project_type__is_move=True)
    elif extra_filter_choice == 0:
        total = counts[-2]
        q &= Q(upgrade=False)
    else:
        if is_online == 0:
            total = counts[2]
        elif is_online == 1:
            total = counts[1]
        else:
            total = counts[0]
    if is_online == 0:
        q &= Q(is_online=False)
    elif is_online == 1:
        q &= Q(is_online=True)

    result = {
        'size':count,
        'total':total,
        'counts':counts,
        'services':[]
    }
    services_list = Service.objects.filter(q).order_by('-id')[start_num:start_num+count]
    # TODO 批量获取service_id所对应的tag是可移动
    service_ids = [service.id for service in services_list]
    service_tags_info = ctx.rpc_remote['pims/catalog/services/move_check'](services=service_ids).unwrap()

    def get_sku_info(service_obj):
        sku_list = []
        low_price = 0
        high_price = 0
        # 在线
        service_item_list = ServiceItem.objects.filter(parent_id=0, service=service_obj, is_delete=False)
        # 未升级的sku、非标准化sku id name映射
        sku_2_name = {}
        need_request_sku_name_id = []

        sku_name_pre = u'【{}】'
        project_type = service_obj.project_type
        service_tag_list = ServiceTag.objects.filter(
            Q(service_id=service_obj.id) & ~Q(tag__tag_type=TAG_TYPE.YUNYING))
        if service_tag_list.count() > 1:
            parent_relation = project_type.parents_relations.first()
            if parent_relation:
                sku_name_pre = sku_name_pre.format(parent_relation.parent.name)
            else:
                sku_name_pre = sku_name_pre.format(project_type.name)
        else:
            sku_name_pre = sku_name_pre.format(project_type.name)

        for item in service_item_list:
            sku_price = ServiceItemPrice.objects.filter(service_item_id=item.id, is_enable=True,
                                                        is_default_price=True).first()
            sku_info = {
                'id':item.id,
                'gengmei_price': sku_price.gengmei_price,
                'now_pre_payment': item.get_current_price_info()['pre_payment_price'],
                'discount': sku_price.discount,
                'image_header': item.image_header if item.image_header else service_obj.image_header,
                'is_online': True
            }
            low_price = sku_price.gengmei_price if (sku_price.gengmei_price < low_price or low_price==0) else low_price
            high_price = sku_price.gengmei_price if sku_price.gengmei_price > high_price else high_price

            if service_obj.upgrade:
                if not item.property_id:
                    sku_2_name[item.id] = sku_name_pre + service_obj.short_description
                else:
                    need_request_sku_name_id.append(item.id)
            else:
                opt = ServiceItemKey.objects.filter(serviceitem=item, serviceattroption__is_online=True).first()
                if opt is None:
                    opt_name = ""
                else:
                    opt_name = opt.serviceattroption.name if getattr(opt, "serviceattroption") else ''
                sku_2_name[item.id] = sku_name_pre + opt_name + u'，' + service_obj.short_description
            sku_list.append(sku_info)

        # 不在线
        if service_obj.servicereg.exists():
            r_q_i = Q(service_register=service_obj.servicereg.first(), is_delete=False) & Q(serviceitem__is_delete=True)
            offline_items = ServiceRegisterItem.objects.filter(r_q_i)
            for service_register_item in offline_items:
                item = service_register_item.serviceitem
                sku_price = ServiceItemPrice.objects.filter(service_item_id=item.id, is_enable=True,
                                                            is_default_price=True).first()
                sku_info = {
                    'id': item.id,
                    'gengmei_price': sku_price.gengmei_price,
                    'now_pre_payment': item.get_current_price_info()['pre_payment_price'],
                    'discount': sku_price.discount,
                    'image_header': item.image_header if item.image_header else service_obj.image_header,
                    'is_online': False
                }
                if service_obj.upgrade:
                    if not item.property_id:
                        sku_2_name[item.id] = sku_name_pre + service_obj.short_description
                    else:
                        need_request_sku_name_id.append(item.id)
                else:
                    opt = ServiceItemKey.objects.filter(serviceitem=item, serviceattroption__is_online=True).first()
                    if opt is None:
                        opt_name = ""
                    else:
                        opt_name = opt.serviceattroption.name if getattr(opt, "serviceattroption") else ''
                    sku_2_name[item.id] = sku_name_pre + opt_name + u'，' + service_obj.short_description
                sku_list.append(sku_info)

        if need_request_sku_name_id:
            sku_id_2_namedict = get_rpc_remote_invoker()["pims/product/get_sku_id_to_sku_name_info"](
            sku_ids=need_request_sku_name_id, is_toc=False
            ).unwrap()['result']
            info_logger.info('need_request_sku_name_id-----{}-----{}'.format(need_request_sku_name_id, sku_id_2_namedict))
        for item in sku_list:
            sku_id = item['id']
            if sku_id in need_request_sku_name_id:
                sku_name = sku_id_2_namedict.get(str(sku_id),{}).get('name','')
                if sku_name:
                    sku_name = sku_name_pre + sku_name + u'，' + service_obj.short_description
                item['name'] = sku_name
            else:
                item['name'] = sku_2_name.get(sku_id, '')

        return low_price, high_price, sku_list

    for item in services_list:

        low_price, high_price, sku_list = get_sku_info(item)
        if low_price == high_price:
            price = str(low_price)
        else:
            price='{}~{}'.format(low_price, high_price)
        item_dict = {
            'start_time':item.start_time.strftime("%Y-%m-%d %H:%M:%S") if item.start_time else '',
            'end_time':item.end_time.strftime("%Y-%m-%d %H:%M:%S") if item.end_time else '',
            'id':item.id,
            'register_id': item.servicereg.first().id,
            'service_type':item.service_type,
            'image_header':item.image_header,
            'is_online':item.is_online,
            'service_name':item.name,
            'short_description':item.short_description,
            'is_specialreview':item.servicereg.first().is_specialreview,
            'doctor_name':item.doctor.name if item.doctor else '',
            'is_move': service_tags_info['result'].get(str(item.id), False),
            'upgrade': item.upgrade,
            'price': price,
            'sku_list': sku_list
        }
        if not item.is_online:
            item_dict['offline_reason'] = item.offline_reason if item.offline_reason else '手动下线'

        result['services'].append(item_dict)
    return result


@bind_context('doctor/servicedetail', login_required=True)
def get_service_detail(ctx, service_id, doctor_ids=None):
    doctor = get_doctor_from_context(ctx)
    q = Q(id=service_id)
    if doctor_ids:
        q &= Q(doctor__in=doctor_ids)
    else:
        q &= Q(doctor=doctor)
    try:
        service = Service.objects.get(q)
    except Service.DoesNotExist:
        gen(CODES.SERVICE_NOT_EXSIT)

    def get_register_header():
        item = service.servicereg.first().items.filter(is_delete=False).first()
        if not item:
            return None
        keys = ServiceRegisterItemKey.objects.filter(serviceregisteritem=item)
        return [to_dict(x.serviceregisterattroption.tag_attr) for x in keys]
    # def get_register_header():
    #     item = service.items.filter(is_delete=False).first()
    #     if not item:
    #         return None
    #     keys = ServiceItemKey.objects.filter(serviceitem=item)
    #     return [to_dict(x.serviceattroption.tag_attr) for x in keys]

    def item_info(item):
        item_dict = to_dict(item)
        opt = ServiceItemKey.objects.filter(serviceitem=item)
        item_dict['option_ids'] = [to_dict(x.serviceattroption) for x in opt]
        item_dict['sku_stock'] = item.sku_stock
        item_dict['is_lock'] = item.is_lock

        # item_dict['option_ids'] = []
        # for x in opt:
        #     serviceattroption = to_dict(x)
        #     auditattroptions = AttrOptions.objects.filter(tag_attr=x.serviceattroption.tag_attr).order_by('created_time').first()
        #     if auditattroptions:
        #         serviceattroption['name'] = auditattroptions.name
        #     item_dict['option_ids'].append(serviceattroption)


        info = item.get_current_price_info()
        item_dict['show_dialog'] = False if info['gengmei_price'] == item.gengmei_price else True
        item_dict['now_price'] = info['gengmei_price']
        item_dict['now_pre_payment'] = info['pre_payment_price']
        item_dict['price_start_time'] = get_timestamp_epoch(info['selling_rule']['start_time']) \
            if info.get('selling_rule') else ''
        item_dict['price_end_time'] = get_timestamp_epoch(info['selling_rule']['end_time']) \
            if info.get('selling_rule') else ''
        item_dict['activity_name'] = info['selling_rule']['name'] \
            if info.get('selling_rule') else ''
        item_dict['now_stock'] = info['sale_limit']

        try:
            city_id = item_dict.pop('city')
            if city_id:
                item_dict['city_name'] = item.city.name
                item_dict['city_id'] = item.city_id
        except:
            pass
        sri = ServiceRegisterItem.objects.filter(serviceitem=item).first()
        if not sri:
            return None
        item_price = ServiceItemPrice.objects.filter(service_item=item, is_enable=True).first()
        item_dict['discount'] = item_price.discount
        item_dict['pre_payment_price'] = item_price.pre_payment_price
        item_dict['pre_payment_price_int'] = item_price.pre_payment_price
        item_dict['original_price'] = item_price.original_price
        item_dict['gengmei_price'] = item_price.gengmei_price
        item_dict['cash_back_rate'] = item_price.cash_back_rate
        item_dict['cash_back_fee'] = item_price.cash_back_fee
        item_dict['is_online'] = True
        item_dict['sort'] = sri.sort
        item_dict['stock_add_num'] = 0
        item_dict['serviceitem'] = item.id
        item_dict['id'] = sri.id

        item_dict['sku_description'] = item.sku_description

        #组装类目信息
        category_relation = CommodityCategoryRelation.objects.filter(commodity_id=item.id).first()
        category_property_relations = CommodityCategoryPropertyRelation.objects.filter(commodity_id=item.id)

        item_dict['commodity_category_info'] = category_relation.category_info() if category_relation else []
        item_dict['category_roperty'] = {c_p_r.property_type: c_p_r.property_name for c_p_r in category_property_relations}
        return item_dict

    items_ = []
    for x in service.items.filter(is_delete=False):
        item_info_dict = item_info(x)
        if item_info_dict:
            items_.append(item_info_dict)
    sk_info = service.get_lowest_price_seckill_info()
    # 美购详情显示注册sku 下线、有对应线上sku、未删除的
    def register_item_info(item):
        item_dict = to_dict(item)
        opt = ServiceRegisterItemKey.objects.filter(serviceregisteritem=item)
        item_dict['option_ids'] = [to_dict(x.serviceregisterattroption) for x in opt]
        item_dict['sku_stock'] = item.serviceitem.sku_stock if item.serviceitem else 0
        item_dict['is_lock'] = item.serviceitem.is_lock if item.serviceitem else False

        item_dict['option_ids'] = []
        for x in opt:
            serviceregisterattroption = to_dict(x.serviceregisterattroption)
            auditattroptions = AuditAttrOptions.objects.filter(serviceregisteritem=x.serviceregisteritem).order_by('created_time').first()
            if auditattroptions:
                serviceregisterattroption['name'] = auditattroptions.name
            item_dict['option_ids'].append(serviceregisterattroption)

        if item.serviceitem:
            info = item.serviceitem.get_current_price_info()
            item_dict['show_dialog'] = False if info['gengmei_price'] == item.gengmei_price else True
            item_dict['now_price'] = info['gengmei_price']
            item_dict['now_pre_payment'] = info['pre_payment_price']
            item_dict['price_start_time'] = get_timestamp_epoch(info['selling_rule']['start_time']) \
                if info.get('selling_rule') else ''
            item_dict['price_end_time'] = get_timestamp_epoch(info['selling_rule']['end_time']) \
                if info.get('selling_rule') else ''
            item_dict['activity_name'] = info['selling_rule']['name'] \
                if info.get('selling_rule') else ''
            item_dict['now_stock'] = info['sale_limit']
        else:
            item_dict['show_dialog'] = False
            item_dict['now_price'] = 0
            item_dict['now_pre_payment'] = 0
            item_dict['price_start_time'] = ''
            item_dict['price_end_time'] = ''
            item_dict['activity_name'] = ''
            item_dict['now_stock'] = 0
        try:
            city_id = item_dict.pop('city')
            if city_id:
                item_dict['city_name'] = item.city.name
                item_dict['city_id'] = item.city_id
        except:
            pass
        item_dict['sku_description'] = item.sku_description

        #组装类目信息
        category_relation = CommodityCategoryRelation.objects.filter(commodity_register_id=item.id).first()
        category_property_relations = CommodityCategoryPropertyRelation.objects.filter(commodity_register_id=item.id)

        item_dict['commodity_category_info'] = category_relation.category_info() if category_relation else []
        item_dict['category_roperty'] = {c_p_r.property_type: c_p_r.property_name for c_p_r in category_property_relations}
        item_dict['is_online'] = False
        return item_dict
    r_q_i = Q(service_register=service.servicereg.first(), is_delete=False)&~Q(serviceitem__is_delete=False)
    offline_items = ServiceRegisterItem.objects.filter(r_q_i)
    for s_o_item in offline_items:
        items_.append(register_item_info(s_o_item))
    service_tags_info = ctx.rpc_remote['pims/catalog/services/move_check'](services=[service.id]).unwrap()
    data = {
        'id': service.id,
        'service_name': service.name,
        'short_description': service.short_description,
        'register_id': service.servicereg.first().id,
        'start_time': get_timestamp_epoch(service.start_time),
        'end_time': get_timestamp_epoch(service.end_time),
        'reservation': service.reservation,
        'total_num': service.sell_num_limit_display,  # 废弃, 上线后可删除, @张晓林
        'add_num': service.servicereg.first().add_num,  # 废弃,上线后可删除, @张晓林
        'image_header': service.image_header,
        'photo_details': service.photo_details_doctor,
        'project_type': service.project_type.id,
        'project_name': service.project_type.name,
        'tag_attr': get_tag_template(service.project_type) if service.project_type else {'attr_options': []},
        'seckill_discount': service.servicereg.first().upload_button.discount if service.servicereg.first().upload_button else settings.SERVICE_SETTING['seckill_default_discount'],
        'pre_payment_price': service.pre_payment_price,
        'attr_header': get_register_header(),
        'is_seckill': True if sk_info else False,
        'is_specialreview': service.servicereg.first().is_specialreview,
        'review_status': service.servicereg.first().review_status,
        'turn_down_reason': '',
        'items': items_,
        'record_info': service.servicereg.first().record_info(with_operator_name=False),
        'have_extra_pay': service.have_extra_pay,
        'extra_pay_info': service.extra_pay_info,
        'image_bigpic': service.image_bigpic,
        'supplement_images': service.get_supplement_images(),
        'recommend_services': service.get_recommend_services(),
        'service_type': service.service_type,
        'video_token': get_video_upload_token(),
        'video_pic': service.video.get_video_info()['video_pic'] if getattr(service,'video',None) else '',
        'video_url': service.video.get_video_info()['video_url'] if getattr(service,'video',None) else '',
        'doctor_name': service.doctor.name,
        'doctor_id': service.doctor.id,
        'reject_reason': service.servicereg.first().servicereviewrecord_set.order_by('-created_time')[0].reason if service.servicereg.first().servicereviewrecord_set.order_by('-created_time') else None,
        'is_move': service_tags_info['result'].get(str(service.id), False),
        'upgrade': service.upgrade
    }
    return data


@bind_context('doctor/service/count',login_required=True)
def servicecounts(ctx, doctor_ids=None):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)
    q = (Q(service__is_delete=False) | Q(is_register=True)) & Q(is_draft=False,
                                                                review_status__in=[SERVICE_REVIEW_STATUS.TURN_DOWN,
                                                                                   SERVICE_REVIEW_STATUS.SPECIAL_APPROVAL_TURN_DOWN])
    if doctor_ids:
        q &= Q(doctor__in=doctor_ids)
    else:
        q &= Q(doctor__in=[doctor])
    rejections = ServiceRegister.objects.filter(q).count()
    return rejections

@bind_context('doctor/serviceregister/list', login_required=True)
def get_doctorregister_list(ctx, count=10,
            type=0,
            start_num=0,
            doctor_ids=None,
            service_id=None,
            serviceitem_id=None,
            service_name=None,
            register_id=None):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    q = Q()

    if doctor_ids:
        q &= Q(doctor__in=doctor_ids)
    else:
        q &= Q(doctor__in=[doctor])
        doctor_ids = [doctor]

    # 获取下线驳回的注册id列表
    serviceregister_id_list = ServiceReviewRecord.objects.filter(review_type=SERVICE_REVIEW_TYPE.OFFLINE,
                                       serviceregister__review_status=SERVICE_REVIEW_STATUS.TURN_DOWN,
                                                                 serviceregister__doctor__in=doctor_ids).values_list(
        'serviceregister').annotate(id=Max(F('id')))
    servicegister_max_id_list = ServiceReviewRecord.objects.filter(serviceregister__doctor__in=doctor_ids).values_list('serviceregister').annotate(id=Max(F('id')))
    serviceregister_offline_turn_down_id_list = [serviceregister for serviceregister,_ in set(serviceregister_id_list)&set(servicegister_max_id_list)]

    if service_id:
        q &= Q(service_id=service_id)

    if serviceitem_id:
        q &= Q(service__items__id=serviceitem_id)

    if service_name:
        q &= Q(name__contains=service_name)

    if register_id:
        q &= Q(id=register_id)

    # 获得总数
    def get_counts(query):
        """获取总数的辅助方法"""
        new = ServiceRegister.objects.filter(query & Q(is_register=True)).count()
        old = ServiceRegister.objects.filter(~Q(id__in=serviceregister_offline_turn_down_id_list) & query & Q(is_register=False, service__is_delete=False) & (~Q(
            review_status__in=[SERVICE_REVIEW_STATUS.PASS, SERVICE_REVIEW_STATUS.UNDER_OFFLINE]) | Q(review_status=SERVICE_REVIEW_STATUS.PASS, is_draft=True))).count()
        down_review = ServiceRegister.objects.filter(query & (Q(is_register=False, service__is_delete=False,
                                                               review_status=SERVICE_REVIEW_STATUS.UNDER_OFFLINE) | Q(
            id__in=serviceregister_offline_turn_down_id_list))).count()
        return [new, old, down_review]

    counts = get_counts(q)

    if type == 1:
        q &= ~Q(id__in=serviceregister_offline_turn_down_id_list) & Q(is_register=False, service__is_delete=False) & (~Q(
            review_status__in=[SERVICE_REVIEW_STATUS.PASS, SERVICE_REVIEW_STATUS.UNDER_OFFLINE]) | Q(review_status=SERVICE_REVIEW_STATUS.PASS, is_draft=True))
        total = counts[1]
    elif type == 2:
        q &= (Q(is_register=False, service__is_delete=False, review_status=SERVICE_REVIEW_STATUS.UNDER_OFFLINE)|Q(id__in=serviceregister_offline_turn_down_id_list))
        total = counts[2]
    else:
        q &= Q(is_register=True)
        total = counts[0]

    result = {
        'size': count,
        'counts': counts,
        'total':total,
        'serviceregisters': []
    }

    serviceregister_list = ServiceRegister.objects.filter(q).order_by('-last_submit_time')[start_num:start_num+count]
    # TODO 批量获取service_id所对应的tag是可移动
    service_ids = [service.id for service in serviceregister_list]
    service_tags_info = ctx.rpc_remote['pims/catalog/servicesregister/move_check'](registers=service_ids).unwrap()

    for item in serviceregister_list:
        item_dict = {
            'start_time':item.start_time.strftime("%Y-%m-%d %H:%M:%S") if item.start_time else '',
            'end_time':item.end_time.strftime("%Y-%m-%d %H:%M:%S") if item.end_time else '',
            'id':item.id,
            'is_specialreview':item.is_specialreview,
            'service_type':item.service_type,
            'service_name':item.name,
            'short_description':item.short_description,
            'image_header':item.image_header,
            'service_id':item.service.id if item.service else None,
            'last_submit_time':item.last_submit_time.strftime("%Y-%m-%d %H:%M:%S") if item.last_submit_time else '',
            'is_move': service_tags_info['result'].get(str(item.id), False),
            'upgrade': item.upgrade
        }

        # 新美购审核通过但未包装，此时审核状态为审核通过 应视为审核中
        # 审核中
        if (item.review_status == SERVICE_REVIEW_STATUS.PASS and item.is_register) or item.review_status in [SERVICE_REVIEW_STATUS.UNDER_REVIEW,
                                                                                      SERVICE_REVIEW_STATUS.UNDER_OFFLINE,
                                                                                      SERVICE_REVIEW_STATUS.SPECIAL_UNDER_REVIEW] :
            item_dict['review_status'] = 0
            item_dict['review_message'] = '当前美购正在审核，请稍后查看审核结果'
            result['serviceregisters'].append(item_dict)
            continue

        # 草稿状态
        if item.review_status == SERVICE_REVIEW_STATUS.DRAFT or item.is_draft == 1:
            item_dict['review_status'] = 2
            item_dict['review_message'] = '当前美购为草稿状态，请提交审核后查看审核结果'
            result['serviceregisters'].append(item_dict)
            continue

        # 特批驳回
        if item.review_status == SERVICE_REVIEW_STATUS.SPECIAL_APPROVAL_TURN_DOWN:
            item_dict['review_status'] = 1
            item_dict['review_message'] = '特批驳回原因：' + item.servicereviewrecord_set.last().reason if \
                item.servicereviewrecord_set.last().reason else '无'
            result['serviceregisters'].append(item_dict)
            continue

        # 编辑驳回、下线驳回
        if item.review_status == SERVICE_REVIEW_STATUS.TURN_DOWN:
            # 判断是否下线驳回
            servicereviewrecord = item.servicereviewrecord_set.last()
            if servicereviewrecord and servicereviewrecord.review_type == SERVICE_REVIEW_TYPE.OFFLINE:
                item_dict['review_status'] = 3
                item_dict['review_message'] = '下线驳回原因：' + servicereviewrecord.reason
            elif servicereviewrecord:
                item_dict['review_status'] = 1
                item_dict['review_message'] = '驳回原因：' + servicereviewrecord.reason
            else:
                item_dict['review_status'] = 1
                item_dict['review_message'] = '驳回原因：' + '无'
            result['serviceregisters'].append(item_dict)

    return result


@bind_context('doctor/servicereview/option', login_required=True)
@transaction.atomic
def serviceregister_option(ctx, id, type, doctor_ids=None):
    doctor = get_doctor_from_context(ctx)
    if not doctor:
        return gen(CODES.DOCTOR_NOT_FOUND)

    doctor_list = [doctor]

    if doctor_ids:
        doctor_list = doctor_ids

    serviceregister = ServiceRegister.objects.select_for_update().get(id=id, doctor__in=doctor_list)
    if not serviceregister:
        return gen(CODES.SERVICE_NOT_EXSIT)

    # 编辑美购时候已经在数据库层面加锁了，所以这块就不用了
    # if getattr(serviceregister.service, 'is_lock', False):
    #     raise gen(CODES.SERVICE_STATUS_ERROR)

    if (serviceregister.is_register and serviceregister.service_id) or (serviceregister.review_status == SERVICE_REVIEW_STATUS.PASS and not serviceregister.is_draft):
        # 走到包装的美购、审核成功的 不能进行撤回、取消操作
        return gen(CODES.SERVICE_STATUS_ERROR)

    if type == 0:
        # 取消
        if serviceregister.is_register:
            # 删除注册数据
            serviceregister.delete()
        else:
            if serviceregister.upgrade:
                q = Q(service=serviceregister.service) & (~Q(tag__tag_type=TAG_TYPE.YUNYING))
                ServiceRegisterTag.objects.filter(serviceregister_id=serviceregister.id).delete()
                service_tags = ServiceTag.objects.filter(q)
                for service_tag in service_tags:
                    ServiceRegisterTag.objects.create(serviceregister_id=serviceregister.id,
                                                      tag_id=service_tag.tag_id)
            # 将线上数据覆盖注册数据，状态恢复为审核成功 SERVICE_REVIEW_STATUS.PASS 非草稿 is_draft: false
            serviceregister.project_type = serviceregister.service.project_type
            serviceregister.short_description = serviceregister.service.short_description
            serviceregister.start_time = serviceregister.service.start_time
            serviceregister.end_time = serviceregister.service.end_time
            serviceregister.reservation = serviceregister.service.reservation
            serviceregister.image_header = serviceregister.service.image_header
            serviceregister.photo_details = serviceregister.service.photo_details_doctor
            serviceregister.image_bigpic = serviceregister.service.image_bigpic
            serviceregister.update_supplement_images(serviceregister.service.get_supplement_images())
            serviceregister.update_supplement_images_order(serviceregister.service.get_supplement_images())
            serviceregister.have_extra_pay = serviceregister.service.have_extra_pay
            serviceregister.extra_pay_info = serviceregister.service.extra_pay_info
            serviceregister.service_type = serviceregister.service.service_type
            recommend_service_ids = [item.get('id') for item in serviceregister.service.get_recommend_services()]
            serviceregister.update_recommend_services(recommend_service_ids)
            serviceregister.merchant_id = serviceregister.service.merchant_id
            serviceregister.doctor_id = serviceregister.service.doctor_id
            serviceregister.name = serviceregister.service.name
            serviceregister.review_status = SERVICE_REVIEW_STATUS.PASS
            serviceregister.is_draft = False
            serviceregister.upgrade = serviceregister.service.upgrade
            serviceregister.save()

            old_video = getattr(serviceregister.service, 'video', None)
            new_video = getattr(serviceregister, 'video', None)

            if new_video:
                if old_video:
                    new_video.video_url = old_video.video_url
                    new_video.video_pic = old_video.video_pic
                    new_video.persistentId = old_video.persistentId
                    new_video.persistent_status = old_video.persistent_status
                    new_video.water_url = old_video.water_url
                    new_video.save()
                else:
                    new_video.delete()
            else:
                if old_video:
                    ServiceRegisterVideo.objects.create(
                        serviceregister=serviceregister,
                        video_url=old_video.video_url,
                        video_pic=old_video.video_pic,
                        persistentId=old_video.persistentId,
                        persistent_status=old_video.persistent_status,
                        water_url=old_video.water_url
                    )

            # 线上美购项目
            items = ServiceItem.objects.filter(parent_id=0, service_id=serviceregister.service.id,is_delete=False)
            # 编辑后删除增加的美购项目
            # q_i = Q(service_register=serviceregister)
            # q_i &= Q(serviceitem=None)
            # ServiceRegisterItem.objects.filter(q_i).update(is_delete=True)
            serviceregister_items = ServiceRegisterItem.objects.filter(serviceitem__in=items)
            for item in serviceregister_items:
                serviceitemprice = ServiceItemPrice.objects.filter(service_item=item.serviceitem)[0]
                item.key = item.serviceitem.key
                item.discount = serviceitemprice.discount
                item.pre_payment_price_int = serviceitemprice.pre_payment_price
                item.original_price = serviceitemprice.original_price
                item.gengmei_price = serviceitemprice.gengmei_price
                item.cash_back_rate = serviceitemprice.cash_back_rate
                item.cash_back_fee = serviceitemprice.cash_back_fee
                item.is_online = True
                item.is_delete = False
                item.sort = item.serviceitem.sort
                item.stock_add_num = 0
                item.city = item.serviceitem.city
                item.sku_description = item.serviceitem.sku_description
                item.property_id = item.serviceitem.property_id
                item.image_header = item.serviceitem.image_header
                item.save()
    elif type == 1:
        # 撤回 将状态置为草稿 is_draft: true SERVICE_REVIEW_STATUS.PASS
        if serviceregister.review_status in [SERVICE_REVIEW_STATUS.UNDER_OFFLINE,SERVICE_REVIEW_STATUS.TURN_DOWN,
                                             SERVICE_REVIEW_STATUS.SPECIAL_APPROVAL_TURN_DOWN,SERVICE_REVIEW_STATUS.DRAFT] or serviceregister.is_draft:
            # 驳回、特批驳回、草稿 不能撤回
            return gen(CODES.SERVICE_STATUS_ERROR)

        if serviceregister.review_status == SERVICE_REVIEW_STATUS.UNDER_REVIEW:
            # 通过特批审核的 不能撤回
            if serviceregister.is_specialreview:
                return gen(CODES.SERVICE_STATUS_ERROR)

        serviceregister.is_draft = True
        if serviceregister.is_register:
            serviceregister.review_status = SERVICE_REVIEW_STATUS.DRAFT
        else:
            serviceregister.review_status = SERVICE_REVIEW_STATUS.PASS
        serviceregister.save()
    return
