#!/usr/bin/env python
# coding=utf-8
from __future__ import unicode_literals, absolute_import

import json

from django.db import models
from gm_types.doctor import DOCTOR_ACCOUNT_TYPE, DOCTOR_ACCOUNT_STATUS, BILL_INFO_TYPE
from gm_types.doctor import HOSTING_TYPE, AGREEMENT_TYPE, BUSINESS_TYPE
from gm_types.doctor import AGREEMENT_IMG_TYPE, ID_TYPE, AGREEMENT_RECORD_STATUS
from gm_types.gaia import MERCHANT_LEVEL, MERCHANT_FREEZE_ACTION, MERCHANT_LEVEL_NEW
from gm_upload import ImgUrlField, IMG_TYPE

from api.models.person import User, Person
from api.models.area import Country, Province, City
from api.tool.datetime_tool import get_timestamp_epoch
from hippo.models.finance import FinanceCity
from .doctor import Doctor

from hippo.utils import time_base_prikey


class Merchant(models.Model):
    class Meta:
        verbose_name = u'商户表'
        app_label = 'hippo'

    id = models.BigIntegerField(u'商户id', primary_key=True, default=time_base_prikey)
    doctor = models.OneToOneField(Doctor, verbose_name=u'对应的医生', related_name='d_merchant')
    name = models.CharField(max_length=200, verbose_name=u'医生姓名')
    created_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)
    is_online = models.BooleanField(verbose_name=u'是否还在使用', default=True)
    merchant_level = models.IntegerField(verbose_name='商户等级', choices=MERCHANT_LEVEL_NEW, default=MERCHANT_LEVEL_NEW.V0)
    merchant_score = models.FloatField(verbose_name='商户得分', default= '0.00')
    verify_gmv_score = models.FloatField(verbose_name='验证GMV得分', default='0.00')
    advertise_score = models.FloatField(verbose_name='广告消费得分', default='0.00')
    verify_gmv_amount = models.FloatField(verbose_name='验证GMV金额均值', default= '0.00')
    advertise_consume_amount = models.FloatField(verbose_name='广告消费金额均值', default='0.00')
    is_freeze = models.BooleanField(verbose_name='商户状态', default=False)
    verify_pv_amount = models.FloatField(verbose_name='单pv验证金额', default=0.0)
    refund_proportion = models.FloatField(verbose_name='近三月退款率', default=0.0)

    @staticmethod
    def get_doctor_merchant_level(doctor_id):
        merchant_level = MERCHANT_LEVEL_NEW.V1
        merchant = Merchant.objects.filter(
            is_online=True,
            doctor_id=doctor_id
        ).values("merchant_level").first()
        if merchant:
            merchant_level = merchant["merchant_level"]
        return merchant_level


class MerchantFreezeRecord(models.Model):
    class Meta:
        verbose_name = u'商户冻结记录表'
        app_label = 'hippo'
    merchant = models.ForeignKey(Merchant, verbose_name=u'关联的商户id')
    created_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)
    reason = models.CharField(max_length=64, verbose_name='冻结理由', blank=True, null=True)
    action = models.IntegerField(verbose_name='冻结、解冻', default=MERCHANT_FREEZE_ACTION.FREEZE)


class MerchantRelevance(models.Model):
    class Meta:
        verbose_name = u'商户关联表'
        app_label = 'hippo'

    merchant = models.ForeignKey(Merchant, verbose_name=u'关联的商户id', related_name='merchant_doctors')
    doctor = models.ForeignKey(Doctor, verbose_name=u'商户下的doctor', unique=True)


class MerchantNonsync(models.Model):
    class Meta:
        verbose_name = u'不需要同步的商户id'
        app_label = 'hippo'

    merchant_id = models.BigIntegerField(u'商户id', null=False, unique=True)
    created_time = models.DateTimeField(verbose_name='添加时间', auto_now_add=True)


