from django.db import models
from django.contrib.auth.models import AbstractUser
import re 


class Role(models.Model):
    id = models.AutoField(primary_key=True)
    role_name = models.CharField(u'角色名称',max_length=100, default='')  # 角色名称
    role_message = models.TextField(u'角色描述', default='')  # 设备描述
    role_perm = models.TextField(u'角色拥有的权限', default='')  # 角色拥有的权限
    role_status = models.PositiveIntegerField(default=1)  # 角色状态 0被删除 1正常
    addtime = models.PositiveIntegerField(default=0)  # 添加时间
    uptime = models.PositiveIntegerField(default=0)  # 角色修改时间
    mark = models.TextField("备注", max_length=64, default="")
    add_by = models.PositiveIntegerField(u'创建人', null=True, blank=True, default=None)   # 创建人，如果为空则是管理员创建，或者后续全部添加上。

    class Meta:
        db_table = "sa_role"


class Purview(models.Model):
    id = models.AutoField(primary_key=True)
    parent_perm_id = models.PositiveIntegerField(u'父级权限',default=0)  # 父级权限id
    purview_name = models.CharField(u'权限名称',max_length=100, default='')
    path = models.CharField(u'接口标识',max_length=100, default='')
    menu = models.CharField(u'菜单标识',max_length=100, default='')
    addtime = models.PositiveIntegerField(default=0)  # 添加时间
    uptime = models.PositiveIntegerField(default=0)  # 修改时间
    url = models.TextField(u'页面路由',default=0)  # 修改时间
    enable = models.BooleanField(verbose_name="是否启用", default=True)
    priority = models.IntegerField(verbose_name="排序优先级，整数0最小", default=0)

    class Meta:
        db_table = "sa_purview"


class UserPurview(models.Model):
    id = models.AutoField(primary_key=True)
    parent_perm_id = models.PositiveIntegerField(u'父级权限',default=0)  # 父级权限id
    purview_name = models.CharField(u'权限名称',max_length=100, default='')
    path = models.CharField(u'接口标识',max_length=100, default='')
    menu = models.CharField(u'菜单标识',max_length=100, default='')
    addtime = models.PositiveIntegerField(default=0)  # 添加时间
    uptime = models.PositiveIntegerField(default=0)  # 修改时间
    url = models.TextField(u'页面路由',default=0)  # 修改时间

    class Meta:
        db_table = "sa_user_purview"


class MongoMenuPerGroupModel(models.Model):
    name = models.CharField(verbose_name="权限组名称", max_length=20)
    menus = models.TextField(verbose_name="菜单id列表")
    uid = models.IntegerField(verbose_name="创建用户uid")
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    modify_time = models.DateTimeField(verbose_name="修改时间", auto_now=True)

    class Meta:
        db_table = "sa_menu_per_group"
        unique_together = ("name", "uid")


class MongoUserMenuPerGroupModel(models.Model):
    uid = models.IntegerField(verbose_name="用户uid", unique=True)
    menus = models.TextField(verbose_name="菜单id列表")
    group_ids = models.CharField(verbose_name="权限组id列表", max_length=256)

    class Meta:
        db_table = "sa_user_menu_per_group"


