import requests
import json
import codecs
import os
from datetime import datetime, timedelta

qxData = []
swData = []
swHeightData = []
wagaData = []
def GetStartEndTime(deltaHour = 6):
    # 获取当前时间
    current_time = datetime.now()

    # 取整到最近的小时，即当前时间的小时数不变，分钟和秒数归零
    rounded_time = datetime(current_time.year, current_time.month, current_time.day, current_time.hour, 0, 0)

    # 往前推6个小时
    previous_time = rounded_time - timedelta(hours=deltaHour)

    # 输出两个时间
    return rounded_time.strftime('%Y-%m-%d %H:%M:%S'), previous_time.strftime('%Y-%m-%d %H:%M:%S')
    #return "2024-07-13 16:00:00", "2024-07-10 16:00:00"


def GetSixHourQXData():
    global qxData

    requestData = {}
    requestHead = {}
    requestData["eqaddvcd"] = "421083"
    requestData["pageSize"] = "80"
    requestHead["token"] = "6C60F37D40B48DECF9A3F2CC1A5A50142C4BE52F26D15B171153F20DB63960696A439E435DDCA9AF925F13338470FFBDDC98CEE65AFBC92C2EB4E44C0A757DB5"
    responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/baseinfo/stbprp/qx",data=requestData,headers=requestHead)

    qxDataDic = {}
    jsonData = json.loads(responese.content)
    index = 0
    for jsData in jsonData["data"]["list"]:
        #if (114.115926000756 > jsData["LGTD"] and jsData["LGTD"] > 113.410714576698 and 30.2676753765206 > jsData["LTTD"] and jsData["LTTD"] > 29.8114499954776):
        qxData.append(jsData)
        qxDataDic[jsData["STCD"]] = index
        index += 1

    requestData = {}
    sts = ''
    index = 0
    for qx in qxData:
        if index == 0:
            sts += qx["STCD"]
        else:
            sts += "," + qx["STCD"]
        index += 1
    
    etm,stm = GetStartEndTime(6)
    requestData["sts"] = sts
    requestData["etm"] = etm
    requestData["stm"] = stm
    #print(sts)
    dropDic = {}
    responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/monitdata/pptn/qx",data=requestData,headers=requestHead)
    jsonData = json.loads(responese.content)
    for jd in jsonData['data']:
        if jd["STCD"] not in dropDic.keys():
            dropDic[jd["STCD"]] = jd["DRP"]
        else:
            dropDic[jd["STCD"]] += jd["DRP"]
    
    for key in dropDic.keys():
        if key in qxDataDic:
            qxData[qxDataDic[key]]["dropSum6"] = dropDic[key]

    for sw in qxData:
        print(sw["STNM"] + " 经度:" + str(sw["LGTD"]) + " 维度:" + str(sw["LTTD"]) + " 六小时内降雨量:" + str(sw["dropSum6"]))
    
    
def GetSixHourSWData():
    global swData

    requestData = {}
    requestHead = {}
    requestData["eqaddvcd"] = "421083"
    requestData["pageSize"] = "80"
    requestHead["token"] = "6C60F37D40B48DECF9A3F2CC1A5A50142C4BE52F26D15B171153F20DB63960696A439E435DDCA9AF925F13338470FFBDDC98CEE65AFBC92C2EB4E44C0A757DB5"
    responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/baseinfo/stbprp/sw",data=requestData,headers=requestHead)

    swDataDic = {}
    jsonData = json.loads(responese.content)
    index = 0
    for jsData in jsonData["data"]["list"]:
        #if (114.115926000756 > jsData["LGTD"] and jsData["LGTD"] > 113.410714576698 and 30.2676753765206 > jsData["LTTD"] and jsData["LTTD"] > 29.8114499954776):
        swData.append(jsData)
        swDataDic[jsData["STCD"]] = index
        index += 1

    
    
        
    requestData = {}
    sts = ''
    index = 0
    for sw in swData:
        if index == 0:
            sts += sw["STCD"]
        else:
            sts += "," + sw["STCD"]
        index += 1
    print(sts)
    etm,stm = GetStartEndTime(6)
    requestData["sts"] = sts
    requestData["etm"] = etm
    requestData["stm"] = stm
    dropDic = {}
    wthDic = {}
    responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/monitdata/pptn/sw",data=requestData,headers=requestHead)
    jsonData = json.loads(responese.content)
    for jd in jsonData['data']:
        if jd["STCD"] not in dropDic.keys():
            dropDic[jd["STCD"]] = jd["DRP"]
        else:
            dropDic[jd["STCD"]] += jd["DRP"]

        wthDic[jd["STCD"]] = jd["WTH"]
    
    for key in dropDic.keys():
        if key in swDataDic:
            swData[swDataDic[key]]["dropSum6"] = dropDic[key]
            swData[swDataDic[key]]["wth"] = wthDic[key]

    # 使用列表推导过滤出包含 'dropSum6' 字段的字典
    filtered_swData = [item for item in swData if 'dropSum6' in item]

    swData = filtered_swData
    for sw in swData:
        print(sw["STNM"] + " 经度:" + str(sw["LGTD"]) + " 维度:" + str(sw["LTTD"]) + " 六小时内降雨量:" + str(sw["dropSum6"]) + " 天气:" + str(sw["wth"]))
    

