# -*- coding: utf-8 -*-
"""中台：资讯发布管理（标题+摘要+正文+封面图，H5 首页展示最新若干条）。"""
import os
import uuid
from flask import render_template, request, redirect, url_for, flash, current_app, jsonify
from flask_login import login_required

from app.models import Article
from app.extensions import db
from app.admin import bp
from app.admin.views import _admin_only
from app.services import log_action

ALLOWED_IMG = {"png", "jpg", "jpeg", "gif", "webp"}


@bp.route("/articles")
@login_required
def articles():
    _admin_only()
    items = Article.query.order_by(Article.sort.desc(), Article.id.desc()).all()
    return render_template("admin/article_list.html", articles=items, active="articles")


@bp.route("/articles/new", methods=["GET", "POST"])
@bp.route("/articles/<int:id>/edit", methods=["GET", "POST"])
@login_required
def article_edit(id=None):
    _admin_only()
    a = Article.query.get_or_404(id) if id else Article(status="published", sort=0)
    if request.method == "POST":
        a.title = request.form.get("title", "").strip()
        a.summary = request.form.get("summary", "").strip()
        a.content = request.form.get("content", "").strip()
        a.sort = request.form.get("sort", 0, type=int)
        a.status = request.form.get("status", "published")
        f = request.files.get("cover")
        if f and f.filename and "." in f.filename and \
                f.filename.rsplit(".", 1)[1].lower() in ALLOWED_IMG:
            ext = f.filename.rsplit(".", 1)[1].lower()
            fn = "article/%s.%s" % (uuid.uuid4().hex, ext)
            path = os.path.join(current_app.config["UPLOAD_DIR"], fn)
            os.makedirs(os.path.dirname(path), exist_ok=True)
            f.save(path)
            a.cover = "/uploads/" + fn
        if request.form.get("clear_cover"):
            a.cover = None
        if not a.title:
            flash("标题必填", "danger")
        else:
            if id is None:
                db.session.add(a)
            db.session.commit()
            log_action("article_create" if id is None else "article_edit",
                       target_type="article", target_id=a.id, summary="资讯：%s" % a.title)
            flash("已保存", "success")
            return redirect(url_for("admin.articles"))
    return render_template("admin/article_form.html", a=a, active="articles", is_new=(id is None))


@bp.route("/articles/upload-img", methods=["POST"])
@login_required
def article_upload_img():
    """正文插图上传：返回 url，前端在 textarea 光标处插入 {{IMG:url}} 标记（H5 渲染为图片）。"""
    _admin_only()
    f = request.files.get("file")
    if not f or not f.filename or "." not in f.filename or \
            f.filename.rsplit(".", 1)[1].lower() not in ALLOWED_IMG:
        return jsonify({"error": "请上传图片（png/jpg/jpeg/gif/webp）"}), 400
    ext = f.filename.rsplit(".", 1)[1].lower()
    fn = "article/%s.%s" % (uuid.uuid4().hex, ext)
    path = os.path.join(current_app.config["UPLOAD_DIR"], fn)
    os.makedirs(os.path.dirname(path), exist_ok=True)
    f.save(path)
    return jsonify({"url": "/uploads/" + fn})


@bp.route("/articles/<int:id>/delete", methods=["POST"])
@login_required
def article_delete(id):
    _admin_only()
    a = Article.query.get_or_404(id)
    title = a.title
    db.session.delete(a)
    log_action("delete_article", target_type="article", target_id=id,
               summary="删除资讯：%s" % title, commit=False)
    db.session.commit()
    flash("已删除", "success")
    return redirect(url_for("admin.articles"))
