#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""验证 /originals/ 三个新功能：①字段可点即搜 ②ID 外链图标 ③正文访问次数。"""
import re
import sqlite3
import urllib.parse
import urllib.request

BASE = "http://127.0.0.1:8000"


def fetch(path):
    return urllib.request.urlopen(BASE + path, timeout=30).read().decode("utf-8", "ignore")


# ── ① 列表页：找含 7 位 / 9 位 id_code 的记录 ─────────────────────────
conn = sqlite3.connect("/root/originals.db")
c7 = conn.execute("SELECT id_code FROM tsk_data WHERE LENGTH(TRIM(id_code))=7 LIMIT 1").fetchone()[0]
c9 = conn.execute("SELECT id_code FROM tsk_data WHERE LENGTH(TRIM(id_code))=9 LIMIT 1").fetchone()[0]
kw = "自贡中天胜新材料科技有限公司"
print("样例码: 7位=%s  9位=%s" % (c7, c9))
conn.close()

h = fetch("/originals/?q=" + urllib.parse.quote(kw))
print("\n=== ① 列表页（q=%s）===" % kw)
print("  含 <span class=vc>（访问次数）  :", "vc" in h and "正文被打开的次数" in h)
print("  含 selbar（选中即搜脚本）      :", "selbar" in h and "encodeURIComponent" in h)
print("  含 class=kw（字段可点搜索）    :", 'class=kw' in h or "class=\"kw" in h)
print("  结果条数                        :", h.count("class=result-item"))
m = re.findall(r'href="(https://ed\.industrialinfo\.com[^"]+)"', h)
print("  外链 URL 样例                  :", m[:3])
print("  7 位码是否拼成 plant/:",
      bool(re.search(r"ED/plant/" + re.escape(c7), h)) or "（本页无该码）")
print("  9 位码是否拼成 confirmedProject/:",
      bool(re.search(r"ED/confirmedProject/" + re.escape(c9), h)) or "（本页无该码）")
vc = re.findall(r'class=vc title="[^"]*">([^<]+)</span>', h)
print("  访问次数展示样例               :", vc[:5])

# ── ② 详情页：访问次数自增 ───────────────────────────────────────────
conn = sqlite3.connect("/root/originals.db")
rid, icode = conn.execute(
    "SELECT id, id_code FROM tsk_data WHERE LENGTH(TRIM(id_code))=9 LIMIT 1").fetchone()
conn.close()
print("\n=== ② 详情页计数（记录 id=%s, id_code=%s）===" % (rid, icode))
for i in range(3):
    d = fetch("/originals/detail?id=%d" % rid)
    got = re.findall(r'正文被打开的次数">[^0-9]*([0-9]+)\s*次', d)
    print("  第 %d 次打开 → 页面显示访问次数 = %s" % (i + 1, got))

print("\n=== ③ 计数库落盘 ===")
vc_db = sqlite3.connect("/root/originals_views.db")
n = vc_db.execute("SELECT COUNT(*) FROM view_count").fetchone()[0]
print("  /root/originals_views.db 表 view_count 行数 =", n)
for r in vc_db.execute("SELECT id_code, n, last_view FROM view_count ORDER BY n DESC LIMIT 5"):
    print("     %-12s %d 次  最后 %s" % r)
vc_db.close()
