# -*- coding: utf-8 -*-
"""中台后台：登录、仪表盘、各模块入口。
门店/店员 CRUD 在 stores.py；题库/考试/积分/商城/集赞在各自模块（P2-P5 实现）。
"""
from flask import (render_template, request, redirect,
                   url_for, flash, abort)
from flask_login import login_user, logout_user, login_required, current_user

from app.models import (Staff, Store, Chain, Product, Exam,
                        LikeSubmission, ExamRecord, OperationLog)
from app.extensions import db
from app.services import log_action
from app.admin import bp


# -------------------- 登录/登出 --------------------

@bp.route("/login", methods=["GET", "POST"])
def login():
    if current_user.is_authenticated and getattr(current_user, "is_admin", False):
        return redirect(url_for("admin.dashboard"))
    if request.method == "POST":
        phone = request.form.get("phone", "").strip()
        pwd = request.form.get("password", "")
        # 后台只登录管理员账号（同一手机号可同时是前台店员，按 role 隔离互不影响）
        staff = Staff.query.filter(
            Staff.phone == phone, Staff.role.in_(("super", "admin"))).first()
        if (staff and staff.is_admin and staff.status == "active"
                and staff.check_password(pwd)):
            login_user(staff)
            return redirect(url_for("admin.dashboard"))
        flash("手机号或密码错误，或无后台权限", "danger")
    return render_template("admin/login.html")


@bp.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for("admin.login"))


def _admin_only():
    if not current_user.is_authenticated or not current_user.is_admin:
        abort(403)


# -------------------- 仪表盘 --------------------

@bp.route("/")
@login_required
def dashboard():
    _admin_only()
    stats = {
        "staff": Staff.query.filter_by(role="staff", deleted=False).count(),
        "stores": Store.query.count(),
        "chains": Chain.query.count(),
        "products": Product.query.filter_by(status="on").count(),
        "exams_open": Exam.query.filter_by(status="open").count(),
        "pending_likes": LikeSubmission.query.filter_by(status="pending").count(),
        "today_records": ExamRecord.query.count(),
    }
    return render_template("admin/dashboard.html", stats=stats, active="dashboard")


# -------------------- 各模块占位（P2-P5 逐步实现）--------------------

# 各业务模块见: stores.py / points.py / questions.py / exams.py / shop.py / likes.py


# -------------------- 操作日志 --------------------

@bp.route("/logs")
@login_required
def op_logs():
    _admin_only()
    action = request.args.get("action", "").strip()
    admin_id = request.args.get("admin_id", type=int)
    query = OperationLog.query
    if action:
        query = query.filter_by(action=action)
    if admin_id:
        query = query.filter_by(admin_id=admin_id)
    logs = query.order_by(OperationLog.id.desc()).limit(300).all()
    actions = [r[0] for r in db.session.query(OperationLog.action).distinct().all() if r[0]]
    admins = Staff.query.filter(Staff.role.in_(("super", "admin"))).order_by(Staff.name).all()
    return render_template("admin/op_logs.html", logs=logs, actions=actions, admins=admins,
                           action=action, admin_id=admin_id, active="logs")


# -------------------- 我的信息（改姓名/手机/密码）--------------------

@bp.route("/profile", methods=["GET", "POST"])
@login_required
def profile():
    _admin_only()
    s = Staff.query.get(current_user.id)
    if request.method == "POST":
        name = request.form.get("name", "").strip()
        phone = request.form.get("phone", "").strip()
        old_pwd = request.form.get("old_password", "").strip()
        new_pwd = request.form.get("new_password", "").strip()
        if not name or not phone:
            flash("姓名和手机号必填", "danger")
        elif Staff.query.filter(Staff.phone == phone, Staff.role.in_(("super", "admin")),
                                Staff.id != s.id).first():
            flash("该手机号已被其他管理员占用", "danger")
        elif new_pwd and not old_pwd:
            flash("修改密码需填写旧密码", "danger")
        elif new_pwd and not s.check_password(old_pwd):
            flash("旧密码不正确", "danger")
        else:
            s.name = name
            s.phone = phone
            pwd_changed = bool(new_pwd)
            if pwd_changed:
                s.set_password(new_pwd)
            db.session.commit()
            log_action("profile_edit", target_type="staff", target_id=s.id,
                       summary="修改个人信息：%s %s%s" % (name, phone, "（含改密）" if pwd_changed else ""))
            flash("已保存" + ("，密码已更新（下次登录用新密码）" if pwd_changed else ""), "success")
            return redirect(url_for("admin.profile"))
    return render_template("admin/profile.html", s=s, active="profile")