class MerchantAccount(models.Model):
    class Meta:
        verbose_name = u'商户的结算信息'
        app_label = 'hippo'

    merchant = models.OneToOneField(Merchant, related_name='account')
    country = models.ForeignKey(Country, null=True, blank=True)
    province = models.ForeignKey(Province, null=True, blank=True)
    city = models.ForeignKey(City, null=True, blank=True)
    bank = models.CharField('开户银行', max_length=30)
    subbranch = models.CharField('支行/分行', max_length=100, null=True, blank=True)
    account_name = models.CharField('户名', max_length=100)
    account_number = models.CharField('账号', max_length=50)
    account_type = models.IntegerField('开户类型', choices=DOCTOR_ACCOUNT_TYPE, default=DOCTOR_ACCOUNT_TYPE.BANK)
    #  0 银行 1 支付宝
    status = models.IntegerField(verbose_name=u'信息修改状态', choices=DOCTOR_ACCOUNT_STATUS,
                                 default=DOCTOR_ACCOUNT_STATUS.CHECKED)
    city_finance = models.ForeignKey(FinanceCity, null=True, blank=True, verbose_name=u'城市(关联财务省市的表)')
    update_time = models.DateTimeField(verbose_name='资料审核通过时间', null=True, blank=True)


class MerchantAccountRecord(models.Model):
    """
        商户账号结算 信息
        每次提交修改+审核(驳回或者通过)  合在一起只有一条记录
    """

    class Meta:
        app_label = 'hippo'
        db_table = 'hippo_merchantaccountrecord'
        verbose_name = u'商户结算账号修改日志'
        verbose_name_plural = u'商户结算账号修改日志'

    account = models.ForeignKey(MerchantAccount, help_text=u"商户结算账号")
    status = models.IntegerField(verbose_name=u'信息修改状态', choices=DOCTOR_ACCOUNT_STATUS,
                                 default=DOCTOR_ACCOUNT_STATUS.CHECKED)
    reject_reason = models.CharField(u'拒绝原因', max_length=100, blank=True, null=True)
    handler = models.ForeignKey(Person, help_text=u"处理人", blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=u'记录时间')
    content = models.TextField(u'修改后信息内容')

    def data(self):
        info = {
            'merchant_id': self.account.merchant_id,
            'status': self.status,
            'reject_reason': self.reject_reason,
            'created_at': get_timestamp_epoch(self.created_at),
            'content': json.loads(self.content)['content'],
        }
        city_id = info['content'].get('city_id', None)
        if city_id:
            try:
                info['content']['city_name'] = FinanceCity.objects.get(id=city_id).name
            except:
                info['content']['city_name'] = ''

        else:
            info['content']['city_name'] = ''
        return info


class MerchantLicense(models.Model):
    class Meta:
        app_label = 'hippo'
        verbose_name = u'机构商户营业执照信息'

    merchant = models.OneToOneField(Merchant, verbose_name=u'对应商户', related_name='license')
    lincense_img = ImgUrlField(img_type=IMG_TYPE.ORGANIZATIONIMAGE, max_length=256, help_text=u"图片url")
    lincense_name = models.CharField(verbose_name=u'营业执照名称', max_length=100)
    lincense_number = models.CharField(verbose_name=u'统一社会信用代码', max_length=100)
    lincense_start_time = models.DateTimeField(verbose_name=u'营业开始时间')
    # 若营业结束时间为长期则 lincense_end_time 为空
    lincense_end_time = models.DateTimeField(verbose_name=u'营业结束时间', null=True)


class MerchantBillInfo(models.Model):
    class Meta:
        verbose_name = u'商户发票信息'
        app_label = 'hippo'

    # 发票抬头及税号可选合同信息中甲方公司名称和税号、甲方代运营公司名称和税号
    info_type = models.IntegerField(verbose_name=u'抬头类型', choices=BILL_INFO_TYPE,
                                    default=BILL_INFO_TYPE.NORMAL)
    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)
    email = models.CharField(verbose_name='邮件地址', max_length=200)

    merchant = models.OneToOneField(Merchant, verbose_name=u'对应商户', related_name='billinfo')


class MerchantAgreement(models.Model):
    class Meta:
        verbose_name = u'商户合同'
        app_label = 'hippo'

    merchant = models.OneToOneField(Merchant, verbose_name=u'对应商户', related_name='agreement')
    first_company_name = models.CharField(verbose_name=u'甲方公司名称', max_length=100)
    first_company_number = models.CharField(verbose_name=u'甲方公司统一社会信用代码', max_length=100)
    hosting_type = models.IntegerField(verbose_name=u'代运营类型', choices=HOSTING_TYPE)
    first_hosting_company_name = models.CharField(verbose_name=u'甲方代运营公司名称', max_length=100, null=True)
    first_hosting_company_number = models.CharField(
        verbose_name=u'甲方代运营公司统一社会信用代码', max_length=100, null=True
    )
    first_hosting_single_name = models.CharField(verbose_name=u'甲方代运营个人姓名', max_length=100, null=True)
    first_hosting_single_type = models.IntegerField(u'甲方代运营个人证件类型', choices=ID_TYPE)
    first_hosting_single_number = models.CharField(verbose_name=u'甲方代运营个人证件编号', max_length=100)
    second_company_name = models.CharField(verbose_name=u'乙方公司名称', max_length=100)
    agreement_start_time = models.DateTimeField(verbose_name=u'合同开始时间')
    agreement_end_time = models.DateTimeField(verbose_name=u'合同结束时间', null=True)
    enter_amount = models.IntegerField(verbose_name=u'入驻费')
    cash_deposit = models.IntegerField(verbose_name=u'保证金')
    agreement_type = models.IntegerField(u'合同结算类型', choices=AGREEMENT_TYPE)
    business_type = models.IntegerField(verbose_name=u'美容业务类型', choices=BUSINESS_TYPE)


