import json
import requests
from processing.tools.StringUtils import get_download_dir

spotfileuri = "http://127.0.0.1:8080/file/"


# 上传图斑成果zip文件
def spotfileUpload(filepath, uri=f'{spotfileuri}uploadSpotZip', uploaduser='admin'):
    print("上传图斑成果zip文件！")
    # 通过files参数传递文件
    files = {'file': open(filepath, 'rb')}
    data = {'uploaduser': uploaduser}
    response = requests.post(uri, files=files, data=data)
    requestmsg = response.text
    # 打印响应内容
    json_obj = json.loads(requestmsg)
    print(json_obj)
    return json_obj


# 获取图斑上传列表
def getSpotFileList(uri=f'{spotfileuri}spotfileList', uploaduser='admin'):
    print("获取图斑成果列表！")
    data = {'uploaduser': uploaduser}
    response = requests.get(uri, params=data)
    requestmsg = response.text
    # 打印响应内容
    json_obj = json.loads(requestmsg)
    print(json_obj)
    return json_obj


# 下载图斑成果数据包
def downloadspotfile(filename, dir):
    print("通过uri下载文件")
    download_dir = get_download_dir()
    url = f'{spotfileuri}spotfile/{filename}'
    response = requests.get(url)
    if response.status_code == 200:
        filedir = f'{download_dir}\\{filename}'
        if dir is not None and dir != "TEMPORARY_OUTPUT":
            filedir = dir
        with open(filedir, 'wb') as f:
            f.write(response.content)
        print('文件下载成功!')
        return f'文件下载成功!文件地址：{filedir}'
    else:
        print('文件下载失败。')
        return '文件下载失败。'

# 删除图斑
def deletespotfile(id):
    print("删除图斑！")
    data = {'id': id}
    response = requests.delete(f'{spotfileuri}spotfileDelete', params=data)
    requestmsg = response.text
    # 打印响应内容
    json_obj = json.loads(requestmsg)
    print(json_obj)
    return json_obj
