# coding=utf-8
import json

from django.db import models

from hippo.models.doctor import Doctor
from gm_types.doctor import DOCTOR_EXPRESS_COMPANY, DOCTOR_BILLAPPLY_STATUS, DOCTOR_BILL_TYPE, \
    BILL_REFUSE_REASON, DOCTOR_BILL_CLASS
from pay.models.statementall import StatementAll
from api.models.budan import BuDan


class DoctorFinanceInfo(models.Model):
    class Meta:
        verbose_name = u'医生财务信息'
        db_table = 'hippo_financeinfo'
        app_label = 'hippo'

    tax_id = models.CharField(verbose_name=u'税务登记号', max_length=40)
    register_address = models.CharField(verbose_name=u'注册场所地址', max_length=50)
    register_phone = models.CharField(verbose_name=u'注册固定电话号码', max_length=50)
    account_name = models.CharField(verbose_name=u'基本开户行名称', max_length=50)
    bank_account = models.CharField(verbose_name=u'银行账号', max_length=50)
    receiver_name = models.CharField(verbose_name=u'收件人姓名', max_length=40)
    receiver_phone = models.CharField(verbose_name=u'收件人联系电话', max_length=40)
    receiver_address = models.CharField(verbose_name=u'收件地址', max_length=100)

    doctor = models.OneToOneField(Doctor, verbose_name=u'对应医生')

    def get_info(self):
        """
        获取信息
        :return:
        """
        return {
            "id": self.id,
            "doctor_name": self.doctor.name,
            "doctor_id": self.doctor.id,
            "hospital_id": self.doctor.hospital.id if self.doctor.hospital else '',
            "hospital_name": self.doctor.hospital.name if self.doctor.hospital else '',
            "taitou": self.doctor.merchant.account.account_name if self.doctor.merchant.account else '',
            "tax_id": self.tax_id,
            "register_address": self.register_address,
            "register_phone": self.register_phone,
            "account_name": self.account_name,
            "bank_account": self.bank_account
        }


class BillApplyRecord(models.Model):
    class Meta:
        verbose_name = u'医生发票申请记录'
        db_table = 'hippo_billapplyrecord'
        app_label = 'hippo'

    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')
    bill_time = models.DateTimeField(verbose_name=u'开票时间', null=True)
    amount = models.FloatField(verbose_name=u'发票金额')
    bill_type = models.IntegerField(verbose_name=u'发票类型', choices=DOCTOR_BILL_TYPE,
                                    default=DOCTOR_BILL_TYPE.GENERAL)
    status = models.IntegerField(choices=DOCTOR_BILLAPPLY_STATUS, default=DOCTOR_BILLAPPLY_STATUS.PENDING)
    express_company = models.IntegerField(verbose_name=u'快递公司', choices=DOCTOR_EXPRESS_COMPANY, null=True)
    express_id = models.CharField(verbose_name=u'快递单号', max_length=100, null=True)
    # 所有的doctorfinanceinfo ，关联的对账单ID；结构 {finance_info:{}, statement_ids/rechange_ids:[]}
    snapshot = models.CharField(verbose_name=u'申请发票时，开快递的快照', max_length=2000)
    reason = models.IntegerField(verbose_name=u'驳回原因', choices=BILL_REFUSE_REASON,
                                 default=BILL_REFUSE_REASON.TAX_ID_ERROR)
    category = models.IntegerField(verbose_name=u'发票类别', choices=DOCTOR_BILL_CLASS,
                                   default=DOCTOR_BILL_CLASS.COMMISSION)

    doctor = models.ForeignKey(Doctor, verbose_name=u'关联医生')
    more_reason = models.TextField(verbose_name=u'自定义驳回原因', null=True)
    remark = models.TextField(verbose_name=u'备注', null=True, blank=True)
    is_online = models.BooleanField(verbose_name=u'是否为在线充值', default=False)

    @property
    def bill_ids(self):
        return [obj.bill_id for obj in self.applytobillids.all()]

    def get_recordfinance_info(self):
        finance_info = json.loads(self.snapshot)['finance_info']
        if self.category == DOCTOR_BILL_CLASS.COMMISSION:
            return {
                'id': self.id,
                'created_time': self.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                'bill_header': finance_info['bill_header'],
                'bill_type': DOCTOR_BILL_TYPE.getDesc(self.bill_type),
                'tax_id': finance_info['tax_id'],
                'amount': self.amount,
                'bill_id': self.bill_ids,
                'status': self.status,
                'status_desc': DOCTOR_BILLAPPLY_STATUS.getDesc(self.status),
                'reason': self.more_reason if self.reason == BILL_REFUSE_REASON.OTHERS
                else BILL_REFUSE_REASON.getDesc(self.reason),
                'express_company': DOCTOR_EXPRESS_COMPANY.getDesc(self.express_company),
                'express_id': self.express_id,
                'periods': [obj.statementall.statement_date for obj in self.recordtoperiods.all()],
                'category': self.category,
                'email': finance_info.get('email', '')
            }
        elif self.category == DOCTOR_BILL_CLASS.RECHANGE:
            return {
                'id': self.id,
                'created_time': self.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                'bill_header': finance_info['bill_header'],
                'bill_type': DOCTOR_BILL_TYPE.getDesc(self.bill_type),
                'tax_id': finance_info['tax_id'],
                'amount': self.amount,
                'bill_id': self.bill_ids,
                'status': self.status,
                'status_desc': DOCTOR_BILLAPPLY_STATUS.getDesc(self.status),
                'reason': self.more_reason if self.reason == BILL_REFUSE_REASON.OTHERS
                else BILL_REFUSE_REASON.getDesc(self.reason),
                'express_company': DOCTOR_EXPRESS_COMPANY.getDesc(self.express_company),
                'express_id': self.express_id,
                'periods': [obj.adrechange_id for obj in self.recordtorechanges.all()],
                'category': self.category,
                'email': finance_info.get('email', ''),
                'is_online': self.is_online
            }
        elif self.category ==  DOCTOR_BILL_CLASS.BUDAN:
            return {
                'id': self.id,
                'created_time': self.created_time.strftime('%Y-%m-%d %H:%M:%S'),
                'bill_header': finance_info['bill_header'],
                'bill_type': DOCTOR_BILL_TYPE.getDesc(self.bill_type),
                'tax_id': finance_info['tax_id'],
                'amount': self.amount,
                'bill_id': self.bill_ids,
                'status': self.status,
                'status_desc': DOCTOR_BILLAPPLY_STATUS.getDesc(self.status),
                'reason': self.more_reason if self.reason == BILL_REFUSE_REASON.OTHERS
                else BILL_REFUSE_REASON.getDesc(self.reason),
                'express_company': DOCTOR_EXPRESS_COMPANY.getDesc(self.express_company),
                'express_id': self.express_id,
                'periods': [obj.budan_id for obj in self.recordtobudans.all()],
                'category': self.category,
                'email': finance_info.get('email', '')
            }
        else:
            return {}

    def get_finance_and_record_info(self):
        record_info = {}

        record_info['finance_info'] = json.loads(self.snapshot)['finance_info']
        record_info['bill_info'] = self.get_recordfinance_info()

        return record_info