class MerchantAgreementImg(models.Model):
    class Meta:
        verbose_name = u'商户合同图片'
        app_label = 'hippo'

    merchantagreement = models.ForeignKey(MerchantAgreement, verbose_name=u'对应合同', related_name='img')
    img_url = ImgUrlField(img_type=IMG_TYPE.ORGANIZATIONIMAGE, max_length=256, help_text=u"图片url")
    img_type = models.IntegerField(u'图片类型', choices=AGREEMENT_IMG_TYPE)


class MerchantAgreementRecord(models.Model):
    class Meta:
        verbose_name = u'商户合同修改Dtcols日志'
        app_label = 'hippo'

    merchant = models.ForeignKey(Merchant, related_name='agreement_records')
    status = models.IntegerField(u'信息修改状态', choices=AGREEMENT_RECORD_STATUS, default=AGREEMENT_RECORD_STATUS.TODO)
    reject_reason = models.CharField(u'拒绝原因', max_length=100, blank=True, null=True)
    proposer = models.ForeignKey(User, help_text=u'提交人', related_name='agreementproposer')
    handler = models.ForeignKey(User, help_text=u'审核人', blank=True, null=True, related_name='agreementhandler')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name=u'记录时间')
    handle_at = models.DateTimeField('审核时间', null=True)

    first_company_name = models.CharField(u'甲方公司名称', max_length=100)
    first_company_number = models.CharField(u'甲方公司统一社会信用代码', max_length=100)
    hosting_type = models.IntegerField(u'代运营类型', choices=HOSTING_TYPE)
    first_hosting_company_name = models.CharField(u'甲方代运营公司名称', max_length=100, null=True)
    first_hosting_company_number = models.CharField(u'甲方代运营公司统一社会信用代码', max_length=100, null=True)
    first_hosting_single_name = models.CharField(u'甲方代运营个人姓名', max_length=100, null=True)
    first_hosting_single_type = models.IntegerField(u'甲方代运营个人证件类型', choices=ID_TYPE)
    first_hosting_single_number = models.CharField(u'甲方代运营个人证件编号', max_length=100)
    second_company_name = models.CharField(u'乙方公司名称', max_length=100)
    agreement_start_time = models.DateTimeField(u'合同开始时间')
    agreement_end_time = models.DateTimeField(u'合同结束时间', null=True)
    enter_amount = models.IntegerField(u'入驻费')
    cash_deposit = models.IntegerField(u'保证金')
    agreement_type = models.IntegerField(u'合同结算类型', choices=AGREEMENT_TYPE)
    business_type = models.IntegerField(u'美容业务类型', choices=BUSINESS_TYPE)

    @classmethod
    def record_approve(cls, **kwargs):
        record = MerchantAgreementRecord.objects.get(**kwargs)
        if not record:
            return
        defaults = {
            'first_company_name': record.first_company_name,
            'first_company_number': record.first_company_number,
            'hosting_type': record.hosting_type,
            'first_hosting_company_name': record.first_hosting_company_name,
            'first_hosting_company_number': record.first_hosting_company_number,
            'first_hosting_single_name': record.first_hosting_single_name,
            'first_hosting_single_type': record.first_hosting_single_type,
            'first_hosting_single_number': record.first_hosting_single_number,
            'second_company_name': record.second_company_name,
            'agreement_start_time': record.agreement_start_time,
            'agreement_end_time': record.agreement_end_time,
            'enter_amount': record.enter_amount,
            'cash_deposit': record.cash_deposit,
            'agreement_type': record.agreement_type,
            'business_type': record.business_type,
        }
        agreement, _ = MerchantAgreement.objects.update_or_create(
            defaults, merchant=record.merchant
        )
        agreement.img.all().delete()
        for img in record.img.all():
            MerchantAgreementImg.objects.create(
                merchantagreement=agreement,
                img_type=img.img_type,
                img_url=img.img_url
            )
        return


