from flask import Blueprint, render_template, request, redirect, url_for

from App.models.models import Category

category = Blueprint('category',__name__,url_prefix='/category')

@category.route("/",methods=['GET','POST'])
def manage_category():
    if request.method == 'POST':
        ids = request.form.getlist('id')
        #根据下标获取记录
        i = 0
        for pk in ids:
            category = Category.query.get(int(pk))
            orderbys = request.form.getlist('orderby')
            category.orderby = 0 if orderbys[i]=='None' else int(orderbys[i])
            category.cname = request.form.getlist('cname')[i]
            category.compere = request.form.getlist('compere')[i]
            i += 1
            category.save()

    bigs = Category.query.filter(Category.parentid==0).order_by(Category.orderby).all()
    smalls = Category.query.filter(Category.parentid!=0).order_by(Category.orderby).all()

    return render_template("admin/admin_category.html",**locals())

@category.route("/add/",methods=['GET','POST'])
def add_category():
    if request.method == 'POST':
        category = Category()
        category.cname = request.form.get('cname')
        category.parentid = int(request.form.get('parentid'))
        category.save()
        return redirect(url_for('category.manage_category'))
    return render_template("admin/admin_category_add.html",bigs = Category.get_bigs())