# coding=utf-8

from django.db import models

from utils.exceptions import CustomError

from apps.images.models import Images
from apps.vehicle.models import Brand

class Shop(models.Model):
    name = models.CharField(max_length=100, verbose_name=u"名称")
    addr = models.CharField(max_length=1000, verbose_name=u'地址')
    tel = models.CharField(max_length=50, verbose_name=u'电话')
    longitude = models.FloatField(verbose_name=u"经度", null=True)
    latitude = models.FloatField(verbose_name=u"纬度", null=True)
    img = models.ForeignKey(Images, verbose_name=u'图片', on_delete=models.PROTECT, null=True)
    sort = models.PositiveSmallIntegerField(verbose_name=u'排序', help_text=u'越小越靠前', default=0)
    enabled = models.BooleanField(verbose_name=u"在用", default=True)
    is_xgj = models.BooleanField(verbose_name=u'销管佳公司', default=False, editable=False)
    xgj_id = models.IntegerField(verbose_name=u'销管佳id', null=True)
    delete = models.BooleanField(verbose_name=u'删除', default=False, editable=False)

    class Meta:
        db_table = "shop"
        verbose_name = u"门店管理"
        ordering = ['sort', '-id']
        index_together = (
            'name',
            'tel',
        )
        default_permissions = ()

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

        instance = Shop.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的门店信息')
        return instance


class StoreBrand(models.Model):
    store = models.ForeignKey(Shop, verbose_name=u'门店', on_delete=models.PROTECT)
    brand = models.ForeignKey(Brand, verbose_name=u'品牌', on_delete=models.PROTECT)

    class Meta:
        db_table = 'store_brand'
        verbose_name = u'门店品牌'
        default_permissions = ()