class MerchantAgreementRecordImg(models.Model):
    class Meta:
        verbose_name = u'商户合同图片审核'
        app_label = 'hippo'

    record = models.ForeignKey(MerchantAgreementRecord, related_name='img')
    img_url = ImgUrlField(img_type=IMG_TYPE.ORGANIZATIONIMAGE, max_length=256)
    img_type = models.IntegerField(u'图片类型', choices=AGREEMENT_IMG_TYPE)


class MerchantRelatedInfo(models.Model):
    class Meta:
        verbose_name = u'商户联系信息'
        app_label = 'hippo'

    merchant = models.ForeignKey(Merchant, verbose_name=u'关联的商户id', related_name='merchant_relatedinfos')
    name = models.CharField(max_length=50, verbose_name=u'联系人姓名')
    role = models.CharField(max_length=50, verbose_name=u'联系人角色')
    phone = models.CharField(max_length=50, verbose_name=u'联系人电话')


class MerchantLevelRecord(models.Model):
    class Meta:
        verbose_name = u'商户评级记录'
        app_label = 'hippo'

    merchant = models.ForeignKey(Merchant, verbose_name='关联的商户')
    merchant_level = models.IntegerField(verbose_name='商户等级', choices=MERCHANT_LEVEL_NEW, default=MERCHANT_LEVEL_NEW.V1)
    merchant_score = models.FloatField(verbose_name='商户得分', default= '0.00')
    verify_gmv_amount = models.FloatField(verbose_name='验证GMV金额均值', default= '0.00')
    advertise_consume_amount = models.FloatField(verbose_name='广告消费金额均值', default='0.00')
    created_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=False)
    verify_pv_amount = models.FloatField(verbose_name='单pv验证金额', default=0.0)
    refund_proportion = models.FloatField(verbose_name='近三月退款率', default=0.0)

class MerchantContract(models.Model):
    class Meta:
        verbose_name = u'商户合同'
        app_label = 'hippo'
        db_table="hippo_merchant_contract"

    merchant = models.ForeignKey(Merchant, verbose_name='关联的商户',related_name="merchantcontract_merchant")
    cash_back_rate_str = models.CharField(max_length=100,verbose_name='抽拥比例')
    start_time = models.DateTimeField(verbose_name='开始时间')
    end_time = models.DateTimeField(verbose_name='结束时间')
    create_time = models.DateTimeField(verbose_name='创建时间',  auto_now_add=True)
    update_time = models.DateTimeField(verbose_name='修改时间',  auto_now=True)


class Account(models.Model):
    class Meta:
        verbose_name = u'医生账号信息'
        app_label = 'account'

    doctor_id = models.CharField(max_length=100, verbose_name=u'医生ID', unique=True)
    rechange_amount = models.IntegerField(verbose_name='充值余额', default=0)
    cashback_amount = models.IntegerField(verbose_name='返现余额', default=0)
    status = models.IntegerField(verbose_name=u'账户状态')
    is_accountuser = models.BooleanField(verbose_name=u'是否启用交易转广告', default=False)


class PriorityBDtransfer(models.Model):

    class Meta:
        app_label = 'bdtransfer'
        verbose_name = '优先派单商户'

    doctor_id = models.CharField(verbose_name='商户医生id', max_length=100)
    merchant_id = models.CharField(verbose_name='商户id', max_length=64)
    budget = models.PositiveIntegerField(verbose_name='单日推广预算', default=0)
    is_open = models.BooleanField(verbose_name='是否开启', default=False)
    created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)


class BDtransferConsume(models.Model):
    class Meta:
        app_label = 'bdtransfer'
        verbose_name = '转诊消耗'

    priority_bdtransfer_id = models.IntegerField(verbose_name=u'优先派单商户表主键id')
    merchant_id = models.CharField(verbose_name=u'商户id', max_length=64)
    date = models.DateField(verbose_name=u'消耗日期', db_index=True)
    amount = models.IntegerField(verbose_name=u'单天消耗总额', default=0)
    recharge_amount = models.IntegerField(verbose_name=u'单天充值消耗', default=0)
    cashback_amount = models.IntegerField(verbose_name=u'单天返点消耗总额', default=0)
    created_time = models.DateTimeField(verbose_name=u'创建时间', auto_now_add=True)