import datetime
import json
import os
import sys
from decimal import Decimal
from io import BytesIO
from itertools import groupby

import requests
from PIL import ImageDraw, Image, ImageFont

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from db import MysqlSession
from db.mysql import ZxIeCost, ZxIeDischarge, ZxIeSettlement, ZxPhhd, ZxOcr, ZxPhrec
from ucloud import ucloud


def check_ie_result(pk_phhd):
    os.makedirs(f"./check_result/{pk_phhd}", exist_ok=True)
    json_result = {"pk_phhd": pk_phhd}
    session = MysqlSession()
    phhd = session.query(ZxPhhd.cXm).filter(ZxPhhd.pk_phhd == pk_phhd).one()
    json_result["cXm"] = phhd.cXm
    settlement = session.query(ZxIeSettlement.pk_ie_settlement, ZxIeSettlement.name, ZxIeSettlement.admission_date,
                               ZxIeSettlement.discharge_date,
                               ZxIeSettlement.medical_expenses, ZxIeSettlement.personal_cash_payment,
                               ZxIeSettlement.personal_account_payment,
                               ZxIeSettlement.personal_funded_amount, ZxIeSettlement.medical_insurance_type,
                               ZxIeSettlement.admission_id, ZxIeSettlement.settlement_id).filter(
        ZxIeSettlement.pk_phhd == pk_phhd).one()
    settlement_result = {
        "pk_ie_settlement": settlement.pk_ie_settlement,
        "name": settlement.name,
        "admission_date": settlement.admission_date,
        "discharge_date": settlement.discharge_date,
        "medical_expenses": settlement.medical_expenses,
        "personal_cash_payment": settlement.personal_cash_payment,
        "personal_account_payment": settlement.personal_account_payment,
        "personal_funded_amount": settlement.personal_funded_amount,
        "medical_insurance_type": settlement.medical_insurance_type,
        "admission_id": settlement.admission_id,
        "settlement_id": settlement.settlement_id,
    }
    json_result["settlement"] = settlement_result

    discharge = session.query(ZxIeDischarge.pk_ie_discharge, ZxIeDischarge.hospital, ZxIeDischarge.pk_yljg,
                              ZxIeDischarge.department, ZxIeDischarge.pk_ylks,
                              ZxIeDischarge.name, ZxIeDischarge.admission_date, ZxIeDischarge.discharge_date,
                              ZxIeDischarge.doctor, ZxIeDischarge.admission_id, ZxIeDischarge.age).filter(
        ZxIeDischarge.pk_phhd == pk_phhd).one()
    discharge_result = {
        "pk_ie_discharge": discharge.pk_ie_discharge,
        "hospital": discharge.hospital,
        "pk_yljg": discharge.pk_yljg,
        "department": discharge.department,
        "pk_ylks": discharge.pk_ylks,
        "name": discharge.name,
        "age": discharge.age,
        "admission_date": discharge.admission_date,
        "discharge_date": discharge.discharge_date,
        "doctor": discharge.doctor,
        "admission_id": discharge.admission_id,
    }
    json_result["discharge"] = discharge_result

    cost = session.query(ZxIeCost.pk_ie_cost, ZxIeCost.name, ZxIeCost.admission_date, ZxIeCost.discharge_date,
                         ZxIeCost.medical_expenses).filter(ZxIeCost.pk_phhd == pk_phhd).one()
    cost_result = {
        "pk_ie_cost": cost.pk_ie_cost,
        "name": cost.name,
        "admission_date": cost.admission_date,
        "discharge_date": cost.discharge_date,
        "medical_expenses": cost.medical_expenses,
    }
    json_result["cost"] = cost_result

    phrecs = session.query(ZxPhrec.pk_phrec, ZxPhrec.pk_phhd, ZxPhrec.cRectype, ZxPhrec.cfjaddress).filter(
        ZxPhrec.pk_phhd == pk_phhd).all()
    for phrec in phrecs:
        img_name = phrec.cfjaddress
        img_path = ucloud.get_private_url(img_name)

        response = requests.get(img_path)
        image = Image.open(BytesIO(response.content)).convert("RGB")
        size = image.width * image.height / 200000
        font = ImageFont.truetype("./font/simfang.ttf", size=size)

        ocr = session.query(ZxOcr.id, ZxOcr.content, ZxOcr.x_offset, ZxOcr.y_offset).filter(
            ZxOcr.pk_phrec == phrec.pk_phrec).all()
        if not ocr:
            os.makedirs(f"./check_result/{pk_phhd}/0", exist_ok=True)
            image.save(f"./check_result/{pk_phhd}/0/{img_name}")

        for id, group_results in groupby(ocr, key=lambda x: x.id):
            draw = ImageDraw.Draw(image)
            for ocr_item in group_results:
                result = json.loads(ocr_item.content)
                x_offset = ocr_item.x_offset
                y_offset = ocr_item.y_offset
                for key in result:
                    for value in result[key]:
                        box = value["bbox"][0]
                        if x_offset:
                            box[0] += x_offset
                            box[2] += x_offset
                        if y_offset:
                            box[1] += y_offset
                            box[3] += y_offset

                        draw.rectangle(box, outline="red", width=2)  # 绘制矩形
                        draw.text((box[0], box[1] - size), key, fill="blue", font=font)  # 在矩形上方绘制文本
                        draw.text((box[0], box[3]), value["text"], fill="blue", font=font)  # 在矩形下方绘制文本
                os.makedirs(f"./check_result/{pk_phhd}/{ocr_item.id}", exist_ok=True)
                image.save(f"./check_result/{pk_phhd}/{ocr_item.id}/{img_name}")
    session.close()

    # 自定义JSON处理器
    def default(obj):
        if isinstance(obj, Decimal):
            return float(obj)
        if isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")

    with open(f"./check_result/{pk_phhd}/result.json", "w", encoding="utf-8") as json_file:
        json.dump(json_result, json_file, indent=4, ensure_ascii=False, default=default)


if __name__ == '__main__':
    check_ie_result(3572938)