def GetSWHegihtData():
    global swHeightData
    swDataDic = {}
    requestData = {}
    requestHead = {}
    requestHead["token"] = "6C60F37D40B48DECF9A3F2CC1A5A50142C4BE52F26D15B171153F20DB63960696A439E435DDCA9AF925F13338470FFBDDC98CEE65AFBC92C2EB4E44C0A757DB5"
    if not os.path.exists("importZa.json"):
        requestData["pageSize"] = "10000"
        responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/baseinfo/stbprp/sw",data=requestData,headers=requestHead)

        importZ = ["福田寺","黄丝南","下新河","子贝渊","沙螺"]
        
        jsonData = json.loads(responese.content)
        index = 0
        for jsData in jsonData["data"]["list"]:
            esixt = False
            for im in importZ:
                if im in jsData["STNM"]:
                    esixt = True
            if esixt:
                swHeightData.append(jsData)
                swDataDic[jsData["STCD"]] = index
                index += 1
        newJ = json.dumps(swHeightData, ensure_ascii=False)
        with codecs.open("importZa.json", "w+", encoding="utf-8") as nj:
            nj.write(newJ)
    else:
        index = 0
        with codecs.open("importZa.json","r", encoding="utf-8") as iz:
            izContent = json.loads(iz.read())
        for izc in izContent:
            swHeightData.append(izc)
            swDataDic[izc["STCD"]] = index
            index+=1
        # requestData["eqaddvcd"] = "421083"
        # requestData["pageSize"] = "80"
        # responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/baseinfo/stbprp/sw",data=requestData,headers=requestHead)
        # jsonData = json.loads(responese.content)
        # for jsData in jsonData["data"]["list"]:
        #     if jsData not in swHeightData:
        #         swHeightData.append(jsData)
        #         swDataDic[jsData["STCD"]] = index
        #         index += 1
    
    requestData = {}
    etm,stm = GetStartEndTime(0)
    requestData["pageSize"] = 300
    requestData["etm"] = etm
    requestData["stm"] = stm
    dwzDic = {}
    upzDic = {}
    tgtqDic = {}
    responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/monitdata/rw/st_was_r",data=requestData,headers=requestHead)
    jsonData = json.loads(responese.content)
    for jd in jsonData['data']["list"]:
        dwzDic[jd["STCD"]] = jd["DWZ"]
        upzDic[jd["STCD"]] = jd["UPZ"]
        tgtqDic[jd["STCD"]] = jd["TGTQ"]
    

    for key in dwzDic.keys():
        if key in swDataDic.keys():
            swHeightData[swDataDic[key]]["dwz"] = dwzDic[key]
            swHeightData[swDataDic[key]]["upz"] = upzDic[key]
            swHeightData[swDataDic[key]]["tgtq"] = tgtqDic[key]

    # 使用列表推导过滤出包含 'dropSum6' 字段的字典
    filtered_swData = [item for item in swHeightData if 'dwz' in item]
    

    sub_swData = [item for item in swHeightData if 'dwz' not in item]
    for ssw in sub_swData:
        ssw["dwz"] = None
        ssw["upz"] = None
        ssw["tgtq"] = None
        filtered_swData.append(ssw)

    swHeightData = filtered_swData

    for sw in swHeightData:
        #print(sw)
        print(sw["STNM"] + " 编码:" + str(sw["STCD"]) + " 经度:" + str(sw["LGTD"]) + " 维度:" + str(sw["LTTD"]) + " 下水位:" + str(sw["dwz"]) + " 下水位:" + str(sw["dwz"]) + " 上水位:" + str(sw["upz"]) + " 流量:" + str(sw["tgtq"]))



def GetWaGaData():
    global wagaData

    requestData = {}
    requestHead = {}
    requestData["pageSize"] = "320"
    requestHead["token"] = "6C60F37D40B48DECF9A3F2CC1A5A50142C4BE52F26D15B171153F20DB63960696A439E435DDCA9AF925F13338470FFBDDC98CEE65AFBC92C2EB4E44C0A757DB5"
    responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/baseinfo/bfx/fx_att_waga",data=requestData,headers=requestHead)

    wagaDataDic = {}
    jsonData = json.loads(responese.content)
    index = 0
    for jsData in jsonData["data"]["list"]:
        #if (114.115926000756 > jsData["LGTD"] and jsData["LGTD"] > 113.410714576698 and 30.2676753765206 > jsData["LTTD"] and jsData["LTTD"] > 29.8114499954776):
        wagaData.append(jsData)
        wagaDataDic[jsData["WAGA_CODE"]] = index
        index += 1
        
    
    requestData = {}
    etm,stm = GetStartEndTime(0)
    #requestData["etm"] = etm
    #requestData["stm"] = stm
    dwzDic = {}
    upzDic = {}
    tgtqDic = {}

    for waga in wagaData:
        #requestData["waga_code"] = waga["WAGA_CODE"]
        requestData["waga_name"] = waga["WAGA_NAME"]
        
        responese = requests.post("http://111.4.141.191:18081/shareddata/api/v1/monitdata/rw/waga_st_info",data=requestData,headers=requestHead)
        jsonData = json.loads(responese.content)
        if(len(jsonData["data"]["list"]) > 0):
            print(waga["WAGA_NAME"])
            print(waga["WAGA_CODE"])
            print(len(jsonData["data"]["list"]))
    


#GetSixHourQXData()
#GetSixHourSWData()
GetSWHegihtData()
#GetWaGaData()
