import cv2
import numpy as np
import hyperlpr3 as lpr3
import os
from PIL import Image, ImageDraw, ImageFont
import requests
import json
import time

con=0.75 #置信度阈值
API_url="http://localhost:8087/api/payment"
MIN_CONSECUTIVE_FRAMES = 5    # 需连续识别到同一车牌的最小帧数
RECORD_INTERVAL = 30           # 同一车牌发送间隔(秒)
plate_counter = {}             # 车牌连续计数 {车牌: 计数}
last_record_time = {}          # 车牌最后记录时间 {车牌: 时间戳}

def send_plate_to_server(plate_number):
    """发送车牌号到Spring Boot后端"""
    # 构建JSON请求体
    payload = {"plate": plate_number}
    # 发送POST请求
    response = requests.post(
        API_url,
        data=json.dumps(payload),
        headers={'Content-Type': 'application/json'},
    )
    # 检查响应状态
    if response.status_code == 200:
        print(f"✅ 车牌发送成功: {plate_number}")
        return True
    else:
        print(f"⚠️ 服务端错误: {response.status_code} - {response.text}")
        return False

def draw_plate_on_image(img, box, text, font):
    x1, y1, x2, y2 = box
    cv2.rectangle(img, (x1, y1), (x2, y2), (139, 139, 102), 2, cv2.LINE_AA)
    cv2.rectangle(img, (x1, y1 - 20), (x2, y1), (139, 139, 102), -1)
    data = Image.fromarray(img)
    draw = ImageDraw.Draw(data)
    draw.text((x1 + 5, y1 - 20), text, (255, 255, 255), font=font)
    res = np.asarray(data)
    return res

def save_txt(code):
    """
    将识别的车牌号保存到文本文件
    """
    file_path = 'piu.txt'
    with open(file_path, 'r+',encoding='utf-8') as f:
        # 将变量值写入文件
        last_line = len(f.readlines())
        f.write(str(last_line + 1) + ' '+ str(code))
        f.write(str('\n'))
        print(code)

font_ch=ImageFont.truetype("../resource/font/platech.ttf",20,0)

catcher=lpr3.LicensePlateCatcher(detect_level=lpr3.DETECT_LEVEL_HIGH)

# rtsp_url="rtsp://admin:MRQWNM@192.168.3.10:554/h264/ch1/main/av_stream"
cap= cv2.VideoCapture("../resource/video/车牌付.mp4")
cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)  # 关键：减少缓冲区降低延迟
while (cap.isOpened()):
    ret, frame =cap.read()
    if ret == True:
        current_plates = set()  # 当前帧有效车牌
        # 车牌识别
        results = catcher(frame)
        # 绘制识别结果
        for code, confidence,type_idx,box in results:
            if confidence < con:
                continue
             # 添加到当前帧车牌集合
            current_plates.add(code)
            text=f"{code}-{confidence:.2f}"
            frame = draw_plate_on_image(frame, box, text, font_ch)
            # 更新连续计数
            plate_counter[code] = plate_counter.get(code, 0) + 1

            # if code in plate_counter:
            #     plate_counter[code] += 1
            # else:
            #     plate_counter[code] = 1

        for plate in list(plate_counter.keys()):
            # 4.1 重置非连续出现的车牌
            if plate not in current_plates:
                plate_counter[plate] = 0
                continue
            if plate_counter[plate] >= MIN_CONSECUTIVE_FRAMES:
                current_time = time.time()
                last_time = last_record_time.get(plate, 0)

                if current_time - last_time > RECORD_INTERVAL:
                    # 存储到日志
                    save_txt(plate)

                    # #发送post请求
                    # send_plate_to_server(plate)

                    # 更新记录时间
                    last_record_time[plate] = current_time
                    
                    # 4.4 重置计数器（避免重复触发）
                    plate_counter[plate] = 0
        cv2.namedWindow('视频', cv2.WINDOW_NORMAL)
        cv2.resizeWindow('视频', 800, 600)  # 设置合适尺寸（宽x高）
        cv2.imshow('视频',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()