from flask import Flask,  render_template, flash, session, redirect, url_for, request
from form import LoginForm, PassForm, TeaInfoForm, EvaInfoForm
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin


app = Flask(__name__)
app.config['SECRET_KEY'] = '123'
#设置密钥
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:10044006Lxlx@localhost:3306/fkkk'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
# 是否追踪数据库修改，
app.config['SQLALCHEMY_ECHO'] = True
# 是否显示底层执行的SQL语句
db = SQLAlchemy(app)
# 数据库实例,关联flask 项目

#  用户表
class USER(db.Model):
    __table__name = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(45))
    password = db.Column(db.String(45))
    stu_id = db.Column(db.String(45), db.ForeignKey('stu_info.stu_id'))
    tea_id = db.Column(db.String(45), db.ForeignKey('tea_info.tea_id'))
    status = db.Column(db.String(45))

    def __repr__(self):
        return 'USER:%s' % self.username


#  创建教师信息表数据库模型
class TeaInfo(db.Model):
    __table__name = 'tea_info'
    tea_id = db.Column(db.String(45), primary_key=True)
    name = db.Column(db.String(45))
    tec_title = db.Column(db.String(45))
    department = db.Column(db.String(45))
    gender = db.Column(db.String(45))
    en_year = db.Column(db.String(45))
    birthday = db.Column(db.String(45))
    email = db.Column(db.String(45))
    number = db.Column(db.String(45))
    pol_status = db.Column(db.String(45))
    edu_background = db.Column(db.String(45))
    address = db.Column(db.String(45))
    user = db.relationship('USER', backref=db.backref('tea_info'), uselist=False)

    def __repr__(self):
        return 'TeaInfo:%s' % self.name


# 学生和课程关联信息表
registrations = db.Table('registrations',
                         db.Column('stu_id', db.String(45), db.ForeignKey('stu_info.stu_id')),
                         db.Column('course_id', db.String(45), db.ForeignKey('course_info.course_id'))
                         )

# 教师和课程关联信息表
tea_course = db.Table('tea_course',
                      db.Column('tea_id', db.String(45), db.ForeignKey('tea_info.tea_id')),
                      db.Column('course_id', db.String(45), db.ForeignKey('course_info.course_id'))
                      )


# 学生信息表
class StuInfo(db.Model):
    __table__name = 'stu_info'
    stu_id = db.Column(db.String(45), primary_key=True)
    name = db.Column(db.String(45))
    grade = db.Column(db.String(45))
    department = db.Column(db.String(45))
    gender = db.Column(db.String(45))
    en_year = db.Column(db.String(45))
    birthday = db.Column(db.String(45))
    email = db.Column(db.String(45))
    number = db.Column(db.String(45))
    pol_status = db.Column(db.String(45))
    edu_background = db.Column(db.String(45))
    address = db.Column(db.String(45))
    user = db.relationship('USER', backref=db.backref('stu_info'), uselist=False)

    def __repr__(self):
        return 'StuInfo:%s' % self.name


# 课程信息表
class CourseInfo(db.Model):
    __table__name = 'course_info'
    course_id = db.Column(db.String(45), primary_key=True)
    course_name = db.Column(db.String(45))
    course_teacher = db.Column(db.String(45))
    course_credit = db.Column(db.String(45))
    course_time = db.Column(db.String(45))
    stu_info = db.relationship('StuInfo',
                               secondary=registrations,
                               backref=db.backref('course_info', lazy='dynamic'),
                               lazy='dynamic'
                               )
    tea_info = db.relation('TeaInfo',
                           secondary=tea_course,
                           backref=db.backref('course_info', lazy='dynamic'),
                           lazy='dynamic'
                           )

    def __repr__(self):
        return 'CourseInfo:%s' % self.course_name


# 评教信息表
class EvaInfo(db.Model):
    __table__name = 'eva_info'
    #id = db.Column(db.Integer(), primary_key=True)
    eva_course = db.Column(db.String(45), primary_key=True)
    eva_teacher = db.Column(db.String(45))
    eva_student = db.Column(db.String(45), primary_key=True)
    index_one = db.Column(db.Integer())
    index_two = db.Column(db.Integer())
    index_three = db.Column(db.Integer())
    index_four = db.Column(db.Integer())
    opinion = db.Column(db.String(45))

    def __repr__(self):
        return 'EvaInfo:%s' % self.eva_student


@app.route('/mycourse')
def mycourse():
    username = session.get('username')
    user = StuInfo.query.filter_by(name=username).first()
    course = user.course_info.all()
    eva_info = EvaInfo.query.with_entities(EvaInfo.eva_teacher, EvaInfo.eva_student)
    return render_template('mycourse.html', stu_course=course, eva_info=eva_info, username=username)


@app.route('/courseinfo')
def courseinfo():
    user = USER.query.filter_by(username=session.get('username')).first()
    courseid = request.args.get('course_id')
    course = CourseInfo.query.filter_by(course_id=courseid).first()
    context = {
        'userstatus': user.status,
        'courseid': course.course_id,
        'coursename': course.course_name,
        'courseteacher': course.course_teacher,
        'coursecredit': course.course_credit,
        'coursetime': course.course_time
    }
    return render_template('courseinfo.html', **context)


@app.route('/info')
def info():

    return render_template('info.html')