class DeviceUser(models.Model):
    TAG_CHOICES = [
        (1, "专业用户"),
        (2, "销售用户"),
        (3, "普通用户")
    ]

    USER_TYPE_CHOICES = [
        (1, "超级管理员"),
        (2, "经销商"),
        (3, "农林政府单位"),
        (4, "普通用户"),
        (5, "销售用户")
    ]

    USER_TYPE_LIST = [i[0] for i in USER_TYPE_CHOICES]

    user_tag = models.IntegerField(verbose_name="用户分类", choices=TAG_CHOICES, default=3)
    uid = models.PositiveIntegerField(default=0,unique=True)  # 用户User表 关联表
    role_id = models.PositiveIntegerField(default=0)  # 用户对应角色id
    mobile = models.CharField(max_length=15, default='')  # 手机号 ，有些账号没有手机号，不能设置唯一键，唯一性验证在逻辑中做
    username_change_times = models.PositiveIntegerField(default=0)  # 登录账号修改次数
    email = models.EmailField(max_length=80, default='')  # 有些账号没有绑定邮箱，不能设置唯一键， 唯一性验证在逻辑中做
    real_name = models.CharField(max_length=100, default='')  # 昵称
    image = models.CharField(max_length=100, default='')  # 用户头像
    state = models.PositiveIntegerField(default=1)  # 状态 1正常 4禁止使用
    province = models.CharField(u'设备归属  省', max_length=50, default='')  # 设备归属  省
    city = models.CharField(u'设备归属  市', max_length=50, default='')  # 设备归属  市
    district = models.CharField(u'设备归属 县', max_length=50, default='')  # 设备归属 县
    remark = models.TextField(u'用户备注',default='')
    regiest_source = models.PositiveIntegerField(default=0)  # 上级代理商的id
    login_time = models.PositiveIntegerField(default=0)  # 登陆时间
    user_type = models.PositiveIntegerField(default=4)  # 用户对应的类型 1超级管理员  2经销商  3农林政府单位  4普通用户  5 销售用户
    user_area = models.CharField(u'用户区域', max_length=50, default='')  # 当用户类型为3农林政府单位的时候 必须存在
    package_time = models.PositiveIntegerField(default=60*60*24*365)  # 套餐时间
    addtime = models.PositiveIntegerField(default=0)  # 添加时间
    uptime = models.PositiveIntegerField(default=0)  # 修改时间
    user_group_id = models.PositiveIntegerField(default=0)  # 用户组id
    tets_user = models.PositiveIntegerField(default=0)  # 区分是否为测试用户  测试用户1
    children_num = models.PositiveIntegerField(default=0)  # 用户为代理商的时候可创建子账户数量
    identify_model = models.CharField(max_length=5,default='A')  # 用户默认使用的识别模型
    user_purviews = models.TextField(u'角色拥有的用户权限')  # 角色拥有的权限
    user_purviews_init = models.BooleanField("是否初始化用户权限", default=False)   # 是否初始化用户权限，只有在专业用户情况下使用
    sms_count = models.PositiveIntegerField(default=100) # 用户可发送免费短信次数
    pay_sms_count = models.PositiveIntegerField(default=0)  # 用户充值短信次数
    other_uuid = models.CharField(verbose_name="第三方登陆对接用户唯一标识", max_length=512, default="")
    other_type = models.CharField(verbose_name="第三方登陆用户类型标识", max_length=16, default="")
    user_attribute = models.IntegerField(verbose_name="用户属性，0 表示标准用户，1 表示中性用户", default=0)
    api_token = models.CharField(verbose_name="用户调用接口令牌", max_length=32, default="")

    class Meta(AbstractUser.Meta):
        db_table = "sa_device_user"

    def perm(self, uid):
        "获取用户的权限信息"
        try:
            mp = MongoUserMenuPerGroupModel.objects.get(uid=uid)
            role_perm = mp.menus
        except Exception as e:
            role_perm = Role.objects.get(role_status=1, id=self.role_id).role_perm

        if not role_perm:
            return ''
        if role_perm == 'all':
            return 'all'

        role_perm = re.split(',|，', role_perm)
        role_perm = [int(i) for i in role_perm if i]
        purviews = Purview.objects.filter(id__in=role_perm, enable=True)
        paths = [str(i.path).strip() for i in purviews]
        return str(paths)


class MongoOtherUserTypeModel(models.Model):
    other_name = models.CharField(u'其他用户公司名称', max_length=50)
    other_type = models.CharField(u'公司标志', max_length=50)

    class Meta:
        db_table = "sa_other_user_type"
        unique_together = ('other_name', 'other_type')


class MongoUserSaleDevice(models.Model):
    """销售卖出去的设备表"""
    uid = models.PositiveIntegerField(verbose_name="用户UID")
    device_id = models.CharField(u'设备本身id',max_length=50, unique=True)

    class Meta:
        db_table = "sa_user_sale_device"


class MongoUserUploadsPictures(models.Model):
    """用户调用识别接口图片信息记录"""
    uid = models.PositiveIntegerField(u'用户ID',default=0)
    addr = models.CharField(u'原图路径', max_length=200, default='')
    indentify_photo = models.CharField(u'识别图路径', max_length=200, default='')
    indentify_result = models.CharField(max_length=100,default='')
    addtime = models.IntegerField(u'上传时间戳秒级',default=0)
    interface = models.CharField(max_length=50,default='')

    class Meta:
        db_table = "user_uploads_pictures"


class MongoUserLoginLog(models.Model):
    "登录日志表"
    id = models.AutoField(primary_key=True)
    uid = models.PositiveIntegerField(default=0)
    ip = models.GenericIPAddressField(default='')
    addtime = models.PositiveIntegerField(default=0)
    device_type = models.PositiveIntegerField(default=0)  # 设备类型 0 网页版

    class Meta:
        db_table = "sa_user_login_log"


class MongoOperateLogs(models.Model):
    id = models.AutoField(primary_key=True)
    uid = models.PositiveIntegerField(u'操作用户id',default=0)
    target_id = models.CharField(u'被操作目标id',max_length=100,default='')
    content = models.CharField(u'操作内容', max_length=500)
    operation_type = models.PositiveIntegerField(u'操作类型对设备操作为0 对用户操作为1',default=0)
    ip = models.CharField(u'操作者ip', max_length=100)
    addtime = models.IntegerField(default=0)  # 新增时间

    class Meta:
        db_table = "sa_operate_logs"


class MongoUserDeviceOrderModel(models.Model):
    uid = models.IntegerField(u'负责人uid', default=0)
    device_id = models.CharField(u'设备id', max_length=50)
    order = models.IntegerField(u'排序字段', default=0)
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    class Meta:
        db_table = "sa_user_device_order"


class HomeThemeModel(models.Model):
    id = models.AutoField(primary_key=True)
    logo_url = models.TextField(verbose_name="logo_url", null=True, blank=True, default="")
    title_name = models.CharField(verbose_name="标题名称", max_length=50, blank=False, null=False)
    copyright = models.TextField(verbose_name="版权信息", null=True, blank=True, default="")
    create_time = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    class Meta:
        db_table = "sa_theme_home_theme"
        verbose_name = "首页主题表"