# -*- coding:utf-8 -*-
"""投票管理数据处理"""

from kyger.utility import *
from urllib import parse
from tools import qrcode, six

class Vote(object):

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

    def get_vote_list(self, word='', titleid=None, sort=2, publisher=None):
        # 主题信息表数据处理
        if titleid:
            where = "`id`=%s" % titleid
            if publisher:
                where = '`id`=%s and `publisher`=%d' % (titleid, numeric(publisher))
            cand_data = self.db.list(
                table='vote_candidate',
                field='*',
                where=where,
                # shift=1
            )
        else:
            # 最新按照id降序
            if sort == 0:order = '`id` DESC'
            # 按照访问量升序
            elif sort == 1:order = '`traffic` ASC'
            # id升序
            elif sort == 3:order = '`id` ASC'
            # 访问量降序
            elif sort == 4:order = '`traffic` DESC'
            # 开始时间升序
            elif sort == 5:order = '`starttime` ASC'
            # 开始时间降序
            elif sort == 6:order = '`starttime` DESC'
            # 按照自定义sort=2
            else:order = '`sort` ASC'
            # 是否搜索
            if word != '':
                where = "`title` LIKE '%%%s%%'" % word
                # 带会员id搜索
                if publisher:
                    where = "`title` LIKE '%%%s%%' and `publisher`=%d" % (word, numeric(publisher))
                cand_datas = self.db.list(
                    table='vote_candidate',
                    field='*',
                    order=order,
                    where=where
                )
                if cand_datas:
                    cand_data = cand_datas
                else:
                    cand_data = []
            # 只带会员id查询
            elif publisher:
                cand_datas = self.db.list(
                    table='vote_candidate',
                    field='*',
                    order=order,
                    where='`publisher`=%d' % numeric(publisher)
                )
                if cand_datas:
                    cand_data = cand_datas
                else:
                    cand_data = []
            else:
                cand_data = self.db.list(
                    table='vote_candidate',
                    field='*',
                    order=order
                )

        # 主题信息处理
        if len(cand_data) != 0:
            for row in cand_data:

                # 进入投票主题code后url
                # 引导用户进入的网页
                redit_url = '%s/vote_sys_mobile?id=%s' % (self.kg['server']['HTTP_HOST'], row['id'])
                code_url = self.weixin.get_basecode(redit_url)
                row['basecode_url'] = code_url
                # 计算候选项
                row['candi'] = len(json2dict(row['candtitle']))
                # 投票人次
                row['numbers'] = sum(json2dict(row['votefalse']))
                row['truenumb'] = sum(json2dict(row['votenumb']))
                # json转列表
                row['image'] = json2dict(row['image'])
                row['candtitle'] = json2dict(row['candtitle'])
                row['photo'] = json2dict(row['photo'])
                row['candtitles'] = json2dict(row['candtitles'])
                row['canddigest'] = json2dict(row['canddigest'])
                row['url'] = json2dict(row['url'])
                row['locking'] = json2dict(row['locking'])
                row['deduct'] = json2dict(row['deduct'])
                row['queue'] = json2dict(row['queue'])
                # 按照编号排序
                queue = row['queue']
                queues = queue[:]
                queues.sort()
                queuesort = []
                length = len(queue)
                for i in range(length):
                    for j in range(length):
                        if queues[i] == queue[j]:
                            queuesort.append(j)
                row['queuesort'] = queuesort

                row['votenumb'] = json2dict(row['votenumb'])
                row['votefalse'] = json2dict(row['votefalse'])
                row['rank'] = json2dict(row['rank'])
                # 按照排名排序
                rank = row['rank']
                ranks = rank[:]
                ranks.sort()
                ranksort = []
                length = len(rank)
                for i in range(length):
                    for j in range(length):
                        if ranks[i] == rank[j]:
                            ranksort.append(j)
                row['ranksort'] = ranksort
                # 时间判断是否投票结束
                starttime = numeric(row['starttime'])
                stoptime = numeric(row['stoptime'])
                nowtime = self.kg['run_start_time'][1]
                # 未开始
                if nowtime < starttime:
                    row['flag'] = 0
                # 已结束
                elif nowtime > stoptime:
                    row['flag'] = 1
                # 进行中
                else:
                    row['flag'] = 2


                # 格式化处理时间
                row['starttime'] = date(row['starttime'], format='%Y-%m-%d %H:%M:%S')
                row['stoptime'] = date(row['stoptime'], format='%Y-%m-%d %H:%M:%S')


                # 扫码
                url = '%s/vote_sys_mobile?id=%s' % (self.kg['server']['HTTP_HOST'], row['id'])
                # url = weixin.get_basecode(url)
                img = qrcode.make(url)  # 创建二维码片
                # 二维码地址
                save_url = 'upload/vote_sys/qrcode/vote_sys_%s.png' % row['id']
                img.save(url_absolute(save_url))
                row['save_url'] = save_url

            # 主题票数排序需要在数据处理之后
            if sort == 7:
                length = len(cand_data)
                for i in range(length):
                    for j in range(i + 1, length):
                        if cand_data[i]['numbers'] < cand_data[j]['numbers']:
                            cand_data[i], cand_data[j] = cand_data[j], cand_data[i]

            if sort == 8:
                length = len(cand_data)
                for i in range(length):
                    for j in range(i + 1, length):
                        if cand_data[i]['numbers'] > cand_data[j]['numbers']:
                            cand_data[i], cand_data[j] = cand_data[j], cand_data[i]
            # 候选项票数排序
            if sort == 9:
                length = len(cand_data)
                for i in range(length):
                    for j in range(i + 1, length):
                        if cand_data[i]['numbers'] < cand_data[j]['numbers']:
                            cand_data[i], cand_data[j] = cand_data[j], cand_data[i]
            # 候选项编号排序
        return cand_data

    def user_data_format(self, ids=''):
        # 用户数据,用户投票表数据处理
        if ids != '':
            user_data = self.db.list(
                table='vote_user',
                field='*',
                order='`id` DESC',
                where='`titleid`=%s' % ids
            )
        else:
            user_data = self.db.list(
                table='vote_user',
                field='*',
                order='`id` DESC',
            )
        # 数据处理
        for row in user_data:
            if row['fansid'] != 0:
                fans_data = self.db.list(
                    table='wx_fans',
                    field='nickname, openid, headimgurl',
                    where='id=%s' % row['fansid'],
                    shift=1
                )
                if fans_data:
                    row['headurl'] = fans_data['headimgurl']
                    row['nickname'] = parse.unquote(fans_data['nickname'])
                    row['openid'] = fans_data['openid']
                    row['username'] = ''
                    row['phone'] = ''
            if row['kgid'] != 0:
                kg_data = self.db.list(
                    table='user',
                    field='nickname, phone',
                    where='`id`=%s' % row['kgid'],
                    shift=1,
                )
                if kg_data:
                    row['username'] = kg_data['nickname']
                    row['phone'] = kg_data['phone']

            if row['titleid'] != '':
                vote_data = self.db.list(
                    table='vote_candidate',
                    field='title, candtitle',
                    where='`id`=%d' % numeric(row['titleid']),
                    shift=1,
                )
                row['titlename'] = vote_data['title']
                candid = row['candid']
                row['candtitle'] = json2dict(vote_data['candtitle'])[candid]
            row['votetime'] = date(row['votetime'], format='%Y-%m-%d %H:%M:%S')
        return user_data
