import uuid

import requests
import json
from datetime import datetime
import message_pb2 as message
import hashlib

class HttpRequest(object):
    class InDate:
        def __init__(self, ParkId, PlateNo, dataTime, chnnId, Remake, licenseColorDict, InPicUrl, InPlateUrl,
                     InRecordId):
            '''
            :param ParkId: 场ID
            :param PlateNo:车牌号
            :param dataTime:入场时间
            :param chnnId:通道ID
            :param Remake:备注
            :param licenseColorDict:车牌颜色
            :param InPicUrl:入场图片
            :param InPlateUrl:入场车牌特写图片
            :param InRecordId:入场流水号(唯一码)
            '''
            self.ParkId = ParkId
            self.PlateNo = PlateNo
            self.dateTime = dataTime
            self.chnnId = chnnId
            self.Remake = Remake
            self.licenseColorDict = licenseColorDict
            self.InPicUrl = InPicUrl
            self.InPlateUrl = InPlateUrl
            self.InRecordId = InRecordId

    class QueryData:
        def __init__(self, SerialNumber, ParkId):
            '''
            :param SerialNumber: 入场流水号(唯一码)
            :param ParkId:场ID
            '''
            self.SerialNumber = SerialNumber
            self.ParkId = ParkId

    class OutDate:
        def __init__(self, ParkId, PlateNo,InRecordId, dateTime, chnnId, Remake, licenseColorDict, OutPicUrl, OutPlateUrl):
            '''
            :param ParkId: 场ID
            :param PlateNo:车牌号
            :param InRecordId:入场流水号(唯一码)
            :param dateTime:入场时间
            :param chnnId:通道ID
            :param Remake:备注
            :param licenseColorDict:车牌颜色
            :param OutPicUrl: 出场图片
            :param OutPlateUrl:出场车牌特写图片
            '''
            self.ParkId = ParkId
            self.PlateNo = PlateNo
            self.InRecordId = InRecordId
            self.dateTime = dateTime
            self.chnnId = chnnId
            self.Remake = Remake
            self.licenseColorDict = licenseColorDict
            self.OutPicUrl = OutPicUrl
            self.OutPlateUrl = OutPlateUrl

    def __init__(self, msgId, AppId, time, sign, data):
        '''
        :param msgId: 消息ID，随机值
        :param AppId: AppId
        :param time: 时间
        :param sign:签名(msgId+AppId+time+私钥)进行md5小写
        :param data:数据结构体
        '''
        self.msgId = msgId
        self.AppId = AppId
        self.time = time
        self.sign = sign
        self.data = data.__dict__


# def get_request_data(park_table, param):
#     hl = hashlib.md5()
#     msgId = str(uuid.uuid1()) + '@' + park_table.car_number
#     AppId = 'blbc5zkpyymaicd3'
#     time = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
#     sign = msgId + AppId + time+'anzs74aph8ac8dy6tj48t05js6zpkgx5'
#     hl.update(sign.encode(encoding='utf-8'))
#     sign = hl.hexdigest()
#
#     if param == 'in':
#         data = HttpRequest.InDate("2302221444266172014", park_table.car_number,
#                                               str(datetime.now().strftime('%Y-%m-%d')),
#                                               '2302221446265822050',
#                                               park_table.car_number_info.plate_type,
#                                               '1',
#                                               park_table.car_number_info.plate_full_image,
#                                               park_table.car_number_info.plate_clip_image, park_table.primary_key)
#     elif param == 'query':
#         data = HttpRequest.QueryData(park_table.primary_key, "2302221444266172014")
#     elif param == 'out':
#         data = HttpRequest.OutDate("2302221444266172014", park_table.car_number,
#                                    park_table.primary_key,
#                                    str(datetime.now().strftime('%Y-%m-%d')),
#                                    '2302221729013462154',
#                                    park_table.car_number_info.plate_type,
#                                    '1',
#                                    park_table.car_number_info.plate_full_image,
#                                    park_table.car_number_info.plate_clip_image)
#
#     request = HttpRequest(msgId, AppId, time,sign, data)
#
#     return request.__dict__
#

# http_park_request = {"msgId": "12345678901234567890123456789012@鄂A12345$park",  # 32位唯一码 @ 车牌号 $ park
#                      "AppId": "z5OZfJ83faYnpaL65FIRfEwLrST2y26f",  # 固定值，收费系统制定
#                      "time": "2023-02-10 17:33:30",  # 入场时间，年-月-日 时:分:秒
#                      "sign": "cdb34f24cf941e495e9467171341f3f3",  # 签名 （msgid + appid + time + 秘钥）转MD5 小写
#                      "data": {"SerialNumber": "20220210155926DA54SD4A5SD4DDD",  # 32位唯一码， 存车 取车 查询 保持一致
#                               "ParkId": "1000000000000000001",  # 固定值，收费系统制定
#                               "PlateNo": "闽D10001",  # 车牌号，
#                               "dateTime": "2023-02-07",  # 入场时间，年-月-日 时:分:秒
#                               "chnnId": "C1-1",  # C1单元1号入口
#                               "Remake": "",  # 暂时不写，备注
#                               "licenseColorDict": "",  # 暂时不写， 车牌颜色
#                               "InPicUrl": "",  # 暂时不写，入场图片
#                               "InPlateUrl": ""  # 暂时不写，车牌图片特写
#                               }

