import os
import re
import json
from bs4 import BeautifulSoup
import paramiko

# 1. 处理所有json文件
json_dir = '/www/wwwroot/file.jsfsdata.com/rs'
for filename in os.listdir(json_dir):
    if filename.endswith('.json'):
        file_path = os.path.join(json_dir, filename)
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        # 替换内容
        content = content.replace('["', '')
        content = content.replace('\"]', '')
        content = content.replace('", "', '<br>')
        # 保存回原文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)

# 2. 处理html文件，替换所有带data-type属性div的内容
html_path = '/www/wwwroot/file.jsfsdata.com/py/chart13.html'
with open(html_path, 'r', encoding='utf-8') as f:
    html = f.read()

soup = BeautifulSoup(html, 'html.parser')
# 查找所有带data-type属性的div
for div in soup.find_all('div', attrs={'data-type': True}):
    dtype = div.get('data-type')
    if dtype:
        # 构建对应json文件名
        json_filename = f'{dtype}套保推荐结果.json'
        json_path = os.path.join(json_dir, json_filename)
        if os.path.exists(json_path):
            with open(json_path, 'r', encoding='utf-8') as f:
                file_content = f.read()
            div.clear()  # 清空原有内容
            div.append(BeautifulSoup(file_content, 'html.parser'))  # 以HTML方式插入内容，<br>不会被转义
        else:
            print(f'未找到对应文件: {json_filename}')

# 3. 替换所有?ver=数字为?ver=数字+1
# 使用正则查找并替换
pattern = re.compile(r'(\?ver=)(\d+)')
def add_one(match):
    return f"{match.group(1)}{int(match.group(2))+1}"
new_html = pattern.sub(add_one, str(soup))

# 保存html
with open(html_path, 'w', encoding='utf-8') as f:
    f.write(new_html)

print('本地处理完成，准备上传到服务器...')

# === SFTP上传部分 ===
# SFTP配置
sftp_host = '8.141.110.228'
sftp_port = 22
sftp_username = 'root'
sftp_password = 'JkdsDa*7UHds'
remote_path = '/www/wwwroot/www.jsfsdata.com/application/index/view/ichart/chart13.html'

try:
    transport = paramiko.Transport((sftp_host, sftp_port))
    transport.connect(username=sftp_username, password=sftp_password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp.put(html_path, remote_path)
    sftp.close()
    transport.close()
    print('上传成功！')
except Exception as e:
    print(f'上传失败: {e}')

# === 上传所有png图片到服务器指定目录 ===
img_remote_dir = '/www/wwwroot/www.jsfsdata.com/public/assets/img'
img_local_dir = '/www/wwwroot/file.jsfsdata.com/rs'

try:
    transport = paramiko.Transport((sftp_host, sftp_port))
    transport.connect(username=sftp_username, password=sftp_password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    for filename in os.listdir(img_local_dir):
        if filename.lower().endswith('.png'):
            local_img_path = os.path.join(img_local_dir, filename)
            remote_img_path = img_remote_dir + '/' + filename
            try:
                sftp.put(local_img_path, remote_img_path)
                print(f'图片上传成功: {filename}')
            except Exception as e:
                print(f'图片上传失败: {filename}, 错误: {e}')
    sftp.close()
    transport.close()
    print('所有PNG图片上传完成！')
except Exception as e:
    print(f'PNG图片批量上传失败: {e}')
