# coding=utf-8
import datetime
from django.db import models
from django.conf import settings
from utils.exceptions import CustomError
from apps.log.models import BizLog
from django.contrib.auth import get_user_model
User = get_user_model()
from apps.upload.models import Upload
from apps import order

class Product(models.Model):
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='package_create_user', verbose_name=u"添加人",
                                    on_delete=models.PROTECT, editable=False)
    create_time = models.DateTimeField(verbose_name=u'添加时间', auto_now_add=True, editable=False)
    month = models.IntegerField(verbose_name=u'贷款期限')
    name = models.CharField(verbose_name=u'产品名称', max_length=200)
    enable = models.BooleanField(verbose_name=u'是否在用', default=True,)
    main_image = models.ForeignKey(Upload, verbose_name=u'主图', on_delete=models.SET_NULL, null=True,
                                   related_name='main_image')
    notes = models.CharField(verbose_name=u'备注', max_length=200, null=True,)

    class Meta:
        db_table = "product"
        verbose_name = u"贷款产品"
        ordering = ('-id',)
        default_permissions = ()
        permissions = [
        ]

class ProductImages(models.Model):

    name = models.CharField(verbose_name=u'名称', max_length=200)
    product = models.ForeignKey(Product, verbose_name=u'产品', on_delete=models.PROTECT, related_name='product_images')
    image = models.ForeignKey(Upload, verbose_name=u'图片', on_delete=models.PROTECT)

    class Meta:
        db_table = "product_images"
        verbose_name = u"产品图片"
        ordering = ('id',)
        default_permissions = ()

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的ID')

        instance = ProductImages.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的产品图片')
        return instance

class Order(models.Model):

    category = models.PositiveSmallIntegerField(choices=order.CATEGORY_CHOICES, verbose_name=u"订单类型", default=order.ZERO)
    status = models.PositiveSmallIntegerField(choices=order.STATUS_CHOICES, verbose_name=u"订单状态", default=order.ZERO, editable=False)
    seller = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='order_seller', verbose_name=u"业务人员",
                                    on_delete=models.PROTECT)
    create_user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='order_create_user', verbose_name=u"添加人",
                                    on_delete=models.PROTECT, editable=False)
    create_time = models.DateTimeField(verbose_name=u'添加时间', auto_now_add=True, editable=False)
    cancel_reason = models.CharField(max_length=100, verbose_name=u"未通过原因", null=True, editable=False)

    vmodel = models.CharField(max_length=100, verbose_name=u"车型", null=True)
    invioce = models.CharField(max_length=10, verbose_name=u"车辆发票金额", null=True)

    ptax = models.CharField(max_length=10, verbose_name=u"购置税", null=True)
    insurance = models.CharField(max_length=10, verbose_name=u"保险", null=True)
    boutique = models.CharField(max_length=10, verbose_name=u"精品", null=True)
    wextension = models.CharField(max_length=10, verbose_name=u"延保", null=True)
    upkeep = models.CharField(max_length=10, verbose_name=u"保养", null=True)
    dpratio = models.CharField(max_length=10, verbose_name=u"首付比例", null=True)
    lamount = models.CharField(max_length=10, verbose_name=u"申请贷款金额", null=True)
    laompany = models.ForeignKey(Product, verbose_name=u'贷款产品', on_delete=models.PROTECT)

    name = models.CharField(max_length=10, verbose_name=u"姓名")
    sex = models.PositiveSmallIntegerField(choices=order.GENDER_CHOICES, verbose_name=u"性别", default=order.ZERO)
    bdate = models.DateField(verbose_name=u"出生日期", null=True)
    rpr = models.PositiveSmallIntegerField(choices=order.HUKOU_CHOICES, verbose_name=u"户口", default=order.ZERO)
    nationality = models.PositiveSmallIntegerField(choices=order.NATIONALITY_CHOICES, verbose_name=u"国籍/地区", default=order.ZERO)
    ntype = models.PositiveSmallIntegerField(choices=order.ITYPE_CHOICES, verbose_name=u"身份证件类型", default=order.ZERO)
    inumber = models.CharField(max_length=18, verbose_name=u"身份证件号码", null=True)
    dincome = models.CharField(max_length=10, verbose_name=u"税后收入", null=True)
    mstatus = models.PositiveSmallIntegerField(choices=order.HUNYIN_CHOICES, verbose_name=u"婚姻状况", default=order.ZERO)
    elevel = models.PositiveSmallIntegerField(choices=order.JIAOYU_CHOICES, verbose_name=u"教育程度", default=order.ZERO)
    naddress = models.CharField(max_length=100, verbose_name=u"现居住地址", null=True)
    hptype = models.PositiveSmallIntegerField(choices=order.FAGNCHAN_CHOICES, verbose_name=u"现居住房产类型", default=order.ZERO)
    maddress = models.PositiveSmallIntegerField(choices=order.YOUJI_CHOICES, verbose_name=u"邮寄地址", default=order.ZERO)
    email = models.CharField(max_length=100, verbose_name=u"电子邮箱", null=True)
    wx = models.CharField(max_length=100, verbose_name=u"微信号", null=True)
    phone = models.CharField(max_length=15, verbose_name=u"住宅固定电话", null=True)
    tel = models.CharField(max_length=11, verbose_name=u"手机号")
    wname = models.CharField(max_length=100, verbose_name=u"现工作单位名称", null=True)
    wphone = models.CharField(max_length=15, verbose_name=u"单位电话", null=True)
    waddress = models.CharField(max_length=100, verbose_name=u"现工作单位地址", null=True)
    itype = models.PositiveSmallIntegerField(choices=order.HANGYE_CHOICES, verbose_name=u"行业类型", default=order.ZERO)
    otype = models.PositiveSmallIntegerField(choices=order.ZHIYE_CHOICES, verbose_name=u"职业类型", default=order.ZERO)
    position = models.CharField(max_length=20, verbose_name=u"职位", null=True)

    wbst = models.PositiveSmallIntegerField(choices=order.BOOL_CHOICES, verbose_name=u"是否挂靠", default=order.ONE)
    bstname = models.CharField(max_length=100, verbose_name=u"挂靠公司名称", null=True)
    bstcode = models.CharField(max_length=100, verbose_name=u"挂靠公司组织机构代码", null=True)
    bsttel = models.CharField(max_length=100, verbose_name=u"挂靠公司电话", null=True)
    bstaddress = models.CharField(max_length=100, verbose_name=u"挂靠公司地址", null=True)

    cname = models.CharField(max_length=10, verbose_name=u"联系人1名称", null=True)
    ctel = models.CharField(max_length=11, verbose_name=u"联系人1手机号", null=True)
    relation = models.PositiveSmallIntegerField(choices=order.GUANXI_CHOICES, verbose_name=u"与借款人关系", default=order.ZERO)
    caddress = models.CharField(max_length=100, verbose_name=u"现居住地址", null=True)
    ctname = models.CharField(max_length=10, verbose_name=u"联系人2姓名", null=True)
    cttel = models.CharField(max_length=11, verbose_name=u"联系人2手机号", null=True)

    thesame = models.PositiveSmallIntegerField(choices=order.BOOL_CHOICES, verbose_name=u"是否有共同借款人", default=order.ONE)
    tsname = models.CharField(max_length=10, verbose_name=u"共借人姓名", null=True)
    tsbdate = models.DateField(verbose_name=u"出生日期", null=True)
    tsitype = models.PositiveSmallIntegerField(choices=order.ITYPE_CHOICES, verbose_name=u"身份证件类型", default=order.ZERO)
    tsinumber = models.CharField(max_length=18, verbose_name=u"身份证件号码", null=True)
    tstel = models.CharField(max_length=11, verbose_name=u"手机号", null=True)
    tsrelation = models.PositiveSmallIntegerField(choices=order.GUANXI_CHOICES, verbose_name=u"与借款人关系",
                                                default=order.ZERO)
    tsnaddress = models.CharField(max_length=100, verbose_name=u"现居住地址", null=True)
    tsmaddress = models.PositiveSmallIntegerField(choices=order.YOUJI_CHOICES, verbose_name=u"邮寄地址", default=order.ZERO)
    tsemail = models.CharField(max_length=50, verbose_name=u"电子邮箱", null=True)
    tswx = models.CharField(max_length=20, verbose_name=u"微信号", null=True)
    tswname = models.CharField(max_length=100, verbose_name=u"现工作单位名称", null=True)
    tswphone = models.CharField(max_length=15, verbose_name=u"单位电话", null=True)
    tswaddress = models.CharField(max_length=100, verbose_name=u"现工作单位地址", null=True)
    tsmincome = models.CharField(max_length=10, verbose_name=u"税后月收入", null=True)
    notes = models.CharField(max_length=210, verbose_name=u"备注", null=True)

    class Meta:
        db_table = "order"
        verbose_name = u"订单管理"
        ordering = ('-create_time',)
        default_permissions = ()
        permissions = [
        ]

    def get_path(self, image_type):
        today = datetime.datetime.today()
        year = today.year
        month = today.month
        if month < 10:
            parent_month = '{}-0{}'.format(year, month)
        else:
            parent_month = '{}-{}'.format(year, month)

        return '{}/{}/{}/申请/{}/'.format(parent_month, self.seller.name, self.name, OrderImages.TYPE_CHOICE[int(image_type) -1][1])

    @staticmethod
    def get_instance_by_id(id):
        try:
            id = int(id)
        except:
            raise CustomError('无效的订单ID')
        instance = Order.objects.filter(pk=id).first()
        if not instance:
            raise CustomError('未找到对应的订单')
        return instance

