import json
import os
from datetime import datetime
import requests
import PIL
from PIL import Image
from all_connect import ConnectSpider
import time
import shutil
import re
from pathlib import Path
import shutil
import traceback
from pathlib import Path
import tempfile

# 最大像素点
PIL.Image.MAX_IMAGE_PIXELS = 933120000


def generate_thumbnail_240(input_image_path, output_image_path):
    # 打开图片
    with Image.open(input_image_path) as img:
        # 获取原始图片大小
        width, height = img.size
        rate = width / height
        targetHeight = 240
        targetWidth = rate * targetHeight

        # 生成缩略图
        img.thumbnail((targetWidth, targetHeight))
        if img.mode == "RGBA":
            img = img.convert("RGB")
        # 保存缩略图
        img.save(output_image_path)
    pass


def generate_thumbnail_big(input_image_path, output_image_path):
    # 打开图片
    with Image.open(input_image_path) as img:
        # 获取原始图片大小
        width, height = img.size
        if width > height:
            targetWidth = 1500
            targetHeight = (height / width) * targetWidth
        else:
            targetHeight = 1300
            targetWidth = (width / height) * targetHeight

        # 生成缩略图
        img.thumbnail((targetWidth, targetHeight))
        if img.mode == "RGBA":
            img = img.convert("RGB")

        # 保存缩略图
        img.save(output_image_path)


def exec_sql(sql: str, paramMap: dict):
    from sqlalchemy import text
    with db_engine.connect() as connection:
        trans = connection.begin()
        connection.execute(text(sql), paramMap)
        trans.commit()
    pass


def read_sql(sql: str):
    import pandas as pd
    with db_engine.connect() as connection:
        return pd.read_sql(sql, con=connection)


db_engine = ConnectSpider().db_engine192
# 图片目录
all_pic_dir = "/home/wangjing/picture_material/stock_summery/all_pic"

# 成功后转存的图片目录
all_pic_success_dir = "/home/wangjing/picture_material/stock_summery/all_pic_success"


