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

from pprint import pprint
from datetime import datetime
from application.app import db
from models.user import UserModel
from models.menu import MenuModel
from webcreator.log import logger
from webcreator.response import ResponseCode

class MenuResource(object):
    def __init__(self):
        super().__init__()

    def print_tree(self, group_name, tab=1):
        """
        :param str group_name:要查找的树的根的名称
        :param int tab: 格式化用的-数量
        """
        group = db.session.query(MenuModel).filter_by(name=group_name).one_or_none()
        if not group:
            return
        # group found - print name and find children
        print('- ' * tab + group.name)
        for child_group in group.children:  # type: TreeGroup
            # new tabulation value for child record
            self.print_tree(child_group.name, tab * 2)

    def batch(self, params={}, jwt={}):
        # 如果id里面包含无法转换为数字的字符，那么该接口将会报错
        ids = list(map(lambda x:int(x), params.get("ids").split(",")))

        result = db.session.query(MenuModel).filter(MenuModel.id in ids).delete()
        db.session.commit() # 这是批量删除模式
        logger.info(result)
        return True, ResponseCode.HTTP_SUCCESS

    def updateSort(self, params={}, jwt={}):
        user = db.session.query(UserModel).filter(UserModel.uuid==jwt.get("uuid")).one_or_none()
        if not user:
            return False, ResponseCode.USER_NOT_EXISTS
        
        # 接口字段可能和数据库字段不一致
        result = db.session.query(MenuModel).filter(MenuModel.id==params.get("id")).one_or_none()
        if result:
            sort = 1
            if params.get("direction") == "bottom":
                sort = -1
            result.update_at = datetime.now()
            result.update_by = user.id
            result.sort = result.sort + sort
            db.session.commit()
            return True, ResponseCode.HTTP_SUCCESS
        else:
            return False, ResponseCode.HTTP_NOT_FOUND

    def create(self, params={}, jwt={}):
        user = db.session.query(UserModel).filter(UserModel.uuid==jwt.get("uuid")).one_or_none()
        if not user:
            return False, ResponseCode.USER_NOT_EXISTS
        # 接口字段可能和数据库字段不一致
        extends = MenuModel.fields_mapping()
        data = dict(is_delete=False, sort=0, remarks="")
        data.update({
            'create_by': user.id,
            'create_at': datetime.niw(),
            'update_by': user.id,
            'update_at': datetime.now()
        })
        for k in params.keys():
            if k in extends:
                k[extends[k]] = params[k]
                continue
            if hasattr(MenuModel, k):
                data[k] = params[k]

        if data.get("sort") == 0:
            data.sort = db.session.query(MenuModel).filter().count() + 1
        # 默认设置sort等于表内记录个数
        logger.info(data.sort)
        result = MenuModel(**data)
        db.session.add(result)
        db.session.commit()
        return True, ResponseCode.HTTP_SUCCESS

    def treeList(self, params={}, jwt={}):
        filters = [MenuModel.is_delete==False]
        result = db.session.query(MenuModel).filter(*filters).order_by(MenuModel.sort).order_by(MenuModel.update_at.desc()).all()
        data = []
        if result:
            print(result)
            tab = 1
            for item in result:
                tmp = item.get_tree(session=db.session)
                # print(tmp, tmp.get("node"))
                for tt in tmp:
                    logger.info(tt)
                    logger.info(tt.get("node"))
                # pprint(item.get_tree(session=db.session, json=True))
                pprint(item.get_children(session=db.session))
            #     for child_group in i.children:  # type: TreeGroup
            #         # new tabulation value for child record
            #         self.print_tree(child_group.name, tab * 2)
            # for item in result:
            #     t = item.dict()
            #     data.append(t)
            # return result, ResponseCode.HTTP_SUCCESS
        return data, ResponseCode.HTTP_NOT_FOUND

    def treeNodes(self, params={}, jwt={}):
        filters = [MenuModel.is_delete==False, MenuModel.parent_id==0]
        result = db.session.query(MenuModel).filter(*filters).order_by(MenuModel.sort).order_by(MenuModel.update_at.desc()).all()
        logger.info(result)
        if result:
            return result, ResponseCode.HTTP_SUCCESS
        return None, ResponseCode.HTTP_NOT_FOUND

    def updateById(self, params={}, jwt={}):
        user = db.session.query(UserModel).filter(UserModel.uuid==jwt.get("uuid")).one_or_none()
        if not user:
            return False, ResponseCode.USER_NOT_EXISTS
        # 接口字段可能和数据库字段不一致
        extends = MenuModel.fields_mapping()
        data = dict(is_delete=False)
        data.update({
            'update_at': datetime.now(),
            'update_by': user.id
        })
        for k in params.keys():
            if k in extends:
                k[extends[k]] = params[k]
                continue
            if hasattr(MenuModel, k):
                data[k] = params[k]
        
        logger.info(data)
        # filters = [MenuModel.is_delete==False]
        # result = MenuModel.query.filter(*filters).first()
        result = MenuModel.query.filter(MenuModel.id==params.get("id")).update(data, synchronize_session=False)
        db.session.commit()
        logger.info(result)
        if result:
            return result, ResponseCode.HTTP_SUCCESS
        return None, ResponseCode.HTTP_NOT_FOUND


menuManager = MenuResource()