@app.route('/pass', methods=['GET', 'POST'])
def pas():
    form = PassForm()
    if form.validate_on_submit():
        print('验证通过')
        mpass = request.form.get('mpass')
        #print(mpass)
        newpass = request.form.get('newpass')
        #print(newpass)
        username = session.get('username')
        user = USER.query.filter_by(username=username).first()
        if user and user.password == mpass:
            user.password = newpass
            db.session.commit()
            return redirect(url_for('info'))
        else:
            return '修改失败'
    return render_template('pass.html', form=form, username=session.get('username'))


@app.route('/tea_info', methods=['GET', 'POST'])
def tea_info():
    form = TeaInfoForm()
    user = TeaInfo.query.filter_by(name=session.get('username')).first()
    if form.validate_on_submit():
        tec_title = request.form.get('tec_title')
        department = request.form.get('department')
        gender = request.form.get('gender')
        en_year = request.form.get('en_year')
        birthday = request.form.get('birthday')
        email = request.form.get('email')
        number = request.form.get('number')
        pol_status = request.form.get('pol_status')
        edu_background = request.form.get('edu_background')
        address = request.form.get('address')
        user.address = address
        user.edu_background = edu_background
        user.pol_status = pol_status
        user.number = number
        user.email = email
        user.birthday = birthday
        user.en_year = en_year
        user.gender = gender
        user.department = department
        user.tec_title = tec_title
        db.session.commit()
    context = {
        'tea_id': user.tea_id,
        'name': user.name,
        'tec_title': user.tec_title,
        'department': user.department,
        'gender': user.gender,
        'en_year': user.en_year,
        'birthday': user.birthday,
        'email': user.email,
        'number': user.number,
        'pol_status': user.pol_status,
        'edu_background': user.edu_background,
        'address': user.address
    }
    return render_template('tea_info.html', **context, form=form)


@app.route('/stu_info')
def stu_info():
    user = StuInfo.query.filter_by(name=session.get('username')).first()
    context = {
        'stu_id': user.stu_id,
        'name': user.name,
        'tec_title': user.grade,
        'department': user.department,
        'grade': user.grade,
        'gender': user.gender,
        'en_year': user.en_year,
        'birthday': user.birthday,
        'email': user.email,
        'number': user.number,
        'pol_status': user.pol_status,
        'edu_background': user.edu_background,
        'address': user.address
    }
    return render_template('stu_info.html', **context)


@app.route('/teacourse')
def teacourse():
    user = TeaInfo.query.filter_by(name=session.get('username')).first()
    session['tea_id'] = user.tea_id
    teacher = TeaInfo.query.get(session.get('tea_id'))
    # print(student.name)
    teacourse = teacher.course_info.all()
    return render_template('teacourse.html', teacourse=teacourse)


@app.route('/eva_result')
def eva_result():
    courseid = request.args.get('course_id')
    coursename = request.args.get('course_name')
    courseteacher = request.args.get('course_teacher')
    course_info = EvaInfo.query.filter_by(eva_course=coursename, eva_teacher=courseteacher)
    count = 0
    j = 0
    sum1 = []
    sum2 = []
    sum3 = []
    sum4 = []
    for i in course_info:
        sum1.append(i.index_one)
        sum2.append(i.index_two)
        sum3.append(i.index_three)
        sum4.append(i.index_four)
        count += 1
    su1 = sum(sum1)
    su2 = sum(sum2)
    su3 = sum(sum3)
    su4 = sum(sum4)
    return render_template('eva_result.html', courseid=courseid, coursename=coursename, courseteacher=courseteacher
                           , course_info=course_info, su1=su1, su2=su2, su3=su3, su4=su4, count=count)


@app.route('/eva_teacher', methods=['GET', 'POST'])
def eva_teacher():
    username = session.get("username")
    courseid = request.args.get('course_id')
    coursename = request.args.get('course_name')
    courseteacher = request.args.get('course_teacher')
    form = EvaInfoForm()
    try:
        if form.validate_on_submit():
            index_one = request.form.get('index_one')
            index_two = request.form.get('index_two')
            index_three = request.form.get('index_three')
            index_four = request.form.get('index_four')
            opinion = request.form.get('opinion')
            eva_info = EvaInfo(eva_course=coursename, eva_teacher=courseteacher, eva_student=username,
                           index_one=index_one, index_two=index_two, index_three=index_three,
                           index_four=index_four, opinion=opinion)
            db.session.add(eva_info)
            db.session.commit()
            return redirect(url_for('info'))
    except:
        return "不可重复评教"
    return render_template('eva_teacher.html', form=form, courseid=courseid, coursename=coursename, courseteacher=courseteacher, username=username)


@app.route('/stu')
def stu():
    return render_template('stu.html', username=session.get('username'))


@app.route('/tea')
def tea():
    return render_template('tea.html', username=session.get('username'))


@app.route('/', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    # username = form.username.data
    # password = form.password.data
    if form.validate_on_submit():
        session['username'] = request.form.get('username', None)
        status = request.form.get('status')
        #status = request.form.get('status', None)
        user = USER.query.filter_by(username=session.get('username')).first()
        #if not user:
        #    flash('该用户不存在')
        #    flash('密码错误')
        if user and request.form.get('password') == user.password:
            if user.status == '0':
                if status != user.status:
                    flash('用户类型错误')
                else:
                    return render_template('stu.html', username=session.get('username'))
            else:
                if status != user.status:
                    flash('用户类型错误')
                else:
                    return render_template('tea.html', username=session.get('username'))
    return render_template('login.html', form=form)


if __name__ == '__main__':
    app.run(debug=True)