#                      }
# http_query_request = {
#     "msgId": "12321431232324353233123",
#     "AppId": "z5OZfJ83faYnpaL65FIRfEwLrST2y26f",
#     "parkId": "281219316345475072",
#     "time": "2023-02-10 09:05:00",
#     "sign": "cdb34f24cf941e495e9467171341f3f3",
#     "data": {"SerialNumber": "20220210155926DA54SD4A5SD4DDD",
#              "ParkId": "1000000000000000001"
#              }
# }
#
# http_park_response = {
#     "Message": "入场成功",
#     "Tag": 1
# }
if __name__ == "__main__":
    in_url = 'http://110.80.15.100:9030/Api/CarInEntry'
    query_url = 'http://110.80.15.100:9030/Api/GetBill'
    out_url = 'http://110.80.15.100:9030/Api/CarOutEntry'

    park_table = message.park_table()
    park_table.car_number = '鄂A00003'
    park_table.unit_id = 31
    park_table.import_id = 1
    park_table.primary_key = '20230210155926DA54SD4A5SD4DDD'
    park_table.car_number_info.plate_color = '蓝色'
    park_table.car_number_info.plate_type = '蓝牌小汽车'
    park_table.car_number_info.plate_full_image = ''
    park_table.car_number_info.plate_clip_image = ''

    request = get_request_data(park_table,'in')
    print('发送入场请求:')
    print(request)
    try:
        resp = requests.post(in_url, json=request).json()
        print('接收入场反馈:')
        print(resp)
        print('\n')
    except Exception as e:
        print('向收费系统推送请求失败！    ERROR:%s' % (str(e.args)))


    request = get_request_data(park_table,'query')
    print('发送查询账单请求:')
    print(request)
    try:
        resp = requests.post(query_url, json=request).json()
        print('接收查询账单反馈:')
        print(resp)
        print('\n')
    except Exception as e:
        print('向收费系统推送请求失败！    ERROR:%s' % (str(e.args)))

    request = get_request_data(park_table,'out')
    print('发送出场请求:')
    print(request)
    try:
        resp = requests.post(out_url, json=request).json()
        print('接收出场反馈:')
        print(resp)
    except Exception as e:
        print('向收费系统推送请求失败！    ERROR:%s' % (str(e.args)))

    # dict = {'kw': 'hello'}
    # try:
    #     resp = requests.post('https://fanyi.baidu.com/sug', data=dict)
    #     print(resp)
    # except Exception as e:
    #     print('向收费系统推送请求失败！    ERROR:%s' % (str(e.args)))
    # print(resp)
    # p_request.InRequest(msgId="12345678901234567890123456789012@鄂A12345$park",
    #                       AppId="z5OZfJ83faYnpaL65FIRfEwLrST2y26f", sign="cdb34f24cf941e495e9467171341f3f3",
    #                         SerialNumber="20220210155926DA54SD4A5SD4DDD", ParkId="1000000000000000001",
    #                         PlateNo="闽D10001", chnnId="C1-1")
    #
    # res = p_client.send_request(p_request)
    # if res is False:
    #     print('请求失败！')

'''
    word = input("输入您要翻译的单词：")
    url = "https://fanyi.baidu.com/sug"  # 百度翻译接口
    dict = {"kw": word}
    # 发送的数据必须放到字典中，通过data发送
    resp = requests.post(url, data=dict)
    print(resp)
    print(resp.json())  # 将服务器返回的内容直接处理成json数据格式
    print(resp.text)

    print('---------------------------------------------')

    json_str = resp.json()
    print(json_str)
    python_str1 = json.dumps(json_str)
    print(python_str1)
    python_str2 = json.loads(python_str1)
    print(python_str2)
'''

'''
    url = 'http:#127.0.0.1:8099/Api/CarInEntry'
    postdata = http_park_request
    resp = requests.post(url, data=postdata)
    
    print(resp)
    print(resp.json())  #将服务器返回的内容直接处理成json数据格式
    print(resp.text)

    print('---------------------------------------------')
    json_dict = resp.json()
    print(json_dict)
    python_str1 = json.dumps(json_str)
    print(python_str1)
    python_str2 = json.loads(python_str1)
    print(python_str2)
    print('---------------------------------------------')
    
    
    
    if 'Message' in json_str.keys():
        response_message = json_str['Message'] 
        print(response_message)    
    else:
        response_message = ''
        
    if 'Tag' in json_str.keys():
        response_tag = json_str['Tag'] 
        print(response_tag)    
    else:
        response_tag = 0   
            

'''
