#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "chenwei"
# Date: 2018/6/22

from django.db import models
from django.db.models import ManyToManyField, Q
from gm_types.gaia import (
    TRANSFER_SOURCE, USER_NTENTION, USER_POTENTIAL, OPERATION_ACTION,
    SINGLE_TYPE, BDTRANSFER_OBJECT_STATE, USER_GENDER
)
from gm_types.doctor import BDTRANSFER_APPLY_STATUS, BDTRANSFER_PIC_TYPE
from gm_upload import ImgUrlField, IMG_TYPE

from hippo.models import Doctor
from rpc.tool.error_code import CODES, gen
from .budan import BuDan
from .city import City
from .tag import Tag
from .user import User


class BDTransfer(models.Model):
    class Meta:
        db_table = 'api_bdtransfer'
        app_label = 'api'
        verbose_name = '商务转诊记录表'
    user = models.CharField(verbose_name='姓名', max_length=32, default='')
    user_phone = models.CharField(verbose_name=u'用户手机号', default='', max_length=20)
    qq = models.CharField(verbose_name=u'QQ号', max_length=16, default='')
    wechat = models.CharField(verbose_name=u'微信号', max_length=32, default='')
    weibo = models.CharField(verbose_name=u'微博', max_length=32, default='')
    willing_cities = ManyToManyField(City, verbose_name=u"意向城市")
    clue_tags = ManyToManyField('BDTransferClueTag', verbose_name=u"线索标签")
    consume_potential_min = models.IntegerField(verbose_name=u'消费潜力/心里意向(最小值)', default=0)
    consume_potential_max = models.IntegerField(verbose_name=u'消费潜力/心里意向(最大值)', default=0)
    intention = models.SmallIntegerField(
        verbose_name=u'公立/私营', choices=USER_NTENTION, default=USER_NTENTION.UNDEFINED
    )
    source = models.SmallIntegerField(verbose_name=u'来源', choices=TRANSFER_SOURCE, default=TRANSFER_SOURCE.OTHERS)
    potential_assess = models.SmallIntegerField(
        verbose_name=u'潜力评估', choices=USER_POTENTIAL, default=USER_POTENTIAL.GENERAL_CUSTOMER
    )
    creator = models.CharField(verbose_name=u'创建人', max_length=32, default='')
    create_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)
    assigner = models.CharField(verbose_name=u'分配人', max_length=32, default='')
    last_follow_time = models.DateTimeField(verbose_name=u'最后联系时间', null=True)
    is_assign = models.BooleanField(verbose_name=u'是否分配', default=False)
    assigned_time = models.DateTimeField(verbose_name=u'分配时间', null=True)

    # 7740添加 和呼叫中心打通
    note = models.TextField(verbose_name=u'备注', null=True)
    wechat_nickname = models.CharField(verbose_name=u'微信名称', max_length=200, null=True)
    person_id = models.CharField(verbose_name=u'平台账号(用户相关)', max_length=50, null=True)
    object_state = models.SmallIntegerField(verbose_name=u'对象状态(用户相关)', choices=BDTRANSFER_OBJECT_STATE,
                                            default=BDTRANSFER_OBJECT_STATE.NOT_THROUGH_INFOMATION)
    current_follow_up_consultant = models.ForeignKey(User, verbose_name=u'当前跟进顾问', null=True)
    email = models.CharField(verbose_name=u'邮箱', default='', max_length=128)
    gender = models.SmallIntegerField(verbose_name=u'性别', choices=USER_GENDER, default=USER_GENDER.UNKNOWN)
    call_phone = models.CharField(verbose_name=u'联系电话', default='', max_length=128)
    user_province = models.CharField(verbose_name=u'用户所在省份', default='', max_length=128)
    user_city = models.CharField(verbose_name=u'用户所在城市', default='', max_length=128)
    comments = models.TextField(verbose_name=u'备注', default='')
    is_back = models.BooleanField(verbose_name=u'是否回抛', default=False)
    pooled_time = models.DateTimeField(verbose_name=u'入池时间', null=True)
    age = models.IntegerField(verbose_name='用户年龄', null=True, blank=True)
    client_id = models.CharField(verbose_name='客户id', max_length=8, null=True, blank=True, unique=True)

    def get_willing_cities_name(self):
        return list(self.willing_cities.only('name').values_list('name', flat=True))

    @classmethod
    def get_by_id(cls, id, raise_exc=True):
        try:
            return cls.objects.get(id=int(id))
        except cls.DoesNotExist:
            if raise_exc:
                gen(CODES.BDTRANSFER_NOT_EXIST)
            return None


