# coding=utf-8
from __future__ import unicode_literals, absolute_import, print_function
import string
import random

from django.db import models

from gm_types.gaia import FENXIAO_PAY_RULE
from rpc.tool.error_code import CODES, gen
from api.models import Order
from api.models import Person


class FenxiaoCompany(models.Model):

    class Meta:
        verbose_name = u'网红公司'
        verbose_name_plural = u'网红公司'
        db_table = 'api_fenxiaocompany'
        app_label = 'api'

    created_at = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True, null=True)
    is_online = models.BooleanField(null=False, default=True, verbose_name=u'是否上线')
    name = models.CharField(max_length=200, null=False, verbose_name=u'公司名称', unique=True)
    back_rate = models.IntegerField(verbose_name=u'返佣比例')
    pay_type = models.CharField(max_length=4, null=False, verbose_name=u'返佣比例计算方式', choices=FENXIAO_PAY_RULE)
    # 返佣限制天数和返佣限制订单数 默认为None 为None时即表示没有限制
    back_month_limit = models.IntegerField(verbose_name=u'返佣限制天数', null=True, default=None)
    back_order_limit = models.IntegerField(verbose_name=u'返佣限制订单数', null=True, default=None)


class FenxiaoWanghong(models.Model):

    class Meta:
        verbose_name = u'网红'
        verbose_name_plural = u'网红'
        db_table = 'api_fenxiaowanghong'
        app_label = 'api'

    code = models.CharField(max_length=8, null=False, verbose_name=u'网红id(字母+数字,区分大小写)', unique=True)
    created_at = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    is_online = models.BooleanField(null=False, default=True, verbose_name=u'是否上线')
    company = models.ForeignKey(FenxiaoCompany, verbose_name=u'所属网红公司', related_name='wanghongs')

    @classmethod
    def generate_code(cls, size=8):
        chars = string.ascii_letters + string.digits
        return ''.join(random.choice(chars) for _ in range(size))


class FenxiaoPersonWanghong(models.Model):

    class Meta:
        verbose_name = u'通过网红注册的用户与网红关联的中间表'
        verbose_name_plural = u'通过网红注册的用户与网红关联的中间表'
        db_table = 'api_fenxiaopersonwanghong'
        app_label = 'api'

    created_at = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    person = models.OneToOneField(Person, verbose_name=u'注册用户', related_name='fenxiao')
    wanghong = models.ForeignKey(FenxiaoWanghong, verbose_name=u'所属网红')

    @classmethod
    def create(cls, person_id, wanghong_code):
        try:
            wanghong = FenxiaoWanghong.objects.get(code=wanghong_code)
            person = Person.objects.get(pk=person_id)
        except FenxiaoWanghong.DoesNotExist:
            return gen(CODES.FENXIAO_WANGHONG_NOT_EXIST)
        except Person.DoesNotExist:
            return gen(CODES.USER_NOT_FOUND)
        finally:
            cls.objects.create(person=person, wanghong=wanghong)


class FenxiaoOrderWanghong(models.Model):

    class Meta:
        verbose_name = u'网红和订单关联中间表'
        verbose_name_plural = u'网红和订单关联中间表'
        db_table = 'api_fenxiaoorderwanghong'
        app_label = 'api'

    order = models.OneToOneField(Order, verbose_name=u'所属订单')
    person = models.ForeignKey(Person, verbose_name=u'下单用户(由网红引入的用户)', related_name='fenxiao_order')
    wanghong = models.ForeignKey(FenxiaoWanghong, verbose_name=u'所属网红')
    back_rate = models.IntegerField(verbose_name=u'返佣比例')
    money_received_cent = models.IntegerField(verbose_name=u'佣金(单位是分)', default=0)
    pay_type = models.CharField(max_length=4, null=False, verbose_name=u'返佣比例计算方式', choices=FENXIAO_PAY_RULE)

    @classmethod
    def create(cls, order):
        p = order.user.person

        if p.is_from_wanghong:
            wh = p.fenxiao.wanghong
            company = p.fenxiao.wanghong.company
            pay_type = company.pay_type
            back_rate = company.back_rate
            calculate_func = cls.pay_type_func_map().get(pay_type)
            money_received_cent = calculate_func(order, back_rate)
            kwargs = {
                'order': order,
                'person': p,
                'wanghong': wh,
                'back_rate': back_rate,
                'money_received_cent': money_received_cent,
                'pay_type': pay_type,
            }
            cls.objects.create(**kwargs)

    @classmethod
    def pay_type_func_map(cls):

        def gengmei_price(order, rate):
            return order.order_price('gengmei_price') * rate  # 元转分  p * rate / 100 * 100的简化形式

        def gengmei_price_minus_deduction(order, rate):
            p = order.order_price('gengmei_price') - order.deduction()
            return p * rate     # 元转分  p * rate / 100 * 100的简化形式

        map = {
            FENXIAO_PAY_RULE.GENGMEI_PRICE: gengmei_price,
            FENXIAO_PAY_RULE.GENGMEI_PRICE_MINUS_DEDUCTION: gengmei_price_minus_deduction,
        }
        return map
