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

from kyger.utility import *
from kyger.parser_ini import Config


class Comment(object):
    """文章调用"""
    __page = 0  # 当前页
    __total_page = 0  # 总页数
    __total_rows = 0  # 总记录数

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

    def page_list(self, *args, **kwargs):
        """
        分页 参数同list
        :return:
        """
        self.page = numeric(self.kg['get'].get('page', 1), 1)
        if 'rows' in kwargs:
            row = kwargs['rows']  # 在kwargs里
        elif len(args) > 3:
            row = args[3]  # 在args里
        else:
            row = 10  # 默认10

        # 获取文章数据
        data = self.list(*args, **kwargs)
        # 分页模板合成
        web_url = self.kg['server'].get('WEB_URL')
        from kyger.common import page_tpl
        page_html = page_tpl(self.__page, self.__total_page, row, web_url)  # 获取分页模板

        return {
            'list': data,
            'page_html': page_html,
            'page_data': {'page': self.__page, 'total_page': self.__total_page, 'total_rows': self.__total_rows}
        }

    def list(self, type, aid, sort=0, rows=10, start=0, time='%Y-%m-%d %H:%M:%S'):
        """
        获取文章数据
        :param type: [int] 0所有,1文章内容,2产品评论,3图片集评论,4下载评论
        :param aid: [int] 0不限制,相关ID(与类型相关联的ID号例如：文章内容id、商品内容id)
        :param sort: [int] 排序，,0点赞降序，1时间降序，2时间升序
        :param rows: [int] 获取几条,默认两条
        :param start: [int] 从第几条数据开始调用，缺省值0
        :param time: [str] 日期格式化：
                                %y 两位数的年份表示（00-99）  %Y 四位数的年份表示（000-9999）  %m 月份（01-12）  %d 日，月内中的一天（0-31）
                                %H 24小时制小时数（0-23）  %I 12小时制小时数（01-12）  %M 分钟数（00=59）  %S 秒（00-59）
                                %a 本地简化星期名称  %A 本地完整星期名称 %b 本地简化的月份名称, 英文  %B 本地完整的月份名称, 英文
                                %c 本地相应的日期表示和时间表示  %j 年内的一天（001-366）  %p 本地A.M.或P.M.的等价符  %U 一年中的星期数（00-53）星期天为星期的开始（第n周）
                                %w 星期（0-6），星期天为星期的开始  %W 一年中的星期数（00-53）星期一为星期的开始（第n周）   %x 本地相应的日期表示
                                %X 本地相应的时间表示  %Z 当前时区的名称  %% %号本身
        :return:{
        }
        """
        # where条件的处理
        type_sql = ' && a.type=%s' % type
        aid_sql = ' && a.aid=%s' % aid
        where = "a.webid=%s && a.theme=0 && a.audit=1%s%s" % (self.kg['web']['id'], type_sql, aid_sql)

        # 排序
        sort_param = {
            0: 'a.agree DESC',
            1: 'a.addtime DESC',
            2: 'a.addtime ASC'
        }
        userid = self.kg['user'].get('id', 0)
        user_sort = 'a.user=%s DESC, ' % userid if userid else ''

        # 获取数据
        limit = rows if self.page else '%s,%s' % (start, rows)
        data = self.db.list(
            table="%scomment a left join %suser b on a.user = b.id" % (self.db.cfg["prefix"], self.db.cfg["prefix"]),
            field="a.*, b.username, b.image",
            where=where,
            page=self.page,
            order=user_sort + sort_param[sort],
            limit=limit
        )
        if self.page > self.db.total_page:
            self.page = self.db.total_page
            data = self.db.list(
                table="%scomment a left join %suser b on a.user = b.id" % (self.db.cfg["prefix"], self.db.cfg["prefix"]),
                field="a.*, b.username, b.image",
                where=where,
                page=self.page,
                order=user_sort + sort_param[sort],
                limit=limit
            )

        self.__page, self.__total_page, self.__total_rows = (self.db.page, self.db.total_page, self.db.total_rows)

        # 数据整形
        theme_id = []
        for row in data:
            row['interval'] = time_check(row['addtime'], int(self.kg['run_start_time'][1]))
            row['addtime'] = date(row['addtime'], time)
            row['picture'] = json2dict(row['picture'])
            theme_id.append(str(row['id']))

        if data:
            # 获取和主题帖相关的数据
            quote = self.db.list(
                table="comment",
                field='count(*), theme',
                where="audit=1 && theme in (%s) group by theme" % (','.join(theme_id))
            )
            quote_dict = {}
            for row in quote:
                quote_dict[row['theme']] = row['count(*)']

            # 获取点赞记录数据
            ip = self.kg['server']['HTTP_ADDR']
            access_id = self.kg['cookie'].get('KGCMS_ACCESS_ID', '')
            userid = self.kg['user'].get('id', 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)
            agree_list = self.db.list(
                table='ipvisit',
                where='type=11 && oid in (%s) && (%s)' % (','.join(theme_id), ' or '.join(sql_list)),
            )
            already_agree_list = []
            for row in agree_list:
                already_agree_list.append(row['oid'])

            # 回复数目
            r_data = []
            theme_index = 0
            for row in data:
                row['already_agree'] = 1 if row['id'] in already_agree_list else 0
                row['count'] = quote_dict.get(row['id'], 0)
                if userid and userid == row['user']:
                    r_data.insert(theme_index, row)
                    theme_index += 1
                else:
                    r_data.append(row)
            data = r_data

        return data

    def get_quote(self, theme, page, rows=10):
        """
        获取回复内容
        :param theme: [int] 主题id
        :param page: [int] 获取第几页
        :param rows: [int] 每页获取多少条
        :return:
        """
        # 获取点赞记录数据
        ip = self.kg['server']['HTTP_ADDR']
        access_id = self.kg['cookie'].get('KGCMS_ACCESS_ID', '')
        userid = self.kg['user'].get('id', 0)
        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)
        agree_list = self.db.list(
            table='ipvisit',
            where='type=11 && (%s)' % ' or '.join(sql_list),
        )
        already_agree_list = []
        for row in agree_list:
            already_agree_list.append(row['oid'])

        # 获取回复
        quote = self.db.list(
            table="%scomment a left join %suser b on a.user = b.id" % (self.db.cfg["prefix"], self.db.cfg["prefix"]),
            field="a.*, b.username, b.image",
            where="theme=%s" % theme,
            order="addtime ASC",
        )

        # 数据整形
        r_data = []
        insert_index = 0
        quote_dict = {}
        for row in quote:
            row['interval'] = time_check(row['addtime'], int(self.kg['run_start_time'][1]))
            row['addtime'] = date(row['addtime'], '%Y-%m-%d %H:%M:%S')
            row['picture'] = json2dict(row['picture'])
            quote_dict[row['id']] = row
            # 点赞判断
            row['already_agree'] = 1 if row['id'] in already_agree_list else 0
            # 是否为2级回复
            if row['theme'] == row['quote']:
                row['touser'] = ''
                # 当前登录用户回复提前
                if row['user'] == userid:
                    r_data.insert(insert_index, row)
                    insert_index += 1
                else:
                    r_data.append(row)
            else:
                row['touser'] = '//@%s：%s' % (quote_dict[row['quote']]['nickname'], quote_dict[row['quote']]['content'])
                r_data.append(row)
        total_page = (len(r_data) // rows) + 1 if len(r_data) % rows else len(r_data) // rows
        if page > total_page: page = total_page
        return {
            "comment": r_data[(page - 1) * rows: page * rows],
            "total_page": total_page,
            "page": page
        }

    def insert(self, type, aid, content, quote=0, theme=0, star=0):
        """
        评论写入函数
        :param type: [int] 1文章内容,2产品评论,3图片集评论,4下载评论
        :param aid: [int] 相关ID(与类型相关联的ID号例如：文章内容id、商品内容id)
        :param content: [str] 评论的内容
        :param quote: [int] 回复的评论id
        :param theme: [int] 所属的主题帖
        :param star: [int] 星级
        :return:
        """
        # 获取配置文件
        config = Config('config/settings.ini').get('user')

        # 评论限制检查
        comment_type = [7, 8, 9, 10]
        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=%s && oid=%s && (%s)' % (comment_type[type - 1], aid, ' or '.join(sql_list)),
            order='addtime DESC',
            shift=1
        )
        if last and (int(self.kg['run_start_time'][1]) - last['addtime']) < config['comment_interval'] * 60:
            time = config['comment_interval'] * 60 - (int(self.kg['run_start_time'][1]) - last['addtime'])
            return {'status': 0, 'msg': '评论过于频繁，请%s分钟后重试' % ((time // 60) + 1)}

        # 判断是不是回复自己，回复自己重开一层
        # if quote:
        #     quote_data = self.db.list(table='comment', where=quote, shift=1)
        #     if quote_data['user'] == self.kg['user']['id']: quote, theme = (0, 0)
        # 插入数据整形
        import re
        if self.kg['user'].get('nickname', ''):
            nickname = self.kg['user']['nickname']
        elif self.kg['user'].get('username', ''):
            nickname = self.kg['user'].get('username', '')
        else:
            if config['comment_traveler'] == 0: return {"status": 0, 'msg': '不允许游客评论'}
            nickname = '游客'

        # 对评论内容进行过滤处里
        content = html_escape(content)
        content = str_replace(content, ['SELECT', 'select', 'where', 'WHERE'], '')
        picture = re.findall(r'<img.*?src="(.*?)".*?>', content)
        address = ip2address(self.db, self.kg['server']['HTTP_ADDR'])
        data = {
            'webid': self.kg['web']['id'],
            'type': type,
            'aid': aid,
            'agree': 0,
            'quote': quote,
            'content': content,
            'audit': config['comment_audit'],
            'ip': self.kg['server']['HTTP_ADDR'],
            'address': '-'.join([address['country'], address['province'], address['city']]),
            'user': self.kg['user'].get('id', 0),
            'nickname': nickname,
            'picture': json2dict(picture),
            'star': star,
            'theme': theme,
            'addtime': int(self.kg['run_start_time'][1])
        }
        res = self.db.add('comment', data)
        if res:
            # 评论数加一
            tables = ['article', 'product', 'picture', 'download']
            data = self.db.list(table=tables[type-1], where=aid, shift=1)
            self.db.edit(tables[type-1], {'commenttotal': data.get('commenttotal', 0) + 1}, data.get('id', 0))

            # 会员积分增加
            if self.kg['user'].get('id'):
                last = self.db.list(
                    table='ipvisit',
                    where='type in (7,8,9,10) && user=%s' % self.kg['user']['id'],
                    order='addtime DESC',
                    shift=1
                )
                if int(self.kg['run_start_time'][1]) - last.get('addtime', 0) > 43200:
                    r = self.db.list(table='user', where=self.kg['user']['id'], shift=1)
                    self.db.edit('user', {'scores': r['scores'] + config['comment_scores']}, self.kg['user']['id'])

            # 评论记录插入
            insert = {
                'ip': self.kg['server']['HTTP_ADDR'],
                'accessid': self.kg['cookie'].get('KGCMS_ACCESS_ID', ''),
                'user': self.kg['user'].get('id', 0),
                'type': comment_type[type-1],
                'addtime': int(self.kg['run_start_time'][1]),
                'oid': aid
            }
            self.db.add('ipvisit', insert)
            comment_data = self.db.list(
                table="%scomment a left join %suser b on a.user = b.id" % (self.db.cfg["prefix"], self.db.cfg["prefix"]),
                field="a.*, b.username, b.image",
                where='a.id=%s' % res,
            )
            data = {"status": 1, 'msg': '评论成功', 'audit': config['comment_audit'], 'comment': comment_data}
        else:
            data = {"status": 0, 'msg': '评论失败请稍后再试'}
        return data

    def agree(self, id):
        """
        点赞
        :param id: [int] 要点赞的评论id
        :return:
        """
        # 判断是否已为该id点赞
        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=11 && oid=%s && (%s)' % (id, ' or '.join(sql_list)),
            shift=1
        )
        data = self.db.list(table='comment', where=id, shift=1)
        if last:
            self.db.edit('comment', {'agree': data['agree'] - 1}, id)
            # 删除点赞记录
            self.db.dele('ipvisit', 'type=11 && oid=%s && (%s)' % (id, ' or '.join(sql_list)))
            return {'status': 1, 'agree': data['agree'] - 1, 'action': 'against'}
        else:
            self.db.edit('comment', {'agree': data['agree'] + 1}, id)
            insert_data = {
                "ip": ip,
                "accessid": access_id,
                "user": userid,
                "type": 11,
                "addtime": int(self.kg['run_start_time'][1]),
                "oid": id
            }
            # 写记录点赞
            self.db.add('ipvisit', insert_data)
            return {'status': 1, 'agree': data['agree'] + 1, 'action': 'agree'}




