#coding=utf-8
import json
import datetime

from django.db import models
from django.utils import timezone
from django.conf import settings

from utils.exceptions import CustomError
from utils.format import strftime, strfdate

class Option(models.Model):
    USED_VEHICLE_BRAND = 0
    MAINT_TYPE = 1
    PRODUCT_CATEGORY = 2
    VEHICLE_GEARBOX = 3
    VEHICLE_COLOR = 4
    VEHICLE_EMISSION = 5
    VEHICLE_DISPLACEMENT = 6
    VEHICLE_SEAT_COUNT = 7
    VEHICLE_OIL = 8

    TYPE_CHOICES = (
        (USED_VEHICLE_BRAND, u'二手车品牌'),
        (MAINT_TYPE, u'服务类型'),
        (PRODUCT_CATEGORY, u'商品类别'),
        (VEHICLE_GEARBOX, u'汽车变速箱'),
        (VEHICLE_COLOR, u'汽车颜色'),
        (VEHICLE_EMISSION, u'汽车排放标准'),
        (VEHICLE_DISPLACEMENT, u'汽车排量'),
        (VEHICLE_SEAT_COUNT, u'汽车座位数'),
        (VEHICLE_OIL, u'汽车燃油类型'),
    )

    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name=u"类别")
    name = models.CharField(max_length=100, verbose_name=u"名称")
    notes = models.CharField(max_length=500, verbose_name=u"备注",blank=True,null=True)
    enable = models.BooleanField(verbose_name=u"在用", default=True)
    delete = models.BooleanField(verbose_name=u"删除", default=False)

    @staticmethod
    def getTypeText(type):
        return Option.TYPE_CHOICES[type][1]

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

        instance = Option.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的自定义项')
        return instance

    @staticmethod
    def getByName(name, type):
        option = Option.objects.filter(name=name,type=type).first()
        if not option:
            raise CustomError(u'未找到[%s]为[%s]的自定义项' % (Option.getTypeText(type),name))
        return option

    class Meta:
        db_table = "system_option"
        verbose_name = u"自定义项管理"
        ordering = ('-id', )
        index_together = (
            'name',
        )
        default_permissions = ()


class BizLogManager(models.Manager):
    def addnew(self, user, type, description, data=None):
        def default(o):
            if isinstance(o, datetime.datetime):
                return strftime(o)
            elif isinstance(o, datetime.date):
                return strfdate(o)

        row = self.model(user=user, type=type, description=description, create_time=timezone.now())
        if data:
            row.data = json.dumps(data, default=default)
        row.save()
        return row

class BizLog(models.Model):
    INSERT = 1
    UPDATE = 2
    DELETE = 3
    CHECK = 4
    EXPORT = 5
    PRINT = 6
    IMPORT = 7
    TYPE_CHOICES = (
        (INSERT, u'添加'),
        (UPDATE, u'修改'),
        (DELETE, u'删除'),
        (CHECK, u'审核'),
        (EXPORT, u'导出'),
        (PRINT, u'打印'),
        (IMPORT, u'导入'),
    )

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True)
    type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES, verbose_name=u"类别")
    description = models.CharField(max_length=1000, verbose_name=u"内容")
    data = models.TextField(verbose_name=u"数据", null=True, blank=True)
    create_time = models.DateTimeField(verbose_name=u"添加时间", auto_now_add=True, editable=False)

    objects = BizLogManager()

    class Meta:
        db_table = "system_log"
        ordering = ['-id']
        verbose_name = u"日志管理"
        default_permissions = ()


class Config(models.Model):
    KEY_WECHAT_APPID = "wechat_appid"  #小程序appid
    KEY_WECHAT_SESSION_KEY = "wechat_session_key" #小程序密钥
    KEY_ABUTMENT_XGJ = "abutment_xgj" # 对接销管佳
    KEY_XGJ_SESSION_KEY = "xgj_session_key" # 销管佳密钥
    KEY_XGJ_IP = "xgj_ip" # 销管佳地址
    KEY_WECHAT_TENANT_NUM = "wechat_tenant_num" # 商户号
    KEY_WECHAT_TENANT_KEY = "wechat_tenant_key" # 商户密钥

    property = models.CharField(max_length=100, verbose_name=u'属性')
    value = models.TextField(verbose_name=u'值')

    class Meta:
        db_table = "system_config"
        verbose_name = u"基础设置"
        index_together = (
            'property',
        )
        default_permissions = ()
        permissions = [
            ('browse_config', u'查看'),
            ('set_config', u'设置'),
        ]

    @staticmethod
    def getConfigValue(property):
        try:
            row = Config.objects.get(property=property)
            return row.value
        except:
            return ''

    @staticmethod
    def getConfigByText(text):
        if text == 'wechat_appid':
            property = Config.KEY_WECHAT_APPID
        elif text == 'wechat_session_key':
            property = Config.KEY_WECHAT_SESSION_KEY
        elif text == 'abutment_xgj':
            property = Config.KEY_ABUTMENT_XGJ
        elif text == 'xgj_session_key':
            property = Config.KEY_XGJ_SESSION_KEY
        elif text == 'xgj_ip':
            property = Config.KEY_XGJ_IP

        try:
            row = Config.objects.get(property=property)
            return row.value
        except:
            return ''
