import pymysql
import requests
from datetime import datetime
from urllib.parse import urlparse


def check_website_accessibility(url):
    """
    检查网站是否可以直接访问
    返回: True(可访问) 或 False(不可访问)
    """
    try:
        # 设置请求头，模拟浏览器访问
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
        }

        # 设置超时时间为10秒
        response = requests.get(url, headers=headers, timeout=10)

        # 如果状态码是2xx或3xx，认为可以访问
        if response.status_code < 400:
            return True
        return False
    except (requests.exceptions.RequestException, requests.exceptions.Timeout):
        return False


def update_database_record(connection, record_id, accessible):
    """
    更新数据库记录
    """
    try:
        with connection.cursor() as cursor:
            current_date = datetime.now().strftime("%Y/%m/%d")

            if not accessible:
                # 如果不可访问，在memo字段前添加检测信息
                update_sql = """
                UPDATE target_website 
                SET memo = CONCAT(%s, IFNULL(memo, '')) 
                WHERE id = %s
                """
                memo_prefix = f"{current_date}检测无法直接访问\n"
                cursor.execute(update_sql, (memo_prefix, record_id))
            else:
                # 如果可访问，可以选择不更新或添加其他信息
                # 这里我们不做任何操作，或者可以添加成功检测的信息
                pass

        connection.commit()
    except Exception as e:
        print(f"更新数据库记录时出错: {e}")
        connection.rollback()


def main():
    # 数据库连接配置 - 请替换为你的实际配置
    db_config = {
        'host': '47.113.231.200',
        'port': 28089,  # MySQL默认端口
        'user': 'root',
        'password': 'passok123A',
        'db': 'oscm',
        'charset': 'utf8mb4',
        'cursorclass': pymysql.cursors.DictCursor
    }

    try:
        # 连接数据库
        connection = pymysql.connect(**db_config)

        # 查询所有目标网站
        with connection.cursor() as cursor:
            sql = "SELECT id, site_name, start_url, memo FROM target_website"
            cursor.execute(sql)
            websites = cursor.fetchall()

            print(f"共找到 {len(websites)} 个网站需要检测")

            for website in websites:
                website_id = website['id']
                site_name = website['site_name']
                start_url = website['start_url']

                print(f"正在检测: {site_name} ({start_url})")

                # 确保URL有协议头
                if not urlparse(start_url).scheme:
                    start_url = 'http://' + start_url

                # 检测网站可访问性
                accessible = check_website_accessibility(start_url)

                if accessible:
                    print(f"  √ 可访问")
                else:
                    print(f"  × 无法直接访问")

                # 更新数据库记录
                update_database_record(connection, website_id, accessible)

    except Exception as e:
        print(f"程序运行出错: {e}")
    finally:
        if 'connection' in locals() and connection.open:
            connection.close()
        print("检测完成，数据库连接已关闭")


if __name__ == "__main__":
    main()
