#!/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
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, default=MERCHANT_LEVEL.E)
    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')
    is_freeze = models.BooleanField(verbose_name='商户状态',default=False)


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'联系人电话')
