from .base import BaseHandler
from src.confirm_orders import Reconciliation
from db.database import mysqlClient,mongoClient
from log import log
logger = log(__name__)

class TestHandler(BaseHandler):
    def get(self):
        return self.write_resp200("hello,world")

class BookKeepHandler(BaseHandler):
    async def post(self):
        data = self.json()
        item = data.get("item")
        content = data.get("content")
        try:
            _id = await mysqlClient.insert("book_keep",item)
            logger.info(f"id:{_id}")
        except Exception as e:
            logger.error(f"记账异常item:{e}")
            return self.write_resp500("服务器内部异常")

        order = {
            "_id":_id,
            "payNo":item["payNo"],
            "transNumber":item["transNumber"],
            "content":content
        }

        try:
            mongoClient.insert('book_keep_content','order',order)
        except Exception as e:
            logger.error(f"记账异常content:{e}")

        return self.write_resp200(_id)

class BookKeepQueryHandler(BaseHandler):
    async def post(self):
        data = self.json()
        field = data.get("field")
        where = data.get("where")
        try:
            qs = await mysqlClient.query(table="book_keep",field=field,where=where) #订单编号信息list
        except Exception as e:
            logger.error(f"查询记账异常:{e}")
            return self.write_resp500("服务器内部异常")

        payNoList = [item["payNo"] for item in qs]

        #在mongodb中查询金额信息
        db = mongoClient.client["book_keep_content"]
        doc = db["order"]
        qs = doc.find({"payNo":{"$in":payNoList}},{"payNo":1,"content.fee":1})
        return self.write_resp200(list(qs))


class UpdateKeepHandler(BaseHandler):
    async def post(self):
        data = self.json()
        update = data.get("data")
        where = data.get("where")
        try:
            row = await mysqlClient.update("book_keep",data=update,where=where)
        except Exception as e:
            logger.error(f"更改记账状态异常:{e}")
            return self.write_resp500("服务器内部异常")
        return self.write_resp200(row)



class FailedTransactionSaveHandler(BaseHandler):
    async def post(self):
        data = self.json()
        item = data.get("item")
        content = data.get("content")
        try:
            _id = await mysqlClient.insert("trans_failed",item)
        except Exception as e:
            logger.error(f"记录交易源数据item异常:{e}")
            return self.write_resp500("服务器内部异常")
        order = {
            "_id":_id,
            "payNo":item["payNo"],
            "transNumber":item["transNumber"],
            "content":content
        }
        try:
            _id = mongoClient.insert("failed_trans_content","order",order)
        except Exception as e:
            logger.error(f"记录交易源数据content异常:{e}")
            return self.write_resp500("服务器内部异常")
        return self.write_resp200(_id)


class RevokeHandler(BaseHandler):
    async def post(self):
        data = self.json()
        try:
            _id = await mysqlClient.insert("trade_revoke",data=data)
        except Exception as e:
            logger.error(f"记录撤销交易时异常:{e}")
            return self.write_resp500("服务器内部异常")
        return self.write_resp200(_id)

class TransactionResSaveHandler(BaseHandler):
    async def post(self):
        data = self.json()
        try:
            _id = await mysqlClient.insert("res_query",data=data)
        except Exception as e:
            logger.error(f"保存交易结果时异常:{e}")
            return self.write_resp500("服务器内部异常")
        return self.write_resp200(_id)


class CallBackHandler(BaseHandler):
    async def post(self):
        _id = -1
        data = self.json()
        callbackInfo = data.get("callback_info")
        callbackConfirmInfo = data.get("callback_confirm_info")
        try:
            _id = await mysqlClient.insert("callback_res",callbackInfo)
        except Exception as e:
            logger.error(f"保存回调结果时异常:{e}")
        
        try:
            callbackConfirmInfo.update({"_id":_id})
            mongoClient.insert('callback_confirm','confirm_struct',callbackConfirmInfo)
        except Exception as e:
            logger.error(f"记账异常content:{e}")
        return self.write_resp200(_id)

class ParkOrderConfirmHandler(BaseHandler):
    async def post(self):
        data = self.json()
        serviceIds = data.get("service_ids")
        queryDate = data.get("query_date")
        if not (serviceIds and queryDate):
            return self.write_resp400("传入参数不完整")
        logger.info(f"=========>对账日期:{queryDate};车场:{serviceIds}")
        for service_id in serviceIds:
            reconciliation = Reconciliation(service_id=service_id,type=1,start_date=queryDate,start_hour=-1)
            try:
                local_data = await reconciliation.query_local_data()
            except Exception as e:
                logger.error(f"查询本地账单时异常:{e}")
                return
            logger.info(f"local_data_len:{len(local_data)}")
            try:
                await reconciliation.run(local_data)
            except Exception as e:
                logger.error(f"对账过程中异常:{e};{service_id}")
                continue
            logger.info(f"{service_id}对账完成")
        