# -*- coding:utf-8 -*-
"""文章页面"""

from kyger.utility import *


class Category(object):
    """文章调用"""
    # 构造函数
    def __init__(self, db=None, kg=None):
        # 数据库
        from kyger.db import MySQL
        self.db = db if db else MySQL()
        self.kg = kg
        self.__data = []

    def list(self, cid=None, level=0, row=0, display=1):
        """
        获取栏目结构
        :param cid: [int|str] 所属栏目或模块，0所有栏目/其它数字为栏目ID，将调用指定栏目下的所有子栏目。/article文章/product产品/picture图集。缺省值为None
        :param level: [int] 调用几级分类，0全部级别/其它数字为调用的级别数，如：只调用一级分类时可设置为1。缺省值为0
        :param row: [int] 调用记录数，0全部，其它数字为调用的记录数。缺省值为0
        :param webid: [int] 所属的应用id，0调用全部，其他为调用webid。缺省值0
        :return:
        """
        # 唯一模块
        module_sum = self.db.list(table='category', field='module,count(*)', where='webid=%s && level=1 && enable=1 group by module' % self.kg['web']['id'])
        single_module = []
        for var in module_sum:
            if var['count(*)'] == 1: single_module.append(var['module'])

        where = 'webid=%s && enable=1 && display=%d' % (self.kg['web']['id'], display)
        if level:
            if row: data = self.db.list(table="category", where=where + '&& level=%s' % level, limit='0,%s' % row, order='level ASC, sort ASC')
            else: data = self.db.list(table="category", where=where + '&& level=%s' % level, order='level ASC, sort ASC')
        else:
            if not cid: cid = 0  # 没有传值设为0
            if isinstance(cid, str):
                if row: data = self.db.list(table="category", where=where + '&& module="%s"' % cid, order='level ASC, sort ASC', limit='0,%s' % row)
                else:  data = self.db.list(table="category", where=where + '&& module="%s"' % cid, order='level ASC, sort ASC')
            elif isinstance(cid, int):
                if row: data = self.db.list(table="category", where=where + "&& `upper` rlike '[\[|, ]%s\]'" % cid, order='level ASC, sort ASC', limit='0,%s' % row)
                else:
                    data = self.db.list(table="category", where=where + "&& `upper` rlike '[\[|, ]%s\]'" % cid, order='level ASC, sort ASC')
                    
                if not data:
                    upper = self.db.list(table='category', field='upper', where=cid, shift=1)
                    # data = self.db.list(table='category', where='webid=%s && upper like "%s"' % (self.kg['web']['id'], upper.get('upper', [])), order='level ASC, sort ASC')
                    # 20200612:zyy:改为如下
                    data = self.db.list(table='category', where=where + '&& upper like "%s"' % upper.get('upper', []), order='level ASC, sort ASC')
            else: data = []
        if data:
            for var in data:
                var['title'] = str_cutting(var['title'], 21)  # 截取长度
                if var['template']:
                    var['url'] = str_replace(var['template'], '.tpl', '')
                else:
                    if var['module'] in single_module and var['level'] == 1:
                        var['url'] = var['module']
                    else:
                        var['url'] = var['module'] + '?cid=%s' % var['id']
        
        return data

    def rank(self, cid=None):
        """
        获取栏目结构
        :param cid: [int|str] 所属栏目或模块，0所有栏目/其它数字为栏目ID，将调用指定栏目下的所有子栏目。/article文章/product产品/picture图集。缺省值为None
        :return:
        """

        if isinstance(cid, str):
            data = self.db.list(
                table="category",
                where='webid=%s && module="%s"' % (self.kg['web']['id'], cid),
                order='level ASC, `sort` DESC'
            )
        elif isinstance(cid, int):
            cid_data = self.db.list(table='category', where=numeric(cid, 0), shift=1)  # 获取该栏目的信息
            if cid_data:
                cid_sql = "&& `upper` rlike '[\[|, ]%d[\]|,]'" % numeric(cid, 0) if numeric(cid, 0) else ''
                data = self.db.list(
                    table='category',
                    where='webid=%s ' % self['web']['id'] + cid_sql,
                    order='level ASC, `sort` DESC'
                )
                data.insert(0, cid_data)
            else: data = []
        else:
            data = self.db.list(
                table='category',
                where='webid=%s' % self.kg['web']['id'],
                order='level ASC, `sort` DESC'
            )

        res = {}
        for row in data:
            row['upper'] = json2dict(row['upper'])  # 转json
            row['lower'] = []  # 添加下级key
            res[row['id']] = row
        for var in data:
            if var['level'] == data[0]['level']:
                self.__data.append(var)
            else:
                index = self.__data.index(res[var['upper'][var['level']-2]])
                self.__data.insert(index+1, var)

        for row in self.__data:
            row['title'] = str_cutting(row['title'], 21)
        return self.__data