class BillIdToBillApply(models.Model):
    """
    发票编号关联表
    """

    class Meta:
        verbose_name = u'发票编号关联发票申请表'
        db_table = 'hippo_billidtobillapply'
        app_label = 'hippo'

    billapplyrecord = models.ForeignKey(BillApplyRecord, verbose_name='发票申请记录', related_name='applytobillids')
    bill_id = models.CharField(verbose_name=u'发票编号', max_length=50)


class BillToStatementAll(models.Model):
    class Meta:
        verbose_name = u'发票申请与关联的结算单'
        db_table = 'hippo_billtostatementall'
        app_label = 'hippo'

    billapplyrecord = models.ForeignKey(BillApplyRecord, related_name='recordtoperiods')
    statementall = models.ForeignKey(StatementAll, verbose_name=u'关联的结算单')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')


class BillToAdrechange(models.Model):
    class Meta:
        verbose_name = u'发票申请与关联的广告充值单'
        db_table = 'hippo_billtoadrechange'
        app_label = 'hippo'

    billapplyrecord = models.ForeignKey(BillApplyRecord, related_name='recordtorechanges')
    adrechange_id = models.IntegerField(verbose_name=u'充值单ID')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')


class BillToTransferBudan(models.Model):
    class Meta:
        verbose_name = u'发票申请与关联的转诊补单'
        db_table = 'hippo_billtotransferbudan'
        app_label = 'hippo'

    billapplyrecord = models.ForeignKey(BillApplyRecord, related_name='recordtobudans')
    budan = models.ForeignKey(BuDan, verbose_name=u'关联的转诊补单')
    created_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')


class BillApplyReopenRecord(models.Model):
    class Meta:
        verbose_name = u'充值发票/佣金发票重开记录表'
        db_table = u'hippo_billapplyreopenrecord'
        app_label = 'hippo'

    reopenrecords = models.ForeignKey(BillApplyRecord, related_name='reopenrecords')
    create_time = models.DateTimeField(verbose_name=u'重开记录时间', auto_now_add=True)
    status = models.BooleanField(verbose_name=u'状态')
    reopen_reason = models.TextField(verbose_name=u'备注信息', null=True)
    express_company = models.IntegerField(verbose_name=u'快递公司', choices=DOCTOR_EXPRESS_COMPANY, null=True)
    express_id = models.CharField(verbose_name=u'快递单号', max_length=100, null=True)
    bill_type = models.IntegerField(verbose_name=u'发票类型', choices=DOCTOR_BILL_TYPE,
                                    default=DOCTOR_BILL_TYPE.GENERAL)
    bill_id = models.CharField(verbose_name=u'发票编号', max_length=128)