import datetime
import json
import os

from celery import Celery
from sqlalchemy import and_, or_

from app.api.engine import TAMP_SQL, tamp_diagnose_app_engine, template_folder, redis_host, redis_port, redis_db, \
    redis_password, temp_img_save_folder, pdf_save_folder
from app.model.tamp_diagnose_app import HoldReport, HoldDiagnoseReport, PeriodicReport, Customer, ReportView
from app.utils.jinjia2html_v2 import DataIntegrate

celery_app = Celery(__name__)

celery_conf = "redis://:{}@{}:{}/{}".format(redis_password,redis_host[0],redis_port[0],"2")
celery_app.conf.update({"broker_url": celery_conf, "result_backend": celery_conf})


@celery_app.task
def save_pdf(id, ifa_id, customer_id, pdf_name, type):
    """
    加法
    :param x:
    :param y:
    :return:
    """
    try:
        dt = DataIntegrate(ifa_id=ifa_id, customer_id=customer_id, pdf_name=pdf_name, type=type)
        report_data = dt.get_template_data()
        report_data = json.dumps(report_data).replace(template_folder, temp_img_save_folder)
        report_data = json.loads(report_data)
        dt.render_data(data=report_data)
    except:
        pass
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        res = None
        if type == 1:
            res = tamp_diagnose_session.query(HoldReport).filter(and_(
                HoldReport.id == id,
                HoldReport.ifa_id == ifa_id,
            ))
        elif type == 2:
            res = tamp_diagnose_session.query(HoldDiagnoseReport).filter(and_(
                HoldDiagnoseReport.id == id,
                HoldDiagnoseReport.ifa_id == ifa_id,
            ))
        elif type == 3:
            res = tamp_diagnose_session.query(PeriodicReport).filter(and_(
                PeriodicReport.id == id,
                PeriodicReport.ifa_id == ifa_id,
            ))
        else:
            return False
        if res.all():
            if os.path.exists(pdf_save_folder + pdf_name):
                res.update({
                    'file': pdf_name,
                    'update_status': 2,
                    'update_time': datetime.datetime.now()
                })
            else:
                res.update({
                    'update_status': 0,
                    'update_time': datetime.datetime.now()
                })
    return True

        