class UploadPicture():
    def __init__(self):
        self.count = 0
        pass

    def upload_file(self, img_id, file_path):
        # 检查图片是否已上传
        success_flag = False
        sql = f"SELECT err_msg FROM stock_image_detail_wj WHERE image_id = '{img_id}';"
        result_df = read_sql(sql)

        # # 检查是否有任何一个 err_msg 等于 'success'
        # if 'success' in result_df['err_msg'].values:
        #     print(f"img_id:{img_id} 已上传！跳过")
        #     return True

        # result_df = read_sql(f"select max(upload_time) as upload_time from stock_image_detail_wj where image_id = '{img_id}';")
        # upload_time = list(result_df['upload_time'])[0]
        # # 已经上传过不上传
        # if upload_time is not None:
        #     print(f"img_id:{img_id} 已上传！跳过")
        #     return True

        # 转移到临时文件夹
        tmpdir = Path(tempfile.gettempdir(), "shutterstock_upload")
        # 使用前先清空
        shutil.rmtree(tmpdir, ignore_errors=True)
        tmpdir.mkdir(parents=True, exist_ok=True)
        filename = os.path.basename(file_path)
        suffix = os.path.splitext(file_path)[-1]
        target_path = os.path.join(tmpdir, filename)
        shutil.copy(file_path, target_path)
        # 生成缩略图
        big_img_path = os.path.join(tmpdir, "thumbnail_image_big" + suffix)
        img_240_path = os.path.join(tmpdir, "thumbnail_image_240" + suffix)
        try:
            generate_thumbnail_big(target_path, os.path.join(tmpdir, big_img_path))
            generate_thumbnail_240(target_path, os.path.join(tmpdir, img_240_path))
        except Exception as ex:
            print(f"文件{filename}生成缩略图失败:{traceback.format_exc()}")
            return False
            pass
        retry_time = 1

        while retry_time < 3:
            url = 'http://wx.yswg.com.cn:8000/microservice-visual/visual/fileSystem/shutterstock_upload'
            # url = "http://192.168.2.97:6661/microservice-visual/visual/fileSystem/shutterstock_upload"
            # url = 'http://localhost:8600/visual/fileSystem/shutterstock_upload'

            files = {
                'file': open(target_path, 'rb'),
                'file_big': open(big_img_path, 'rb'),
                'file_240': open(img_240_path, 'rb'),
            }
            body = {'token': "dacce869-0471-4ec7-ac50-3b3b1ec22c87"}
            try:
                response = requests.post(url, files=files, data=body, timeout=600)

                response_data = json.loads(response.text)
                formatted_time = datetime.now().strftime('%Y/%m/%d %H:%M:%S')

                if response_data.get('code') == 200:
                    print(f"{filename} 上传成功 第{self.count}个,{formatted_time}")
                    exec_sql(
                        f"""update stock_image_detail_wj set upload_time=:upload_time,err_msg=:err_msg where image_id = :image_id""",
                        {"upload_time": formatted_time, "err_msg": "success", "image_id": img_id})
                    self.count = self.count + 1
                    success_flag = True
                    break
                else:
                    print(f"{filename} 上传失败 第{self.count}个 {formatted_time}: {response_data}")
                    errMsg = response_data.get("msg")
                    if errMsg == '您上传的文件已经被上传过~!请勿重复上传!':
                        exec_sql(
                            f"""update stock_image_detail_wj set upload_time=:upload_time,err_msg=:err_msg where image_id = :image_id""",
                            {"upload_time": formatted_time, "err_msg": "success", "image_id": img_id})
                        self.count = self.count + 1
                        success_flag = True
                        break
                    else:
                        exec_sql(
                            f"""update stock_image_detail_wj set upload_time=:upload_time,err_msg=:err_msg where image_id = :image_id""",
                            {"upload_time": formatted_time, "err_msg": json.dumps(response_data), "image_id": img_id})

                        if "" in errMsg:
                            # 此处超时等
                            pass

                        retry_time = retry_time + 1
            finally:
                # 关闭文件流
                for file in files.values():
                    file.close()

        # 清空临时单个上传
        shutil.rmtree(tmpdir, ignore_errors=True)
        return success_flag

    def upload_dir(self, folder_path):
        # 支持的图像文件扩展名列表
        image_extensions = ['.jpg', '.jpeg', '.png']
        # 获取文件夹中所有支持的图像文件，并按最后修改时间排序
        files = []
        for file_name in os.listdir(folder_path):
            if any(file_name.lower().endswith(ext) for ext in image_extensions):
                file_path = os.path.join(folder_path, file_name)
                mtime = os.path.getmtime(file_path)
                files.append((file_name, mtime))

        # 按文件的最后修改时间排序
        files_sorted = sorted(files, key=lambda x: x[1])
        # 成功后转移
        Path(all_pic_success_dir).mkdir(parents=True, exist_ok=True)
        for file_name, _ in files_sorted:
            image_id_list = re.findall(r"^(\d+)\+", file_name)
            # 判断是不是int
            if len(image_id_list) == 0:
                print(f"文件{file_name}不是正常规则的图片命名！！")
                continue
            image_id_str = image_id_list[0]

            file_path = os.path.join(folder_path, file_name)
            success_flag = self.upload_file(image_id_str, file_path)
            if success_flag:
                # 转移到上传成功的文件夹中
                shutil.move(file_path, os.path.join(all_pic_success_dir, file_name))
                pass

    def run(self):
        folder_path_list = [
            "xiezhihao@yswg.com.cn",
            "24016587887",
            "daiting@yswg.com.cn",
            "yangzinan@yswg.com.cn",
            "danqingmei30",
            "352422819@qq.com",
            "xuyuanlian@yswg.com.cn",
            "496775268@qq.com",
            "878097683@qq.com",
            "991450084@qq.com",
            "yangxia@yswg.com.cn",
            "zouxiayan@yswg.com.cn",
            "laiyawen@yswg.com.cn",
            "1060103503@qq.com",
            "1120841348@qq.com",
            "1014703046@qq.com",
            "shuqian@yswg.com.cn",
            "wengdan300",
            "jiangbin@yswg.com.cn",
            "yangxuanwei54",
            "1196846022@QQ.COM",
            "liyun1@yswg.com.cn",
            "lizhili@yswg.com.cn",
            "chenxiaowei@yswg.com.cn",
            "1101549094@qq.com",
            "liulujun@yswg.com.cn",
            "fanglidong@yswg.com.cn",
            "jiangyuan1@yswg.com.cn",
            "xujianbo@yswg.com.cn",
            "xujing@yswg.com.cn",
            "lujun@yswg.com.cn",
            "liujia@yswg.com.cn",
            "weixiaoling@yswg.com.cn",
            "1073463224",
        ]
        for account_id in folder_path_list:
            if 8 <= datetime.now().hour < 18:
                print(f"当前时间 {datetime.now().hour} 点，超出运行时段 18:00–08:00，退出循环。")
                break
            print(f"当前时间 {datetime.now().hour} 点，开始处理账户 {account_id}。")
            if '@' in account_id:
                account_id_tmp = account_id.split('@')[0]
            else:
                account_id_tmp = account_id
            folder_path = os.path.join(all_pic_dir, account_id_tmp)

            # 带重试地执行上传目录
            success = False
            for attempt in range(3):  # 最多重试3次
                try:
                    self.upload_dir(folder_path)
                    success = True
                    break
                except (
                        requests.exceptions.ConnectionError,
                        requests.exceptions.Timeout,
                        requests.exceptions.RequestException
                ) as e:
                    print(f"第 {attempt + 1} 次上传失败：{e}，正在重试...")
                    time.sleep(5)  # 等待5秒后重试

            if not success:
                print(f"⚠️ 文件夹 [{folder_path}] 上传失败，请检查网络或服务器状态。")


if __name__ == '__main__':
    handler = UploadPicture()
    handler.run()
