import os
import requests
import json
import io
from flask import Flask, request
from urllib.parse import urlparse
from urllib.request import urlopen
from alibabacloud_imagerecog20190930.client import Client
from alibabacloud_imagerecog20190930.models import ClassifyingRubbishAdvanceRequest
from alibabacloud_tea_openapi.models import Config
from alibabacloud_tea_util.models import RuntimeOptions
import mysql.connector
from mysql.connector import Error

def insert_feedback(feedbackInfo,feedbackType):
    try:
        # 弹出文件选择对话框，选择要插入的图片文件
        file_path = r'C:\Users\admin\Desktop\garbage.jpg'

        # 读取图片文件并转换为字节数组
        with open(file_path, "rb") as f:
            image_data = f.read()
        # files = {'file': open(file_path, 'rb')}

        # 建立数据库连接
        database_name = "garbage"
        username = "root"
        password = "root"
        host = '127.0.0.1'
        port = 3306
        connection = mysql.connector.connect(
            host=host,
            port=port,
            user=username,
            password=password,
            database=database_name
        )
        cursor = connection.cursor(prepared=True)
            # 插入用户反馈信息数据到数据库
        sql = "INSERT INTO feedback (feedbackInfo, feedbackType, feedbackPhoto) VALUES (%s, %s, %s)"
        cursor.execute(sql, (feedbackInfo, feedbackType, image_data))
        connection.commit()
        print("信息上传成功！")
        if cursor is not None:
            cursor.close()


    except FileNotFoundError as e:
        print("未选择文件。")
    except (Error, IOError) as e:
        print(e)
    finally:
        if 'connection' in locals():
            if connection.is_connected():
                connection.close()


def recognition(url):
    config = Config(
        access_key_id='LTAI5tHR7LEUHziRSK4TLSnM',
        access_key_secret='uq7sZKEixU5osl54GVzcj4Yb1Yb7XA',
        endpoint='imagerecog.cn-shanghai.aliyuncs.com',
        region_id='cn-shanghai'
    )
    # img = open(r'tmp.jpg', 'rb')
    img = io.BytesIO(urlopen(url).read())
    classifying_rubbish_request = ClassifyingRubbishAdvanceRequest()
    classifying_rubbish_request.image_urlobject = img

    runtime = RuntimeOptions()
    try:
        client = Client(config)
        response = client.classifying_rubbish_advance(classifying_rubbish_request, runtime)
        # result = response.body
        category = response.body.data.elements[0].category;
        return category
        # return JsonResponse({'result': result})
    except Exception as error:
        print(error)
        # print(error.code)
        # return JsonResponse({'error': str(error)}, status=500)

# def upload(path):
#     headers = {
#         'Authorization': 'Bearer 16|Nf1vBh8F0tIy6tAU1Dnbx6C4C2xzn6aSUHA7la6h',
#         }
#     files = {'file': open(path, 'rb')}
#     url = 'https://picui.cn/api/v1/upload'
#     response = requests.post(url, files=files, headers=headers)
#     response_data = response.json()
#     tmp=str(response_data['data']['links']['url'])
#     # print(tmp)
#     return tmp
#     # print(json.dumps(response_data, indent=4))
#     # print(U)


#垃圾识别接口
app = Flask(__name__)
# 保存上传文件的目标目录
UPLOAD_FOLDER = 'C:/Users/admin/Desktop'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/upload_image', methods=['POST'])
def upload_image():
    if 'file' not in request.files:
        return 'No file part'
    
    file = request.files['file']

    if file.filename == '':
        return 'No selected file'

    if file:
        # 保存上传的文件到指定目录
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], 'garbage.jpg'))
        a = recognition(upload(os.path.join(app.config['UPLOAD_FOLDER'], 'garbage.jpg')))
        print(a)
        return a

@app.route('/upload_text', methods=['POST'])
def upload_text():
    data = request.data.decode('utf-8')  # 解码接收到的数据
    lst = data.split('|')
    str = ''
    if lst[0][0]:
        str+='用户体验'
    if lst[0][1]:
        if len(str)>0:
            str+=','
        str+='识别偏差'
    if lst[0][2]:
        if len(str)>0:
            str+=','
        str+='功能建议'
    if lst[0][3]:
        if len(str)>0:
            str+=','
        str+='分类扩充'
    if lst[0][4]:
        if len(str)>0:
            str+=','
        str+='其他问题'
    if lst[0][5]:
        if len(str)>0:
            str+=','
        str+='好评推荐'
    
    insert_feedback(str,lst[1])
    return "Successfully"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)