import json
from collections import defaultdict
from datetime import date, timedelta

from sqlalchemy import update, and_

from db import MysqlSession
from db.mysql import ZxIeOcrerror
from photo_mask_error_check import auto_check_error
from util import util

if __name__ == '__main__':
    today = date.today()
    session = MysqlSession()
    ocr_errors = (session.query(ZxIeOcrerror.pk_phrec, ZxIeOcrerror.cXm, ZxIeOcrerror.cSfzh, ZxIeOcrerror.cfjaddress,
                                ZxIeOcrerror.pk_phhd, ZxIeOcrerror.cfjaddress2)
                  .filter(and_(ZxIeOcrerror.creationtime >= today,
                               ZxIeOcrerror.creationtime < today + timedelta(days=1))).all())
    session.close()

    result = defaultdict(int)
    result[f"{today}涂抹错误图片总数"] = len(ocr_errors)
    for ocr_error in ocr_errors:
        if ocr_error.cfjaddress2:
            result[ocr_error.cfjaddress2] += 1
            continue

        error_descript = auto_check_error(ocr_error)
        if error_descript == "未知错误":
            check_time = None
        else:
            check_time = util.get_default_datetime()

        session = MysqlSession()
        update_error = (update(ZxIeOcrerror).where(ZxIeOcrerror.pk_phrec == ocr_error.pk_phrec).values(
            checktime=check_time, cfjaddress2=error_descript))
        session.execute(update_error)
        session.commit()
        session.close()
        result[error_descript] += 1
    print(result)
    with open("photo_mask_error_report.txt", 'w', encoding='utf-8') as file:
        file.write(json.dumps(result, indent=4, ensure_ascii=False))
        file.write(util.get_default_datetime())
    print("结果已保存。")
