# -*- encoding: utf-8 -*-
# -----------------------------------------------------------------------------
# @File Name  : report_service.py
# @Time       : 2021/1/13 下午3:14
# @Author     : X. Peng
# @Email      : acepengxiong@163.com
# @Software   : PyCharm
# -----------------------------------------------------------------------------
import datetime
import os
import uuid

from sqlalchemy import and_
# from sqlalchemy import union_all

from app.api.engine import TAMP_SQL, tamp_diagnose_app_engine
from app.model.tamp_diagnose_app import HoldReport, HoldDiagnoseReport, PeriodicReport
from app.utils.jinjia2html_v2 import DataIntegrate


def get_report_list(args):
    """."""
    type = args.get('type')
    ifa_id = args.get('ifa_id')
    pageNumber = args['pageNumber']
    pageSize = args['pageSize']
    start_time = args.get('start_time')
    end_time = args.get('end_time')
    offset = (pageNumber - 1) * pageSize
    res = []
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        hold_report = tamp_diagnose_session.query(HoldReport).filter(and_(
            HoldReport.ifa_id == ifa_id,
            HoldReport.update_time >= start_time,
            HoldReport.update_time <= end_time
        ))
        hold_diagnose_report = tamp_diagnose_session.query(HoldDiagnoseReport).filter(and_(
            HoldDiagnoseReport.ifa_id == ifa_id,
            HoldDiagnoseReport.update_time >= start_time,
            HoldDiagnoseReport.update_time <= end_time
        ))
        periodic_report = tamp_diagnose_session.query(PeriodicReport).filter(and_(
            PeriodicReport.ifa_id == ifa_id,
            PeriodicReport.update_time >= start_time,
            PeriodicReport.update_time <= end_time
        ))
        if type == 0:
            res = hold_report.union_all(hold_diagnose_report).union_all(periodic_report)
        elif type == 1:
            res = hold_report
        elif type == 2:
            res = hold_diagnose_report
        elif type == 3:
            res = periodic_report
    totalSize = res.count()
    data = res.offset(offset).limit(pageSize)
    data = [r.to_dict() for r in data]
    return {
        'content': data,
        'pageNum': pageNumber,
        'pageSize': pageSize,
        'totalSize': totalSize
    }


def delete_report(args):
    """."""
    type = args.get('type')
    id = args.get('id')
    ifa_id = args.get('ifa_id')
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        if type == 1:
            tamp_diagnose_session.query(HoldReport).filter(and_(
                HoldReport.ifa_id == ifa_id,
                HoldReport.id == id
            )).delete()
        elif type == 2:
            tamp_diagnose_session.query(HoldDiagnoseReport).filter(and_(
                HoldDiagnoseReport.ifa_id == ifa_id,
                HoldDiagnoseReport.id == id
            )).delete()
        elif type == 3:
            tamp_diagnose_session.query(PeriodicReport).filter(and_(
                PeriodicReport.ifa_id == ifa_id,
                PeriodicReport.id == id
            )).delete()


def get_one_report(args):
    """."""
    id = args.get('id')
    type = args.get('type')
    ifa_id = args.get('ifa_id')
    res = []
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        hold_report = tamp_diagnose_session.query(HoldReport).filter(and_(
            HoldReport.id == id,
            HoldReport.ifa_id == ifa_id,
        ))
        hold_diagnose_report = tamp_diagnose_session.query(HoldDiagnoseReport).filter(and_(
            HoldDiagnoseReport.id == id,
            HoldDiagnoseReport.ifa_id == ifa_id,
        ))
        periodic_report = tamp_diagnose_session.query(PeriodicReport).filter(and_(
            PeriodicReport.id == id,
            PeriodicReport.ifa_id == ifa_id,
        ))
        if type == 0:
            res = hold_report.union_all(hold_diagnose_report).union_all(periodic_report)
        elif type == 1:
            res = hold_report
        elif type == 2:
            res = hold_diagnose_report
        elif type == 3:
            res = periodic_report
    data = [r.to_dict() for r in res]
    return data[0]


def edit_report(args):
    """编辑报告"""
    id = args.get('id')
    type = args.get('type')
    ifa_id = args.get('ifa_id')
    report_data = args.get('report_data')
    res = []
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        hold_report = tamp_diagnose_session.query(HoldReport).filter(and_(
            HoldReport.id == id,
            HoldReport.ifa_id == ifa_id,
        ))
        hold_diagnose_report = tamp_diagnose_session.query(HoldDiagnoseReport).filter(and_(
            HoldDiagnoseReport.id == id,
            HoldDiagnoseReport.ifa_id == ifa_id,
        ))
        periodic_report = tamp_diagnose_session.query(PeriodicReport).filter(and_(
            PeriodicReport.id == id,
            PeriodicReport.ifa_id == ifa_id,
        ))
        if type == 1:
            res = hold_report
        elif type == 2:
            res = hold_diagnose_report
        elif type == 3:
            res = periodic_report
        if not res:
            return False
        r = res.update({
            'report_data': report_data,
            'update_time': datetime.datetime.now()
        })
        if r > 0:
            return True
    return False


def make_report(args):
    """制作报告."""
    ifa_id = args.get('ifa_id')
    customer_id = args.get('customer_id')
    type = args.get('type')
    name = args.get('name')
    report_data = args.get('report_data')
    pdf_name = str(uuid.uuid4()) + '.pdf'
    args['update_time'] = datetime.datetime.now()
    args['update_status'] = 1

    record_id = 0
    with TAMP_SQL(tamp_diagnose_app_engine) as tamp_diagnose_app:
        tamp_diagnose_session = tamp_diagnose_app.session
        report_record = None
        if type == 1:
            report_record = HoldReport(**args)
        elif type == 2:
            report_record = HoldDiagnoseReport(**args)
        elif type == 3:
            report_record = PeriodicReport(**args)
        if not report_record:
            return False
        tamp_diagnose_session.add(report_record)
        tamp_diagnose_session.flush()
        record_id = report_record.id
    pid = os.fork()
    if pid == 0:
        try:
            dt = DataIntegrate(ifa_id=ifa_id, customer_id=customer_id, pdf_name=pdf_name, type=type)
            dt.render_data(data=report_data)
            hold_report = tamp_diagnose_session.query(HoldReport).filter(and_(
                HoldReport.id == record_id,
                HoldReport.ifa_id == ifa_id,
            ))
            hold_diagnose_report = tamp_diagnose_session.query(HoldDiagnoseReport).filter(and_(
                HoldDiagnoseReport.id == record_id,
                HoldDiagnoseReport.ifa_id == ifa_id,
            ))
            periodic_report = tamp_diagnose_session.query(PeriodicReport).filter(and_(
                PeriodicReport.id == record_id,
                PeriodicReport.ifa_id == ifa_id,
            ))
            if type == 1:
                res = hold_report
            elif type == 2:
                res = hold_diagnose_report
            elif type == 3:
                res = periodic_report
            if not res:
                return False
            res.update({
                'file': pdf_name,
                'update_status': 2,
                'update_time': datetime.datetime.now()
            })
        except:
            pass
    else:
        return True