class OrderImages(models.Model):
    ONE = 1
    TOW = 2
    THREE = 3
    FOUR = 4
    FIVE = 5
    SIX = 6
    TYPE_CHOICE = (
        (ONE, '身份证', ),
        (TOW, '驾驶证', ),
        (THREE, '收入类',),
        (FOUR, '流水类',),
        (FIVE, '营业执照', ),
        (SIX, '挂靠协议', ),
    )
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICE, default=ONE)
    order = models.ForeignKey(Order, verbose_name=u'产品', on_delete=models.PROTECT, related_name='order_images')
    image = models.ForeignKey(Upload, verbose_name=u'图片', on_delete=models.SET_NULL, null=True,)
    enable = models.BooleanField(verbose_name=u'是否在用', default=True, )

    class Meta:
        db_table = "order_images"
        verbose_name = u"订单图片"
        ordering = ('id',)
        default_permissions = ()

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的ID')

        instance = OrderImages.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的图片')
        return instance

class OrderDetailEdit(models.Model):
    ZERO = 0
    ONE = 1
    TYPE_CHOICE = (
        (ZERO, '资料'),
        (ONE, '图片'),
    )
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICE, default=ZERO)
    order = models.ForeignKey(Order, verbose_name=u'产品', on_delete=models.PROTECT, related_name='order_detail_edit')
    value = models.CharField(max_length=20, verbose_name=u'订单明细对象值') # 文字资料存自动名称，图片存OrderImages type值
    edit_time = models.DateTimeField(verbose_name=u'修改时间', null=True)
    reason = models.CharField(max_length=200, verbose_name=u'修改原因', null=True)

    class Meta:
        db_table = "order_detail_edit"
        verbose_name = u"订单明细修改"
        ordering = ('id',)
        default_permissions = ()
