# -*- coding:utf-8 -*-
"""微信调用类"""

from kyger.utility import numeric, json2dict, date, str_cutting
from kyger.common import page_tpl
from kyger.parser_ini import Config


class Search(object):
    # fulltext = False  # 是否全文检索
    is_tag = False  # 返回是否为TAG搜索
    title_length = 0  # 标题字符截取长度，0显示完整标题
    content_length = 100  # 内容截取长度，0显示完整内容
    # max_limit = 10000  限制最大记录数

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

    def data(self, word='', tag=0, type=1, limit=10, category=0, sort=0, all_content=0):
        """
        获取搜索数据
        :param word: [str] 搜索字符，当 TAG 搜索时该参数会被忽略，检索的字段：标题、搜索关键字、TAG，是否检索内容取决于系统设置
        :param tag: [int|str] TAG名称，搜索指定类型下含有该 TAG 的内容，忽略搜索关键字。关键字搜索时请将该值设为 0 或空值
        :param type: [int] 搜索类型：1文章、2产品、3图片、4下载
        :param limit: [int] 每页显示的记录数
        :param category: [int] 搜索指定栏目，0为所有栏目，其它数字为栏目ID
        :param sort: [int] 排序方法，始终以标题中含有关键字的作为第一排序选项，0ID降序、1ID升序、2添加时间降序、3添加时间升序
        :param all_content: [int] 是否全文搜索，0否1是
        """
        # 搜索间隔检测
        config = Config('config/settings.ini').get('user')
        # 获取当前用户数据
        ip = self.kg['server']['HTTP_ADDR']
        access_id = self.kg['cookie'].get('KGCMS_ACCESS_ID', '')
        userid = self.kg['user'].get('user', 0)
        # where
        sql_list = []
        if ip: sql_list.append('ip="%s"' % ip)
        if access_id:sql_list.append('accessid="%s"' % access_id)
        if userid:sql_list.append('user=%s' % userid)
        last = self.db.list(
            table='ipvisit',
            where='type=1 && (%s)' % ' or '.join(sql_list),
            order='addtime DESC',
            shift=1
        )
        if last and (int(self.kg['run_start_time'][1]) - last['addtime']) < config['search_interval']:
            time = config['search_interval'] - (int(self.kg['run_start_time'][1]) - last['addtime'])
            return {'status': 0, 'msg': '查询过于频繁，请%s秒后重试' % time}

        # 查询方式
        if self.is_tag:
            search_sql = '&& tag like "%%%s%%"' % tag
        else:
            content_sql = ' or content like "%%%s%%"' % word
            search_sql = '&& (title like "%%%s%%" or description like "%%%s%%" or keyword like "%%%s%%")' % (word, word, word)
            if all_content: search_sql = search_sql + content_sql

        # 查询类型
        type_list = {
            1: 'article',
            2: 'product',
            3: 'picture',
            4: 'download'
        }

        # 栏目
        category_sql = "&& `category` rlike '[\[|, ]%d[\]|,]'" % category if category else ''

        # 排序
        sort_list = {
            0: 'id DESC',
            1: 'id ASC',
            2: 'addtime DESC',
            3: 'addtime ASC'
        }
        if self.is_tag:
            order = ''
        else:
            order = '`title` like "%%%s%%" DESC, `description` like "%%%s%%" DESC, `keyword` like "%%%s%%" DESC, `content` like "%%%s%%" DESC'

        # where
        if type == 4:
            where = 'recycle=0 && audit=1 %s %s' % (search_sql, category_sql)
        else:
            where = 'recycle=0 && audit=1 && published=1 %s %s' % (search_sql, category_sql)
        page = numeric(self.kg['get'].get('page', 1), 1)
        data = self.db.list(
            table=type_list[type],
            where=where,
            page=page,
            limit=limit,
            order=order % (word, word, word, word) + ',' + sort_list[sort]
        )

        if page > self.db.total_page:
            page = self.db.total_page
            data = self.db.list(
                table=type_list[type],
                where=where,
                page=page,
                limit=limit,
                order=order + ',' + sort_list[sort]
            )

        # 数据整形
        if data:
            data = self.data_format(data, type)

        # 分页数据
        branch = page_tpl(page, self.db.total_page, limit, self.kg['server'].get('WEB_URL'))

        # 搜索记录添加
        insert = {
            'ip': self.kg['server']['HTTP_ADDR'],
            'accessid': self.kg['cookie'].get('KGCMS_ACCESS_ID', ''),
            'user': self.kg['user'].get('id', 0),
            'type': 1,
            'addtime': int(self.kg['run_start_time'][1]),
            'oid': 0,
        }
        self.db.add('ipvisit', insert)
        return {
            'list': data,
            'page_html': branch,
            'page_data': {'page': page, 'total_page': self.db.total_page, 'total_rows': self.db.total_rows}
        }

    def data_format(self, data, type):
        """
        数据整形
        :param data: [str] 要整形的数据
        :param type: [int] 搜索类型：1文章、2产品、3图片、4下载
        """
        # 链接地址
        url_list = {
            1: 'article?id=%s',
            2: 'product?id=%s',
            3: 'photo?id=%s',
            4: 'download?id=%s'
        }

        # 获取栏目标题
        category_title = self.db.list(table='category', field='id, title')
        cate = {}
        for row in category_title:
            cate[row['id']] = row

        # 数据整合
        res = []
        for row in data:
            title = str_cutting(row['title'], self.title_length) if self.title_length else row['title']
            row['category'] = json2dict(row['category'])
            i = {
                'url': url_list[type] % row['id'],
                'pushtime': date(row['pushtime'], '%Y-%m-%d'),
                'category': row['category'],
                'category_title': cate.get(row['id'], {}).get('title', ''),
                'title_format': title,
                'content_format': str_cutting(row['title'], self.content_length),
                'description': str_cutting(row['description'], 170),
                'picture': json2dict(row['picture']),
                'thumbnail': row['thumbnail'],
                'click': row['click']
            }
            res.append(i)
        return res


















