# -*- coding:utf-8 -*-
"""其它杂项数据调用类"""

from kyger.utility import *


class Misc(object):

    # 构造函数
    def __init__(self, db=None, kg=None):
        # 数据库
        from kyger.db import MySQL
        self.db = db if db else MySQL()  # 数据库操作对象
        self.kg = kg  # 全局变量

    def app(self, a):
        """
        查询可用的web应用
        :return: [{应用名: id}, ...]
        """
        return self.db.list("web", "id,name", "enable=1 && id !=%s" % self.kg['web']['id'], '`sort` ASC')

    def navigate(self, nid):
        """
        获取单或多个个导航
        :param nid: [int|list|str] 要获取的导航菜单ID
        :return:
        """
        # 查询类型
        if isinstance(nid, int):
            where = 'webid=%s && id=%s' % (self.kg['web']['id'], nid)
        elif isinstance(nid, list):
            where = 'webid=%s && id in (%s)' % (self.kg['web']['id'], ','.join('%s' % v for v in nid))
        elif nid == "all":
            where = 'webid=%s' % self.kg['web']['id']
        else:
            where = 'webid=%s && aid="%s"' % (self.kg['web']['id'], nid)

        # 查询数据
        menu = self.db.list(
            table='navigation',
            field="id, logo, title, from_unixtime(`addtime`, '%Y-%m-%d %H:%i:%s') as `date`",
            where=where,
            order="id ASC"
        )

        # 对接link表
        if menu:
            link = self.db.list(
                table="link",
                field="*, from_unixtime(`addtime`, '%Y-%m-%d %H:%i:%s') as `date`",
                where='webid=%s && enable=1 && nid in (%s)' % (self.kg['web']['id'], ','.join('%s' % v['id'] for v in menu)),
                order="sort ASC"
            )
            res = {}
            for row in link:
                row['target'] = '_blank' if row['target'] else '_self'
                row['limit_des'] = str_cutting(row['description'], 170)
                if row['nid'] not in res: res[row['nid']] = [row]
                else: res[row['nid']].append(row)
            for row in menu:
                row['link'] = res.get(row['id'], [])
        if len(menu) == 1: menu = menu[0]
        return menu



