# -*- coding:utf-8 -*-
"""系统导航"""

from kyger.utility import numeric, mk_time, date, dict2json_file, json2dict, str_replace


class Adminpage(object):
    """系统导航调用"""

    # 构造函数
    def __init__(self, db=None, kg=None):
        # 数据库
        from kyger.db import MySQL
        self.db = db if db else MySQL()  # 数据库操作对象
        self.kg = kg  # 全局变量
        self.__special = {
            "template_manage": ["template_dump", "template_install"],
            "wx_cs_manage": ["wx_cs_group_manage"]
        }

    def list(self, enable=0, current='', id1=0, id2=0, sort=0):
        """
        获取页面方法
        :param enable: [int] 0全部1启用，缺省值0
        :param current: [str] 被选择的页面
        :param id1: [int] 一级ID，0全部其他为id。缺省值0
        :param id2: [int] 二级ID，0全部其他为id，缺省值0
        :param sort: [int] 排序，0sort升，1sort降，2id升，3id降，4添加时间升，5添加时间降
        :return: 返回0、[{}]、{}的数据
        """
        sort_list = {   # 排序
            0: 'sort ASC',
            1: 'sort DESC',
            2: 'id ASC',
            3: 'id DESC',
            4: 'addtime ASC',
            5: 'addtime DESC'
        }

        if id1:  # 一级ID
            data = self.db.list(
                table='adminpage',
                field='name,icon,image',
                where='id = %d && level = 1' % id1,
                shift=1
            )
            if not data: return 0
            where = 'enable = 1 && upper = %d' % id1 if enable else 'upper = %d' % id1
            data['submenu'] = self.db.list(
                table='adminpage',
                field='name,icon,image,page',
                where=where,
                order=sort_list[sort]
            )
        elif id2:  # 二级ID
            data = self.db.list(
                table='adminpage',
                field='name,icon,image,page',
                where='id = %d && level = 2' % id2,
                shift=1
            )
            if not data: return 0
        else:  # 调用一二级
            current = str_replace(current, 'update', 'manage')
            where = 'enable = 1 && level = %d' if enable else 'level = %d'
            lv1 = self.db.list(  # 1级
                table='adminpage',
                field='id,name,icon,image',
                where=where % 1,
                order=sort_list[sort]
            )
            lv2 = self.db.list(  # 2级
                table='adminpage',
                field='name,icon,image,page,upper,plus',
                where=where % 2,
                order=sort_list[sort]
            )
            res = {}
            import copy
            contrast = copy.deepcopy(lv1)
            for var in lv1:  # 1级整理
                id_key = var['id']
                del var['id']
                var['submenu'] = []
                var['current'] = False
                res[id_key] = var
            for var in lv2:  # 二级追加
                upper = var['upper']
                del var['upper']
                if upper in res:
                    if current and (var['page'] == current or (var['page'] in self.__special and current in self.__special[var['page']])):
                        var['current'] = True
                        res[upper]['current'] = True
                        res[upper]['submenu'].append(var)
                    else:
                        var['current'] = False
                        res[upper]['submenu'].append(var)
            data = []
            for var in contrast:
                data.append(res[var['id']])
        return data

    def recent(self, row=0, exclude=["article_manage", "web_statistics_record"]):
        """
        首页调用最近访问
        :param row:
        :param exclude:
        :return:
        """
        access_data = self.db.list(
            table='access',
            field='page,MAX(addtime)',
            where="model = 'admin' && page not in ('%s') GROUP BY page" % "','".join(exclude),
            order='MAX(addtime) ASC',
        )
        adminpage = self.db.list(
            table='adminpage',
            where='level = 2',
        )
        page_list = {}
        for var in adminpage:
            page_list[var['page']] = var
        for var in access_data:
            if var['page'] and var['page'] in page_list:
                del adminpage[adminpage.index(page_list[var['page']])]
                adminpage.insert(0, page_list[var['page']])
        data = adminpage[0:row] if row else adminpage
        return data


