# -*- coding:utf-8 -*-
import datetime
import json
import math
from gm_types.gaia import SERVICE_REVIEW_STATUS, SERVICE_REVIEW_TYPE, TREATMENT_MEANS_CHOICES
from gm_types.gaia import OPERTOR_REVIEW_TYPE, DOCTOR_USE_COUPON_TYPE

from api.models import (
    ServiceRegister, ServiceRegisterItem, ServiceTag, ServiceRegisterItemKey, ServiceReviewRecord,
    ServiceItemKey, TagWiki, ServiceVideo, Coupon, MerchantRelevance, Merchant, AuditAttrOptions
)
from api.models import Service, ServiceItem, CouponSKURestrict, User
from api.models.types import DOCTOR_TYPE, SERVICE_FLAG
from rpc.tool.error_code import gen, CODES
from rpc.tool.log_tool import exception_logger
from api.tasks.service_task import refresh_service_cache_info
from django.core.management import BaseCommand
from hera.views.serviceregister import push_service_detail


def review_result(serviceregister_id, is_pass, is_operator_pass=False, reason=None):
    """
    审核申请
    :param ctx:
    :param reason: 拒绝原因
    :param serviceregister_id: 美购申请ID
    :param is_pass: 是否通过审核
    modify by oldman 2016-12-26 （sku一期优化）
    """

    reviewrecord = ServiceReviewRecord.objects.filter(
        serviceregister__id=serviceregister_id).order_by('-created_time')[0]
    serviceregister = ServiceRegister.objects.get(pk=serviceregister_id)
    if getattr(serviceregister.service, 'is_lock', False):
        raise gen(CODES.SERVICE_STATUS_ERROR)
    if serviceregister.review_status != SERVICE_REVIEW_STATUS.UNDER_REVIEW:
        raise gen(CODES.OPERATION_NOT_SUPPORTED)
    if is_pass and is_operator_pass:
        old_count = Service.any_can_sell_items_has_stock(
            serviceregister.service_id) if serviceregister.service_id else False
        reviewrecord.now_review_status = SERVICE_REVIEW_STATUS.PASS
        serviceregister.review_status = SERVICE_REVIEW_STATUS.PASS
        serviceregister.operator_review_type = OPERTOR_REVIEW_TYPE.NO_REVIEW
        if serviceregister.service:
            serviceregister.service.project_type = serviceregister.project_type
            serviceregister.service.short_description = serviceregister.short_description
            serviceregister.service.start_time = serviceregister.start_time
            serviceregister.service.end_time = serviceregister.end_time
            serviceregister.service.reservation = serviceregister.reservation
            # 2017-3-16 库存改为在ServiceRegisterItem中，此字段不再维护
            # serviceregister.service.total_num = (serviceregister.total_num + serviceregister.add_num)
            serviceregister.service.image_header = serviceregister.image_header
            serviceregister.service.is_online = True
            serviceregister.service.photo_details_doctor = serviceregister.photo_details
            serviceregister.service.sell_num_limit = serviceregister.service.real_stock
            # 美购改版 2017-03-31
            serviceregister.service.image_bigpic = serviceregister.image_bigpic
            serviceregister.service.update_supplement_images(serviceregister.get_supplement_images())
            serviceregister.service.update_supplement_images_order(serviceregister.get_supplement_images())
            serviceregister.service.have_extra_pay = serviceregister.have_extra_pay
            serviceregister.service.extra_pay_info = serviceregister.extra_pay_info
            serviceregister.service.service_type = serviceregister.service_type
            recommend_service_ids = [item.get('id') for item in serviceregister.get_recommend_services()]
            serviceregister.service.update_recommend_services(recommend_service_ids)
            serviceregister.service.merchant_id = serviceregister.merchant_id
            serviceregister.service.doctor_id = serviceregister.doctor_id
            serviceregister.service.name = serviceregister.name
            serviceregister.service.save()
            old_video = getattr(serviceregister.service, 'video', None)
            new_video = getattr(serviceregister, 'video', None)
            if old_video:
                if new_video:
                    old_video.video_url = new_video.video_url
                    old_video.video_pic = new_video.video_pic
                    old_video.persistentId = new_video.persistentId
                    old_video.persistent_status = new_video.persistent_status
                    old_video.water_url = new_video.water_url
                    old_video.save()
                else:
                    old_video.delete()
            else:
                if new_video:
                    ServiceVideo.objects.create(
                        service_id=serviceregister.service.id,
                        video_url=new_video.video_url,
                        video_pic=new_video.video_pic,
                        persistentId=new_video.persistentId,
                        persistent_status=new_video.persistent_status,
                        water_url=new_video.water_url
                    )
        else:
            service_flag = SERVICE_FLAG.DOCTOR if serviceregister.doctor.doctor_type == DOCTOR_TYPE.DOCTOR else \
                SERVICE_FLAG.HOSPITAL  # 美购标记
            is_operation = False  # 是否是手术类
            itemwiki = TagWiki.objects.filter(tag_id=serviceregister.project_type.id)
            wiki = None
            if len(itemwiki) > 0:
                is_operation = True if (
                        itemwiki[0].itemwiki and itemwiki[
                    0].itemwiki.treatment_means == TREATMENT_MEANS_CHOICES.OPERATE) else False
                wiki = itemwiki[0].itemwiki
            serviceregister.service = Service.objects.create(
                doctor=serviceregister.doctor,
                name=serviceregister.name,
                short_description=serviceregister.short_description,
                start_time=serviceregister.start_time,
                end_time=serviceregister.end_time,
                project_type=serviceregister.project_type,
                reservation=serviceregister.reservation,
                image_header=serviceregister.image_header,
                is_stage=serviceregister.is_stage,
                exchange_points_ceiling=0,
                is_online=False,
                service_flag=service_flag,
                service_type=serviceregister.service_type,
                is_operation=is_operation,
                wiki=wiki,
                photo_details_doctor=serviceregister.photo_details,
                valid_duration=180 if is_operation else 90,
                image_bigpic=serviceregister.image_bigpic,
                extra_pay_info=serviceregister.extra_pay_info,
                have_extra_pay=serviceregister.have_extra_pay,
                merchant_id=serviceregister.merchant_id
            )
            video = getattr(serviceregister, 'video', None)
            if video:
                ServiceVideo.objects.create(
                    service_id=serviceregister.service.id,
                    video_url=video.video_url,
                    video_pic=video.video_pic,
                    persistentId=video.persistentId,
                    persistent_status=video.persistent_status,
                    water_url=video.water_url
                )
            ServiceTag.objects.create(service_id=serviceregister.service.id,
                                      tag_id=serviceregister.project_type.id)
            serviceregister.service.update_supplement_images(serviceregister.get_supplement_images())
            serviceregister.service.update_supplement_images_order(serviceregister.get_supplement_images())
            recommend_service_ids = [item.get('id') for item in serviceregister.get_recommend_services()]
            serviceregister.service.update_recommend_services(recommend_service_ids)
            if not serviceregister.upload_button:  # 判断是否是多属性(在创建的时间判断的)
                serviceregister.service.is_multiattribute = True
        # 2017-3-16 库存改为在ServiceRegisterItem中，此字段不再维护
        # serviceregister.total_num += serviceregister.add_num  # 更新美购注册总数量和数量
        items = ServiceRegisterItem.objects.filter(service_register__id=serviceregister_id, is_delete=False,
                                                   is_online=True)

        ServiceItem.objects.filter(parent_id=0, service_id=serviceregister.service.id).update(
            is_delete=True)  # 原来所有的多属性置为软删除

        for item in items:
            if item.serviceitem:  # 修改多属性
                #  获取默认价格信息 modif by oldman 2016-12-26
                price_info = item.serviceitem.get_default_price_info()
                price_info_id = price_info.get('id')

                price_params = {
                    'price_id': price_info_id,
                    'discount': item.discount,
                    'pre_payment_price': item.pre_payment_price_int,
                    'original_price': item.original_price,
                    'cash_back_rate': item.cash_back_rate,
                    'cash_back_fee': math.ceil((item.cash_back_rate * item.gengmei_price) / 100.00),
                    'is_enable': True,
                }

                if price_info.get('gengmei_price') != item.gengmei_price:
                    price_params['self_support_discount'] = int(item.gengmei_price * 0.4)
                    price_params['gengmei_price'] = item.gengmei_price

                try:
                    item.serviceitem.update_price(**price_params)
                except Exception as e:
                    exception_logger.error('item-%s-%s' % (json.dumps(price_params), e.message))
                item.serviceitem.key = item.key
                item.total_num = item.serviceitem.total_num + item.stock_add_num
                item.serviceitem.is_delete = False
                item.serviceitem.serviceregisteritem_id = item.id
                item.serviceitem.service_id = serviceregister.service.id
                item.serviceitem.city_id = item.city_id
                item.serviceitem.sku_description = item.sku_description
                item.serviceitem.save()

                # 设置库存 sku_stock,因为相关实现使用了update，所以必须save item()之后再处理
                if item.stock_add_num > 0:
                    item.serviceitem.increase_stock(item.stock_add_num)
                elif item.stock_add_num < 0:
                    item.serviceitem.decrease_stock((0 - item.stock_add_num))

                # 无申请id的活动价同步更新
                activity_ids = item.serviceitem.specialitem_set.filter(doctorseckillapply__isnull=True).values_list(
                    'special_id', flat=True)
                price_ids = item.serviceitem.serviceitemprice_set.filter(
                    selling_rule__activity_id__in=activity_ids).values_list('id', flat=True)
                for price_id in price_ids:
                    price_params['price_id'] = price_id
                    try:
                        item.serviceitem.update_price(**price_params)
                    except Exception as e:
                        exception_logger.error('price-%s-%s' % (json.dumps(price_params), e.message))

            else:  # 添加多属性
                serviceitem = ServiceItem.objects.create(
                    service_id=serviceregister.service.id,
                    key=item.key,
                    is_delete=False,
                    city_id=item.city_id,
                    sku_description=item.sku_description,
                )
                serviceitem.total_num += item.stock_add_num
                serviceitem.save()
                # todo 设置库存 total_num sku_stock
                if item.stock_add_num > 0:
                    serviceitem.increase_stock(item.stock_add_num)
                elif item.stock_add_num < 0:
                    serviceitem.decrease_stock((0 - item.stock_add_num))
                serviceitem.create_price(
                    sale_limit=0,
                    is_default_price=True,
                    selling_rule_id=None,
                    discount=item.discount,
                    pre_payment_price=item.pre_payment_price_int,
                    original_price=item.original_price,
                    gengmei_price=item.gengmei_price,
                    cash_back_rate=item.cash_back_rate,
                    cash_back_fee=math.ceil((item.cash_back_rate * item.gengmei_price) / 100.00),
                    self_support_discount=int(item.gengmei_price * 0.4),
                    single_user_buy_limit=0
                )
                item.serviceitem = serviceitem
                serviceregisterkeys = ServiceRegisterItemKey.objects.filter(serviceregisteritem__id=item.id)
                for serviceregisterkey in serviceregisterkeys:
                    ServiceItemKey.objects.create(
                        serviceitem=serviceitem,
                        serviceattroption=serviceregisterkey.serviceregisterattroption
                    )

                # 全店通用或者医生通用券则创建相应的美券规则
                # 先看看当前医生有没有全店通用券
                whole_coupon_ids, doctor_coupons_ids = [], []
                mer = MerchantRelevance.objects.filter(doctor_id=serviceregister.service.doctor_id).first()
                if mer:
                    m = Merchant.objects.get(id=mer.merchant_id)
                    whole_coupon_ids = list(Coupon.objects.filter(
                        doctor_id=m.doctor_id,
                        doctor_coupon_use_type=DOCTOR_USE_COUPON_TYPE.FULL_PLATFORM_GENERAL
                    ).values_list('id', flat=True))
                # 再处理医生通用
                if serviceregister.service.doctor_id:
                    doctor_coupons_ids = list(Coupon.objects.filter(
                        doctor_id=serviceregister.service.doctor_id,
                        doctor_coupon_use_type=DOCTOR_USE_COUPON_TYPE.DOCTOR_GENERAL
                    ).values_list('id', flat=True))

                coupons = list(set(whole_coupon_ids) | set(doctor_coupons_ids))
                CouponSKURestrict.objects.bulk_create(
                    [CouponSKURestrict(coupon_id=coupon_id, sku_id=serviceitem.id) for coupon_id in coupons]
                )
            item.stock_add_num = 0
            item.save()
            # 修改项目名字
            auditattroptions = AuditAttrOptions.objects.filter(serviceregisteritem=item, is_delete=False).first()
            if auditattroptions:
                itemkey = ServiceRegisterItemKey.objects.get(serviceregisteritem=item)
                itemkey.serviceregisterattroption.name = auditattroptions.name
                itemkey.serviceregisterattroption.save()
                auditattroptions.delete()

        new_count = Service.any_can_sell_items_has_stock(serviceregister.service_id)
        if not old_count and new_count:
            push_service_detail(serviceregister.service)
    elif is_operator_pass and not is_pass:  # 运营通过
        serviceregister.operator_review_type = OPERTOR_REVIEW_TYPE.REVIEW_PASS
    else:
        serviceregister.review_status = SERVICE_REVIEW_STATUS.TURN_DOWN
        serviceregister.operator_review_type = OPERTOR_REVIEW_TYPE.NO_REVIEW
        reviewrecord.now_review_status = SERVICE_REVIEW_STATUS.SPECIAL_APPROVAL_TURN_DOWN if \
            reviewrecord.review_type == SERVICE_REVIEW_TYPE.SPECIAL else SERVICE_REVIEW_STATUS.TURN_DOWN
        reviewrecord.reason = reason
    serviceregister.last_review_time = datetime.datetime.now()
    serviceregister.save()

    if serviceregister.service:
        serviceregister.service.save()
        refresh_service_cache_info.delay(service_ids=[serviceregister.service.id])

    # 所长大人
    suozhang = User.objects.get(id=22)
    # reviewrecord.operator = get_user_from_context(ctx).person
    reviewrecord.operator = suozhang.person
    reviewrecord.audit_time = datetime.datetime.now()
    reviewrecord.save()
    # doctor 设置自营医生
    if serviceregister.service:
        serviceregister.service.smart_self_support()


class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('register_id', type=str)

    def handle(self, *args, **options):
        if options['register_id'] is None:
            return
        register_id = int(options['register_id'])
        review_result(register_id, True, True, '')
