from flask import Flask, render_template, jsonify, request
import pandas as pd
import os
import json

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')  # 假设你有一个 index.html 页面

@app.route('/process-data', methods=['POST'])
def process_data():
    # 假设上传的CSV文件已保存在 'uploaddatas/data.csv'
    openfile = 'uploaddatas/data.csv'
    data_lists, minValue, maxValue = process_csv(openfile)

    # 生成热图数据并保存为 JSON
    result = generate_heatmap(data_lists, minValue, maxValue)
    save_path = 'uploaddatas/heatmap_data.json'
    with open(save_path, 'w') as f:
        json.dump(result, f)

    return jsonify({'message': '数据已处理并保存为JSON', 'path': save_path})

def process_csv(openfile):
    numRows, numCols = 10, 10
    attribute = 2

    data_lists = []
    MaxLatitude, MinLatitude, MaxLongitude, MinLongitude = -100000, 100000, -10000, 10000

    with open(openfile, 'r') as file:
        lines = file.readlines()

    for line in lines:
        values = line.strip().split(',')
        templist = [float(value) for value in values[1:6]]
        if templist[3] > MaxLatitude:
            MaxLatitude = templist[3]
        if templist[3] < MinLatitude:
            MinLatitude = templist[3]
        if templist[4] > MaxLongitude:
            MaxLongitude = templist[4]
        if templist[4] < MinLongitude:
            MinLongitude = templist[4]
        data_lists.append(templist)

    return data_lists, MinLatitude, MaxLongitude

def generate_heatmap(data_lists, MinLatitude, MaxLongitude):
    # 这里插入之前的矩阵处理逻辑
    numRows, numCols = 10, 10
    attribute = 2
    openfile = 'uploaddatas/data.csv'
    with open(openfile, 'r') as file:
        lines = file.readlines()

    data_lists = []
    MaxLatitude = -100000
    MinLatitude = 100000
    MaxLongitude = -10000
    MinLongitude = 10000
    for line in lines:
        values = line.strip().split(',')
        templist = []
        for i in range(5):
            templist.append(float(values[i+1]))
        if templist[3] > MaxLatitude:
            MaxLatitude = templist[3]
        if templist[3] < MinLatitude:
            MinLatitude = templist[3]
        if templist[4] > MaxLongitude:
            MaxLongitude = templist[4]
        if templist[4] < MinLongitude:
            MinLongitude = templist[4]
        data_lists.append(templist)

    # print(data_lists)
    # print(MaxLatitude,MinLatitude,MaxLongitude,MinLongitude)

    step_rangeLon = (MaxLongitude - MaxLongitude) * 0.05
    step_rangeLat = (MaxLatitude - MinLatitude) * 0.05
    MaxLatitude += step_rangeLat
    MinLatitude -= step_rangeLat
    MaxLongitude += step_rangeLon
    MinLongitude -= step_rangeLon

    step_Latlen = (MaxLatitude - MinLatitude) / numRows
    step_Lonlen = (MaxLongitude - MinLongitude) / numCols

    matrix = [[[0,0] for _ in range(numCols)] for _ in range(numRows)]

    # print(matrix)

    for item in data_lists:
        value = item[attribute]
        i = int((item[3] - MinLatitude)/step_Latlen)
        j = int((item[4] - MinLongitude)/step_Lonlen)
        if i == numRows:
            i = numRows-1
        if j == numCols:
            j = numCols-1
        # print(i,j)
        matrix[i][j][0] += value
        matrix[i][j][1] += 1

    # print(matrix)
    minValue = 10000000
    maxValue = 0
    result = []
    for ritem in matrix:
        temp = []
        for citem in ritem:
            value,count = citem
            if count == 0:
                temp.append(0)
            else:
                number = value/count
                if number > maxValue:
                    maxValue = number
                if number < minValue:
                    minValue = number
                temp.append(number)
        result.append(temp)

    print(maxValue,minValue)
    # print(result)
    colorstep = (maxValue - minValue)/100
    print(colorstep)
    for i in range(len(result)):
        for j in range(len(result[i])):
            if result[i][j] != 0:
                result[i][j] = ((result[i][j] - minValue)/colorstep)
    # 由于篇幅原因，此处省略具体实现，直接使用前面代码示例的逻辑
    # 返回处理后的结果，比如热图数据
    return result

if __name__ == '__main__':
    app.run(debug=True)
