'''
Author: your name
Date: 2021-07-27 16:19:06
LastEditTime: 2021-07-28 09:23:23
LastEditors: your name
Description: In User Settings Edit
FilePath: \evm-store\tools\build_out\models\menu.py
'''
#!/usr/bin/env python
# -*- coding: utf_8 -*-

from datetime import datetime
from application.app import db
from .base import PrimaryModel
# from sqlalchemy.orm import relationship
from sqlalchemy_mptt.mixins import BaseNestedSets

class MenuModel(PrimaryModel, BaseNestedSets):
    __tablename__ = 'evm_menu'

    id = db.Column(db.Integer, primary_key=True)
    visible = db.Column(db.Boolean)
    name = db.Column(db.String(100), nullable = True)
    # parent_id = db.Column(db.Integer, db.ForeignKey("evm_menu.id"), default=0, nullable = True) # 这句话会由mptt自动插入进去
    path = db.Column(db.String(100), nullable = True)
    disabled = db.Column(db.Boolean, nullable = True, default = False)
    fixed = db.Column(db.Boolean, nullable = False, default = False)
    has_children = db.Column(db.Boolean, nullable = True, default = False)
    icon = db.Column(db.String(100), nullable = True, default = '')
    # create_at = db.Column(db.DateTime, default=datetime.now) # 下面这些被注释的字段，都已经从PrimaryModel继承过来了，无需重写
    # create_by = db.Column(db.String(64))
    # update_at = db.Column(db.DateTime, default=datetime.now)
    # update_by = db.Column(db.String(64))
    # remarks = db.Column(db.String(255), default="")
    # sort = db.Column(db.Integer, default=0)
    # is_delete = db.Column(db.BOOLEAN, default=0)
    # parent = db.Column(db.Integer, db.ForeignKey('evm_menu.id'), index=True)
    # 这句话的含义请百度sqlalchemy表自关联，https://www.jianshu.com/p/fa611ab55dd2
    parent = db.relationship("MenuModel", remote_side=[id], backref="ppp")

    # sqlalchemy_mptt 调优
    # sqlalchemy_mptt 在混入ORM对象时，只对rgt, lft, level 设置了索引，导致每次 CRUD操作都需要从头到尾查找。
    # 经测试，添加tree_id索引大约能快4倍，添加parent_id大约快100倍，加起来就能够满足快速插入的需求了
    # https://www.cnblogs.com/estragon/p/12298128.html
    __table_args__ = (
        db.Index('right_idx', 'rgt'),
        db.Index('left_idx', 'lft'),
        db.Index('level_idx', 'level'),
        db.Index('treeid_idx', 'tree_id'),
        db.Index('parent_idx', 'parent_id'),
    )

    def __init__(self, name=None, parentId=None, path="", disabled=False, fixed=False, hasChildren=False, icon='', is_delete=False, sort=0, remarks=""):
        self.name = name
        self.parent_id = parentId
        self.path = path
        self.disabled = disabled
        self.fixed = fixed
        self.has_children = hasChildren
        self.icon = icon
        self.is_delete = is_delete
        self.sort = sort
        self.remarks = remarks

    def __repr__(self):
        return '<MenuModel %r>' % (self.id)

    @classmethod
    def fields_mapping(self):
        return {
            'parendId': 'parent_id',
            'hasChildren': 'has_children'
        }

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'parentId': self.parent_id,
            'path': self.path,
            'disabled': self.disabled,
            'fixed': self.fixed,
            'hasChildren': self.has_children,
            'icon': self.icon,
            'sort': self.sort,
            'remark': self.remark,
            'deleted': self.is_delete,
            'createUser': self.create_by,
            'updateUser': self.update_by,
            'createTime': self.create_at.strftime("%Y-%m-%d %H:%M:%S") if self.create_at else None,
            "updateTime": self.update_at.strftime("%Y-%m-%d %H:%M:%S") if self.update_at else None,
        }