import math
import threading
import pandas as pd
from sqlalchemy import and_, func
from sqlalchemy.orm import Session
from models.recharge import Settlement

locka = threading.Lock()


class GuildSet(object):
    def __init__(self):
        self.settlement_list = []

    def dispose_guild_data(self, db, num):
        guild_list = []
        locka.acquire()
        once_res = db.query(Settlement).filter().offset(num * 10).limit(10).all()
        locka.release()
        for i in once_res:
            info_dict = i.to_dict()
            guild_list.append(info_dict)
        self.settlement_list += guild_list

    def query_guild_data(self, db):
        msg_count = db.query(func.count(Settlement.id)).scalar()
        num = math.ceil(msg_count / 10)
        # 创建线程
        ths = []
        for x in range(num):
            ths.append(threading.Thread(target=self.dispose_guild_data, args=[db, x]))
        for y in range(num):
            ths[y].start()
        for z in range(num):
            ths[z].join()
        return self.settlement_list

    def get_guild_data(self, db: Session, param):
        """公会结算"""
        is_guild_filters = []
        if param.guild_id:
            is_guild_filters.append(Settlement.guild_id == param.guild_id)
        if param.status or param.status == 0:
            is_guild_filters.append(Settlement.status == param.status)
        if param.start_time:
            is_guild_filters.append(Settlement.update_time >= param.start_time)
        if param.end_time:
            is_guild_filters.append(Settlement.update_time <= param.end_time)
        # 判断有无条件
        try:
            if len(is_guild_filters) > 0:
                get_user_orm_sql = db.query(Settlement).filter(and_(*is_guild_filters))
                condition_data = db.execute(get_user_orm_sql).fetchall()
                guild_info = [i[0].to_dict() for i in condition_data]
            else:
                guild_info = self.query_guild_data(db)
        except Exception as e:
            print(e)
            return [], 0
        # 判断是列表还是导出接口
        guild_info.reverse()
        if guild_info:
            return guild_info[(int(param.page) - 1) * param.size:param.size * param.page], len(guild_info)
        return [], 0