class BDTransferOperationRecord(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_operationrecord'
        app_label = 'api'
        verbose_name = '操作记录表'
    bdtransfer = models.ForeignKey(BDTransfer, verbose_name='关联转诊人员', related_name='operation_records')
    operate_user = models.ForeignKey(User, verbose_name=u'操作对象')
    action = models.SmallIntegerField(verbose_name=u'操作类型', choices=OPERATION_ACTION, null=False)
    content = models.CharField(verbose_name=u'操作内容', max_length=128, default='')
    operate_time = models.DateTimeField(auto_now=True, verbose_name=u'操作时间')

    @classmethod
    def get_by_id(cls, id, raise_exc=True):
        try:
            return cls.objects.get(id=int(id))
        except cls.DoesNotExist:
            if raise_exc:
                gen(CODES.BDTRANSFER_OPERATION_RECORD_NOT_EXIST)
            return None


class BDTransferWillingProject(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_willing_project'
        app_label = 'api'
        verbose_name = u'意向项目关联表'

    tag = models.ForeignKey(Tag, verbose_name=u'项目标签')  # 关联二级标签
    start_time = models.DateField(verbose_name=u"意向开始时间", null=True)
    end_time = models.DateField(verbose_name=u"意向结束时间", null=True)
    comment = models.CharField(verbose_name=u'备注', max_length=256, default='')
    bdtransfer = models.ForeignKey(BDTransfer, verbose_name=u'关联转诊记录', related_name='willing_projects')


class BDTransferHistoryProject(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_history_project'
        app_label = 'api'
        verbose_name = "转诊人员历史项目"

    tag = models.ForeignKey(Tag, verbose_name=u'项目标签')  # 关联二级标签
    know_time = models.DateField(verbose_name=u'了解时间', null=True)
    bdtransfer = models.ForeignKey(BDTransfer, verbose_name=u'关联转诊记录', related_name='history_projects')


class BDTransferCommunicationRecord(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_communicationrecord'
        app_label = 'api'
        verbose_name = u'沟通记录表'
    communication_time = models.DateTimeField(verbose_name=u'沟通时间', auto_now_add=True)
    user = models.ForeignKey(User, verbose_name=u'沟通人')
    content = models.TextField(verbose_name=u'沟通记录', default='')
    bdtransfer = models.ForeignKey(BDTransfer, verbose_name=u'关联转诊记录', related_name='communication_records')

    @classmethod
    def get_by_id(cls, id, raise_exc=True):
        try:
            return cls.objects.get(id=int(id))
        except cls.DoesNotExist:
            if raise_exc:
                gen(CODES.BDTRANSFER_COMMUNICATION_RECORD_NOT_EXIST)
            return None

class BDTransferCommunicationRecordImg(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_communicationrecord_img'
        app_label = 'api'
        verbose_name = u'沟通记录图片'
    bdtransfercommunicationrecord = models.ForeignKey(BDTransferCommunicationRecord, verbose_name=u'关联沟通记录表', related_name='communication_records_img')
    image_url = ImgUrlField(u'上传图片', img_type=IMG_TYPE.NOWATERMARK, max_length=200, default='')

class BDTransferSingleRecord(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_singlerecord'
        app_label = 'api'
        verbose_name = '派单记录表'
    single_time = models.DateTimeField(verbose_name=u'派单时间', auto_now_add=True)
    user = models.ForeignKey(User, verbose_name=u'派单人')
    doctor = models.ForeignKey(Doctor, verbose_name=u'派单医生', max_length=32, default='')
    project = models.ManyToManyField(Tag, verbose_name=u'派单项目', max_length=128, default='')
    status = models.SmallIntegerField(verbose_name=u'派单状态', choices=SINGLE_TYPE, default=SINGLE_TYPE.NO_ORDER_FORM)
    budan = models.ForeignKey(BuDan, verbose_name=u'关联补单', related_name='tsrecord', null=True)
    # TODO: 更改字段名 dbtransfer -> bdtransfer
    dbtransfer = models.ForeignKey(BDTransfer, verbose_name=u'关联转诊记录', related_name='single_records')

    # 7740t添加 为了更加精准的确定用户的状态 http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=11615549
    appointment_time = models.DateTimeField(verbose_name=u'预约时间', null=True)
    consultation_time = models.DateTimeField(verbose_name=u'面诊时间', null=True)
    confirm_user = models.ForeignKey(User, verbose_name=u'最后成单确认用户信息', related_name='confirm_single_records', null=True)
    is_consume = models.BooleanField(verbose_name=u'是否提交消费信息', default=False)
    operation_time = models.DateTimeField(verbose_name=u'手术时间', blank=True, null=True)
    consume_image = models.URLField(verbose_name=u'消费截图', blank=True, null=True, default='')
    comment = models.CharField(verbose_name=u'消费备注', max_length=500, blank=True, null=True)
    consume_projects = models.CharField(max_length=5000,
                                    verbose_name=u'消费项目(json) [{"name": x, "money": 1, "time": 2019-01-01}]', blank=True, null=True)
    duplicate_comment = models.CharField(verbose_name=u'重单备注', max_length=200, blank=True, null=True)
    duplicate_image = models.URLField(verbose_name=u'重单截图', blank=True, null=True, default='')
    @classmethod
    def get_by_id(cls, id, raise_exc=True):
        try:
            return cls.objects.get(id=int(id))
        except cls.DoesNotExist:
            if raise_exc:
                gen(CODES.BDTRANSFER_SINGLE_RECORD_NOT_EXIST)
            return None


class BDTransferSingleRecordLog(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_singlerecord_log'
        app_label = 'api'
        verbose_name = '派单记录表日志'

    singlerecord = models.ForeignKey(BDTransferSingleRecord, verbose_name='派单记录')
    status = models.SmallIntegerField(verbose_name=u'派单状态', choices=SINGLE_TYPE)
    created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)


class BDTransferClueTag(models.Model):
    class Meta:
        db_table = 'api_bdtransfer_cluetag'
        app_label = 'api'
        verbose_name = '常用标签'
    name = models.CharField(verbose_name=u'标签名', max_length=32, unique=True)
    is_online = models.BooleanField(verbose_name=u'是否上下线', default=False)
    create_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)

    def __repr__(self):
        return "BDTransferClueTag(name=<{}>, is_online=<{}>)".format(self.name, self.is_online)

    def __str__(self):
        return self.__repr__()


###
# author: kula
# doc: http://wiki.wanmeizhensuo.com/pages/viewpage.action?pageId=15861166
###
class BDTransferDayChangeLog(models.Model):
    class Meta:
        db_table = "api_bdtransfer_daychangelog"
        app_label = "api"
        verbose_name = "派单记录每日单号变更表"

    transfer_id = models.IntegerField(verbose_name=u"派单记录号")
    thread_id = models.IntegerField(verbose_name=u"线索id")
    changed_date = models.DateField(verbose_name=u"变更日期")
    newest_status = models.IntegerField(verbose_name=u"最新变更状态", choices=SINGLE_TYPE)
    source = models.CharField(verbose_name=u"来源渠道", max_length=64)
    created_user = models.CharField(verbose_name=u"创建信息人", max_length=256)
    consultant = models.CharField(verbose_name=u"跟进顾问", max_length=256)
    org = models.CharField(verbose_name=u"派单机构", max_length=256)


class BDTransferWebKefu(models.Model):
    class Meta:
        db_table = "api_bdtransfer_web_kefu"
        app_label = 'api'
        verbose_name = "PC转诊客服表"

    nickname = models.CharField(verbose_name=u"客服姓名", max_length=64)
    qr_code = models.URLField(verbose_name='客服二维码')
    is_online = models.BooleanField(verbose_name=u'是否上线', default=False)


class BDTransferMonth(models.Model):
    class Meta:
        verbose_name = u'佣金月记录'
        db_table = 'api_bdtransfermonth'
        app_label = 'api'

    month_at = models.DateField(null=False, verbose_name=u'那个月的补单')
    total_amount = models.FloatField(verbose_name=u'项目总额', default=0)
    should_pay = models.FloatField(verbose_name=u'应补佣金', default=0)
    already_pay = models.FloatField(verbose_name=u'已补佣金', default=0)
    is_finished = models.BooleanField(verbose_name=u'是否已补齐', default=False)
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')
    monthly_total_amount = models.FloatField(verbose_name=u'跨月撤销转诊项目总额', default=0)
    monthly_should_pay = models.FloatField(verbose_name=u'跨月撤销转诊应补佣金', default=0)

    doctor = models.ForeignKey(Doctor, verbose_name=u'关联医生')


class BDTransferMonthToBudan(models.Model):
    class Meta:
        verbose_name = u'佣金月记录与关联补单'
        db_table = 'api_bdtransfermonthtobudan'
        app_label = 'api'

    bdtransfermonth = models.ForeignKey(BDTransferMonth, related_name='month_budans')
    budan = models.ForeignKey(BuDan)
    has_paid = models.BooleanField(verbose_name=u'是否已补', default=False)
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')

class BDTransferMonthlyWithdrawalToBudan(models.Model):
    class Meta:
        verbose_name = u'跨月撤销补单月记录与关联补单'
        db_table = 'api_bdtransfermonthlywithdrawaltobudan'
        app_label = 'api'

    bdtransfermonth = models.ForeignKey(BDTransferMonth, related_name='monthlywithdrawal_budans')
    budan = models.ForeignKey(BuDan)
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')

class BDTransferApplyRecord(models.Model):
    class Meta:
        verbose_name = u'佣金补交记录'
        db_table = 'api_bdtransferapplyrecord'
        app_label = 'api'

    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')
    pass_time = models.DateTimeField(null=True, blank=True, verbose_name=u'补交成功时间')
    total_amount = models.FloatField(verbose_name=u'项目总额')
    should_pay = models.FloatField(verbose_name=u'应补佣金')
    status = models.IntegerField(choices=BDTRANSFER_APPLY_STATUS, default=BDTRANSFER_APPLY_STATUS.PENDING,
                                 verbose_name=u'申请状态')
    doctor = models.ForeignKey(Doctor, verbose_name=u'关联医生')
    reason = models.CharField(max_length=1000, null=True, blank=True, verbose_name=u'驳回原因')
    bdtransfermonth = models.ForeignKey(BDTransferMonth, verbose_name=u'佣金月记录')

    def update_pics(self, image_type, pics=[]):
        old_imgs = BDTransferApplyPic.objects.filter(bdtransferapplyrecord_id=self.id, image_type=image_type)
        for url in pics:
            BDTransferApplyPic.objects.get_or_create(
                bdtransferapplyrecord_id=self.id,
                content=url,
                image_type=image_type,
            )
        old_imgs.filter(~Q(content__in=pics)).delete()

    def get_pics(self, image_type):
        imgs = BDTransferApplyPic.objects.filter(bdtransferapplyrecord_id=self.id, image_type=image_type)
        return [rp.content for rp in imgs]


class BDTransferApplyPic(models.Model):
    class Meta:
        verbose_name = u'佣金补交记录关联图片'
        db_table = 'api_bdtransferapplypic'
        app_label = 'api'

    bdtransferapplyrecord = models.ForeignKey(BDTransferApplyRecord, verbose_name=u'佣金补交记录')
    content = ImgUrlField(img_type=IMG_TYPE.DOCTOR, max_length=300, help_text=u'', verbose_name=u'图片URL',
                          blank=True, default='')
    image_type = models.IntegerField(verbose_name=u'图片的类型', choices=BDTRANSFER_PIC_TYPE)


class BDTransferToBudan(models.Model):
    class Meta:
        verbose_name = u'佣金补交记录与补单关联表'
        db_table = 'api_bdtransfertobudan'
        app_label = 'api'

    bdtransferapplyrecord = models.ForeignKey(BDTransferApplyRecord, verbose_name=u'佣金补交记录',
                                              related_name='record_budans')
    budan = models.ForeignKey(BuDan, verbose_name=u'补单')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')
