from datetime import date, timedelta

import cv2
from sqlalchemy import and_

from db import MysqlSession
from db.mysql import ZxIeOcrerror
from photo_mask_error_check import check_error

if __name__ == '__main__':
    today = date.today()
    session = MysqlSession()
    # 对涂抹错误的进行测试比较
    ocr_errors = (session.query(ZxIeOcrerror.pk_phrec, ZxIeOcrerror.cXm, ZxIeOcrerror.cSfzh, ZxIeOcrerror.cfjaddress)
                  .filter(and_(ZxIeOcrerror.checktime.is_(None),
                               ZxIeOcrerror.creationtime >= today,
                               ZxIeOcrerror.creationtime < today + timedelta(days=1)))
                  .order_by(ZxIeOcrerror.pk_phrec.desc()).limit(50).all())

    # 对已涂抹的进行测试比较
    # ocr_errors = (session.query(ZxPhrec.pk_phrec, ZxPhhd.cXm, ZxPhhd.cSfzh, ZxPhrec.cfjaddress)
    #               .join(ZxPhrec, ZxPhhd.pk_phhd == ZxPhrec.pk_phhd, isouter=True)
    #               .filter(ZxPhhd.paint_flag >= '8')
    #               .order_by(ZxPhrec.pk_phrec.desc())
    #               .limit(50).all())
    session.close()

    for ocr_error in ocr_errors:
        try:
            image = check_error(ocr_error)
            if image is None:
                continue
            cv2.imwrite(f"./mask_optimization_result/{ocr_error.cfjaddress}.jpg", image)
        except Exception as e:
            print(e)
