from web.controller.admin import route_admin
from common.libs.WebHelper import ops_render
from common.model.admin import Admin

from flask import request, jsonify
from application import db

import time


@route_admin.route('/manager', methods=['GET', 'POST'])
def manager_index():
    resp = {'code': 200, 'info': {}}
    req = request.values

    id = req['id'] if 'id' in req else -1
    name = req['name'] if 'name' in req else -1
    if name == '':
        resp['msg'] = '名字未填写'
        return jsonify(resp)
    username = Admin.query.filter_by(username=name).first()
    if username != None:
        resp['msg'] = '名字已存在'
        return jsonify(resp)
    if request.method == 'GET':
        if id == -1:
            return ops_render('/admin/manager.html', resp)
        info = Admin.query.filter_by(id=id).first()
        resp['info'] = {
            'name': info.username,
            'id': id
        }
        return ops_render('/admin/manager.html', resp)
    power = req['power'] if 'power' in req else -1
    info = Admin()
    info.username = req['name']
    info.power = power
    info.last_time = int(time.time())
    info.password = '123456'
    db.session.add(info)
    db.session.commit()

    resp['msg'] = '操作成功'
    return jsonify(resp)
