# -*- coding: UTF-8 -*-
from __future__ import absolute_import

import math

from django.db.models import Q

from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery

from rpc.all import get_rpc_remote_invoker
from api.models import ServiceItem, Order, ServiceItemKey
from hera.utils import get_mail_instance

mail_template = u"""
{name}：


更美平台在价格排查中发现{service_id} {service}美购存在价格劣势，

现平台决定直接将{service}美购的价格从{gengmei_price_old}降至{gengmei_price_new}，

请在第一时间转告机构，同时告知机构不要在竞对活动未结束之前擅自调价，否则会做降流处理。
竞对活动结束后，机构可以将美购改回原价。如因人员审核错误造成的价格劣势，机构可以在收到通知后的24小时内申诉。
申诉请点击如下链接：http://cn.mikecrm.com/RMraFb7，填写美购名称、项目名称等相关信息，
并上传该美购在更美及竞品平台的APP截图后点击立即申诉。
"""


class ServiceItemDB(DataBuilder):
    def getval_name(self, obj):
        serviceitem = ServiceItemKey.objects.filter(serviceitem_id=obj.id).last()
        return serviceitem.serviceattroption.name

    def getval_order_num(self, obj):
        orders = Order.objects.using(self.using).filter(service_item_key=obj.key)
        if getattr(self, 'pay_time_query', None):
            orders = orders.filter(self.pay_time_query)
        else:
            orders = orders.filter(pay_time__isnull=False)
        return orders.count()

    def getval_insurance_num(self, obj):
        orders = Order.objects.using(self.using).filter(service_item_key=obj.key)
        if getattr(self, 'pay_time_query', None):
            orders = orders.filter(self.pay_time_query)
        else:
            orders = orders.filter(pay_time__isnull=False)
        order_ids = list(orders.values_list('id', flat=True))
        if order_ids:
            return get_rpc_remote_invoker()['plutus/insurance/order/count'](
                order_ids=order_ids
            ).unwrap()
        else:
            return 0

    def getval_original_price(self, item):
        info = item.get_default_price_info()
        return info['original_price']

    def getval_pre_payment_price(self, item):
        info = item.get_default_price_info()
        return info['pre_payment_price']

    def getval_gengmei_price(self, item):
        info = item.get_default_price_info()
        return info['gengmei_price']

    def getval_hospital_payment(self, item):
        info = item.get_default_price_info()
        return info['gengmei_price'] - info['pre_payment_price']

    def getval_cash_back_rate(self, item):
        info = item.get_default_price_info()
        return info['cash_back_rate']

    def getval_cash_back_fee(self, item):
        info = item.get_default_price_info()
        return info['cash_back_fee']

    def getval_discount(self, item):
        info = item.get_default_price_info()
        return info['discount']

    def getval_discount_rate(self, item):
        info = item.get_default_price_info()
        return int(info['discount'] / (info['gengmei_price'] * 1.0) * 100)

    def getval_self_support_discount(self, item):
        info = item.get_default_price_info()
        return info['self_support_discount']

    def getval_self_support_discount_rate(self, item):
        info = item.get_default_price_info()
        return int(info['self_support_discount'] / (info['gengmei_price'] * 1.0) * 100)

    def getval_gengmei_price(self, item):
        info = item.get_default_price_info()
        return info['gengmei_price']


@DB
class ServiceItemDQ(DataSQLQuery):
    model = ServiceItem
    data_model = ServiceItemDB

    def filter_pay_time(self, srch_key, srch_val, regex=False):
        pay_time_query = self._qry_time_range(srch_key, srch_val, regex)
        self.kwargs['pay_time_query'] = pay_time_query
        return Q()

    def filter_id(self, srch_key, srch_val, regex=False):
        return Q(id=srch_val) & Q(parent_id=0)

    def update(self, updates, **kwargs):
        service_item = self.model.objects.get(**kwargs)
        price = service_item.get_default_price_info()
        gengmei_price_new = 1.0 * int(updates['gengmei_price'])
        gengmei_price_old = 1.0 * price['gengmei_price']
        self_discount_rate = price['self_support_discount'] / gengmei_price_old
        cash_back_fee = math.ceil(gengmei_price_new * price['cash_back_rate'] / 100)
        if gengmei_price_new > 500:
            pre_rate = price['pre_payment_price'] / gengmei_price_old
            discount_rate = price['discount'] / gengmei_price_old
            pre_payment_price = int(gengmei_price_new * pre_rate)
            discount = int(gengmei_price_new * discount_rate)
        else:
            from doctor.tool.service_tool import count_pre_payment
            result = count_pre_payment(int(updates['gengmei_price']))
            pre_rate = result['pre_payment_price']
            pre_payment_price = result['pre_payment_price_int']
            discount = result['discount']
        service_item.update_price(
            price_id=price['id'],
            gengmei_price=gengmei_price_new,
            pre_payment_price=pre_payment_price,
            discount=discount,
            cash_back_fee=cash_back_fee,
            self_support_discount=int(gengmei_price_new * self_discount_rate)
        )
        register_item = service_item.serviceregisteritem_set.last()
        if register_item:
            register_item.gengmei_price = gengmei_price_new
            register_item.pre_payment_price = pre_rate * 100
            register_item.pre_payment_price_int = pre_payment_price
            register_item.cash_back_fee = cash_back_fee
            register_item.discount = discount
            register_item.save()
        partner = service_item.service.doctor.business_partener
        if partner:
            title = '美购价更改通知'
            body = mail_template.format(**{
                'name': partner.username,
                'service': service_item.service.name,
                'service_id': service_item.service_id,
                'gengmei_price_new': gengmei_price_new,
                'gengmei_price_old': gengmei_price_old
            })
            get_mail_instance(title, body, [partner.email]).send()
        
        # 多买新增sku 同步父级sku数据
        service_item.update_children()
        return
