import json
from db.database import mysqlClient
from lib.porxy import PlatformProxy
from log import log

logger = log(__name__)
class Probability(object):
    def __init__(self,box_sn,statistical_date) -> None:
        self.box_sn = box_sn
        self.statistical_date = statistical_date

    async def statistical_query(self):
        # 计算扣费率
        sql = '''
        SELECT res,
                count(id) AS statistical_count,
                CAST(((count(id))/
            (SELECT count(id)
            FROM res_query AS 总数 WHERE _date = %s)) * 100 AS CHAR) AS probability_count
        FROM res_query where _date = %s
        GROUP BY  res;
        '''

        cur = await mysqlClient.execute(sql=sql,param=(self.statistical_date,self.statistical_date))
        qs = await cur.fetchall()
        return qs
    
    async def submit(self,submit_url,data):
        httpPorxy = PlatformProxy()
        try:
            await httpPorxy.post(submit_url, data, timeOut=3)
        except Exception as e:
            logger.error(f"提交时网关异常:{e}")
            return -1

class SubmitProbabilityManager(object):
    def __init__(self,push_url,probability:Probability) -> None:
        self.probability = probability
        self.submit_url = push_url
    
    async def submit(self):
        qs = await self.probability.statistical_query()
        if not qs:return
        data = {
            "statistics_date":self.probability.statistical_date,
            "statistics_res":json.dumps(list(qs)),
            "box_sn":self.probability.box_sn,
        }
        logger.info(f"交易结果统计结果==================>:{data}")
        res = await self.probability.submit(self.submit_url,data)
        return res
        
