#coding=utf-8
module Mobile
  module Apis
    class Courses < Grape::API
      resource :courses do
        def self.get_service
          CoursesService.new
        end
        desc "获取所有课程"
        params do
          optional :school_id, type: Integer, desc: '传入学校id,返回该学校课程列表'
          requires :per_page_count, type: Integer, desc: '每页总数'
          requires :page, type: Integer, desc: '当前页码'
          optional :token, type: String
        end
        get do
          authenticate!
          cs = CoursesService.new
          courses = cs.user_courses_list(current_user)
          present :data, courses, with: Mobile::Entities::Course,user: current_user
          present :status, 0
        end

        desc "新建课程"
        #current_user当前用户对象（不是id）
        # params[:course][:name]:课程名称
        #params[:course][:password]:密码
        #params[:course][:description]:描述
        #params[:course][:is_public]:是否公开1公开，0私有
        #params[:course][:open_student]:是否公开学生列表1公开，0不公开，不公开时非课程成员无法看到学生列表
        #params[:course][:course_type]:暂时默认给1值。
        #params[:term]：学期（秋季学期或春季学期）
        #params[:time]: 年份（例：2014）
        #params[:setup_time]：暂不传（貌似已经没用了）
        #params[:endup_time]: 暂不传（貌似已经没用了）
        #params[:class_period]:学时总数
        params do
          requires :token, type: String
          requires :name, type: String, desc: '课程名称'
          requires :password, type: String, desc: '密码'
          requires :description, type: String, desc: '描述'
          requires :is_public, type: Integer, desc: '是否公开 1公开 0私有'
          requires :open_student, type: Integer, desc: '是否公开学生列表1公开，0不公开，不公开时非课程成员无法看到学生列表'
          requires :course_type, type:Integer, desc: '暂时传1'
          requires :term, type: String, desc: '学期（秋季学期或春季学期）'
          requires :time, type: String, desc: '年份'
          requires :class_period, type: String, desc: '学时总数'
        end
        post do
          authenticate!
          cs = CoursesService.new
          cs_params = {
            course: params.reject{|k,v| [:term,:time,:class_period].include?(k)},
            term: params[:term],
            time: params[:time],
            class_period: params[:class_period]
          }
          courses = cs.create_course(cs_params, current_user)
          present :data, courses, with: Mobile::Entities::Course,user: current_user
          present :status, 0
        end

        desc "编辑课程"
        params do
          requires :token, type: String
          requires :course_id, type: Integer, desc: '课程id'
          requires :name, type: String, desc: '课程名称'
          requires :password, type: String, desc: '密码'
          requires :description, type: String, desc: '描述'
          requires :is_public, type: Integer, desc: '是否公开 1公开 0私有'
          requires :open_student, type: Integer, desc: '是否公开学生列表1公开，0不公开，不公开时非课程成员无法看到学生列表'
          requires :course_type, type:Integer, desc: '暂时传1'
          requires :term, type: String, desc: '学期（秋季学期或春季学期）'
          requires :time, type: String, desc: '年份'
          requires :class_period, type: String, desc: '学时总数'
        end
        put do
          authenticate!
          cs = CoursesService.new
          cs_params = {
            course: params.reject{|k,v| [:term,:time,:class_period].include?(k)},
            term: params[:term],
            time: params[:time],
            class_period: params[:class_period]
          }
          course = ::Course.find(params[:course_id])
          # 如果没有传密码过来，那就把原来的密码给上，不然会不更新
          if params[:password].nil? || params[:password].blank?
            cs_params[:course][:password] = course[:password]
          end
          cs.edit_course_authorize(current_user,course)
          course = cs.edit_course(cs_params, course,current_user)
          present :data, course, with: Mobile::Entities::Course,user: current_user
          present :status, 0
        end
        post do
        end

        desc "加入课程"
        params do
          requires :token, type: String
          requires :invite_code, type: String, desc: '邀请码'
          requires :teacher_flag, type: Boolean
          requires :assistant_flag, type: Boolean
          requires :student_flag, type: Boolean
        end
        post "join_class" do
          authenticate!

          roles_ids = []
          if params[:teacher_flag]
            roles_ids << "9"
          elsif params[:assistant_flag]
            roles_ids << "7"
          end

          if params[:student_flag]
            roles_ids << "10"
          end

          go_course_group = 0

          if roles_ids.length <= 0
            {status:-1,message:"请至少选择一个角色"}
          else
            cs = CoursesService.new
            status = cs.join_course_roles({role: roles_ids, openid: params[:openid], invite_code: params[:invite_code]}, current_user)
            {
                status: status[:state],
                message:CoursesService::JoinCourseError.message(status[:state]),
                go_coursegroup_flag:status[:go_coursegroup_flag],
                course_id:status[:course_id]
            }
          end
        end


        desc "退出课程"
        params do
          requires :token, type: String
        end
        delete ":id" do
          authenticate!
          cs = CoursesService.new
          status = cs.exit_course({:object_id => params[:id]}, current_user)
          out = {status: status}
          message = case status
                      when 0; "退出成功"
                      when 1; "您不在课程中"
                      when 2; "您还未登录"
                      else; "未知错误，请稍后再试"
                    end
          out.merge(message: message)
        end

        desc "搜索课程"
        params do
          requires :name, type: String, desc: "课程名"
          optional :token, type: String
        end
        get 'search' do
          cs = CoursesService.new
          courses = cs.search_course(params,current_user.nil? ? User.find(2):current_user)
          present :data, courses, with: Mobile::Entities::Course,user: current_user
          present :status, 0
        end

        desc "课程老师列表"
        params do
          requires :token, type: String
          requires :course_id, type: Integer, desc: "课程id"
        end
        get 'teachers' do

          course = Course.find(params[:course_id])

          cs = CoursesService.new
          teachers = cs.course_teacher_or_student_list({role: '1'}, params[:course_id],current_user)

          teachers.each do |m|
            if m[:id] == course.tea_id
              teachers.delete(m)
              teachers.insert(0,m)
              break
            end
          end

          present :data, teachers, with: Mobile::Entities::User
          present :status, 0
        end

        desc "课程学生列表"
        params do
          requires :token, type: String
          requires :course_id, type: Integer, desc: "课程id"
        end
        get 'students' do
          cs = CoursesService.new
          students = cs.course_teacher_or_student_list({role: '2'}, params[:course_id],current_user)
          present :data, students, with: Mobile::Entities::User
          present :status, 0
        end

        desc "课程未审核列表"
        params do
          requires :token, type: String
          requires :course_id, type: Integer, desc: "课程id"
        end
        get 'reviewers' do
          authenticate!
          cs = CoursesService.new
          reviewers = cs.reviewers_list(params[:course_id])
          present :data, reviewers, with: Mobile::Entities::User
          present :status, 0
        end

        desc "课程单个未审核用户信息"
        params do
          requires :token, type: String
          requires :course_id, type: Integer, desc: "课程id"
          requires :user_id, type: Integer, desc: "用户id"
        end
        post 'review_member_info' do
          authenticate!

          cs = CoursesService.new
          result = cs.get_reviewer_info(params)

          present :data, result[:reviewer], with: Mobile::Entities::User
          present :status,result[:status]
        end

        desc "处理教师或助教的身份申请"
        params do
          requires :token, type: String
          requires :course_id, type: Integer, desc: "课程id"
          requires :user_id, type: Integer, desc: "用户id"
          requires :type, type: Integer, desc: "同意或拒绝"
        end
        post 'deal_join_apply' do
          authenticate!

          cs = CoursesService.new
          result = cs.deal_join_apply(params,current_user)

          present :status, result[:status]
          present :message, result[:message]
        end

        desc "设置助教"
        params do
        requires :token,type:String
        requires :user_id,type:Integer,desc: '用户id'
        requires :course_id,type:Integer,desc:'课程id'
        end
        get 'set_user_as_assitant' do
          cs = CoursesService.new
          cs.set_as_assitant_teacher params
          present :status, 0
        end

        desc "删除助教"
        params do
          requires :token,type:String
          requires :user_id,type:Integer,desc: '用户id'
          requires :course_id,type:Integer,desc:'课程id'
        end
        get 'del_user_as_assitant'  do
          cs = CoursesService.new
          cs.del_assitant_teacher params
          present :status, 0
        end

        desc "返回单个课程"
        params do
          requires :id, type: Integer
          requires :token,type:String
        end
        route_param :id do
          get do
            # course = Course.find(params[:id])
            cs = CoursesService.new
            course = cs.show_course(params,current_user)

            if course[:course][:is_delete] == 1
              {status:-1, message: '该班级不存在或已被删除啦' }
            else
              present :data, course, with: Mobile::Entities::Course,user: current_user
              present :status, 0
            end
          end
        end

        desc "获取课程动态"
        params do
          requires :id, type: Integer
          requires :token, type: String
        end
        post 'activities' do
          authenticate!

          user = current_user

          course_types = "('Message','News','HomeworkCommon','Poll','Course')"
          activities = UserActivity.where("(container_type = 'Course' and container_id = #{params[:id]} and act_type in #{course_types})").order('updated_at desc')

          page = params[:page] ? params[:page] : 0
          all_count = activities.count
          activities = activities.limit(10).offset(page * 10)
          count = activities.count
          present :data, activities, with: Mobile::Entities::Activity,user: user
          present :all_count, all_count
          present :count, count
          present :page, page
          present :status, 0
        end

        desc "课程作业列表"
        params do
          requires :token, type: String
        end
        get "homeworks/:id" do
          cs = CoursesService.new
          homeworks = cs.homework_list params,current_user
          present :data, homeworks, with: Mobile::Entities::Homework,user: current_user
          present :status, 0
        end

        desc "课程通知列表"
        params do
          optional :token, type: String
        end
        get ":course_id/news" do
          cs = CoursesService.new
          news = cs.course_news_list params,current_user.nil? ? User.find(2):current_user
          present :data, news, with: Mobile::Entities::News
          present :status, 0
        end

        desc "显示课程通知"
        params do
          optional :token, type: String
        end
        get "news/:id" do
          cs = CoursesService.new
          cs.show_course_news_authorize(current_user.nil? ? User.find(2):current_user)
          news = cs.show_course_news params,current_user.nil? ? User.find(2):current_user
          present :data, news, with: Mobile::Entities::News
          present :status, 0
        end

        desc '用户课程动态'
        params do
          requires :token, type: String
        end
        get "course_dynamic/:id" do
          cs = CoursesService.new
          count = cs.all_course_dynamics(params,current_user)
          present :data, count, with: Mobile::Entities::CourseDynamic
          present :status, 0
        end

        desc '课程课件'
        params do
          requires :token, type: String
          requires :course_id,type: Integer,desc: '课程id'
          optional :name,type:String,desc:'课件名称可能包含的字符'
        end
        post ":course_id/attachments" do
          cs = CoursesService.new
          count = cs.course_attachments params
          present :data, count, with: Mobile::Entities::Attachment,user: current_user
          present :status, 0
        end

        desc '课程学生'
        params do
          requires :token,type:String
          requires :course_id,type:Integer,desc: '课程id'
          optional :name,type:String,desc:'学生的姓名或者登录名或者学号可能包含的字符'
        end
        get ":course_id/members" do
          cs = CoursesService.new
          count = cs.course_members params
          # 我如果在学生当中，那么我将放在第一位
           count.each do |m|
             if m.user.id == current_user.id
               count.delete m
               count.unshift m
             end
           end
          present :data, count, with: Mobile::Entities::Member
          present :status, 0
        end

        desc '查看用户历次作业成绩'
        params do
          requires :token,type:String
          requires :member_id,type:Integer,desc:'课程member_id'
          optional :homeworkName,type:String,desc:'作业名称以及作业名称可能包含的字符'
        end
        get '/show_member_score/:member_id' do
          cs = CoursesService.new
          homeworkscore = cs.show_member_score params
          present :data,homeworkscore,with: Mobile::Entities::Homeworkscore
          present :status,0
        end

        desc '发布课程通知'
        params do
          requires :token,type:String
          requires :course_id,type:Integer,desc:'课程id'
          requires :title,type:String,desc:'通知标题'
          requires :desc,type:String,desc:'通知描述'
        end
        post ':course_id/create_course_notice' do
           cs = CoursesService.new
           news = cs.create_course_notice params,current_user
           present :data,news,with:Mobile::Entities::News
          present :status,0
        end

        desc '总成绩 or 活跃度列表'
        params do
          requires :token,type:String
          requires :course_id,type:Integer,desc:'课程id'
          optional :page,type:Integer,desc:'页码'
          optional :type,type:Integer,desc:'0是活跃度，1是成绩'
        end
        get ':course_id/students_score_list' do
          cs = CoursesService.new
          news = cs.students_score_list params,current_user
          present :data,news[:user_list],with:Mobile::Entities::User
          present :maxSize,news[:max_size]
          present :status,0
        end

        desc '课程某次作业提交列表 并显示成绩'
        params do
          requires :token,type:String
          requires :course_id,type:Integer,desc:'课程id'
          requires :homework_id,type:Integer,desc:'作业id'
          optional :page,type:Integer,desc:'页码'
        end
        get ':course_id/student_works_list' do
          cs = CoursesService.new
          student_works = cs.student_work_list params,current_user
          present :data,student_works,with:Mobile::Entities::StudentWork
          present :status,0
        end

        desc '讨论区信息'
        params do
          requires :token,type:String
          requires :course_id,type:Integer,desc:'课程id'
          optional :page,type:Integer,desc:'页码'
        end
        get ':course_id/board_message_list' do
          cs = CoursesService.new
          board_messages_list = cs.board_message_list params,current_user
          present :data,board_messages_list.all,with:Mobile::Entities::Message
          present :status,0
        end

        desc '讨论区某主题的回复列表'
        params do
          requires :token,type:String
          requires :board_id,type:Integer,desc:'讨论区id'
          requires :msg_id,type:Integer,desc:'讨论主题id'
          optional :page,type:Integer,desc:'页码'
        end
        get ':board_id/board_message_reply_list' do
          cs = Courses.get_service
          board_messages_list = cs.board_message_reply_list params,current_user
          present :data,board_messages_list.all,with:Mobile::Entities::Message
          present :status,0
        end

        desc '讨论区回复'
        params do
          requires :token,type:String
          requires :board_id,type:Integer,desc:'讨论区id'
          requires :parent_id,type:Integer,desc:'本回复父id'
          requires :subject,type:String,desc:'本回复主题'
          requires :content,type:String,desc:'本回复内容'
          requires :root_id,type:Integer,desc:'本回复根id'
          requires :quote,type:String,desc:'本回复引用内容'
        end
        post ':board_id/board_message_reply' do
          cs = Courses.get_service
          board_messages = cs.board_message_reply params,current_user
          present :data,board_messages,with:Mobile::Entities::Message
          present :status,0
        end


        desc '获取测验列表'
        params do
          requires :token, type:String
        end
        get ':course_id/exercises' do
          authenticate!

          course = Course.find(params[:course_id])
          exercises = course.exercises.where("exercise_status <> 1").reorder("created_at desc")
          present :data,exercises,with:Mobile::Entities::Exercise,user: current_user
          present :status,0
        end

        desc '删除课程'
        params do
          requires :token, type: String
        end
        post ':course_id/del' do
          authenticate!
          c = Course.find(params[:course_id])
          # if c.members.count > 1
          #   {status: -1, message: '已经有成员加入,不能删除'}
          # else
            c.delete!
            present :status,0
          # end


        end

        desc "获取班级某成员角色信息"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :user_id, type: Integer
        end
        post 'get_member_info' do
          authenticate!

          c = Course.find("#{params[:id]}")

          my_member = c.member_principals.where("users.id=#{params[:user_id]}").first

          if my_member && my_member.roles[0]
            present :course_id,params[:id]
            present :user_id,params[:user_id]
            present :member_info,my_member, with: Mobile::Entities::ProjectMember
            present :course_group_id,my_member.course_group_id
            present :status, 0
          else
            present :status, -1
            present :message, "该用户已不在班级中"
          end

        end

        desc "修改班级某成员角色信息"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :user_id, type: Integer
          requires :teacher_flag, type: Boolean
          requires :assistant_flag, type: Boolean
          requires :student_flag, type: Boolean
        end
        post 'edit_member_role' do
          authenticate!

          roles_id = []

          if params[:teacher_flag]
            roles_id << 9
          elsif params[:assistant_flag]
            roles_id << 7
          end

          if params[:student_flag]
            roles_id << 10
          end

          c = Course.find("#{params[:id]}")

          my_member = c.member_principals.where("users.id=#{current_user.id}").first

          rolesids = []
          my_member.roles.each do |role|
            rolesids << role.id
          end

          #7教辅 9教师 10学生
          if c.tea_id == params[:user_id] || roles_id.length <= 0
            present :status, -1
            present :message,"修改失败"
          elsif rolesids.include?(3) || rolesids.include?(7) || rolesids.include?(9)
            cs = CoursesService.new
            status = cs.modify_user_course_role params,roles_id
            present :status, status
          else
            present :status, -1
            present :message,"修改失败"
          end
        end

        desc "发布班级通知"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :text, type: String
          requires :title, type: String
        end
        post ':id/publishnotice' do
          authenticate!

          #老师或教辅才能发通知
          c = Course.find("#{params[:id]}")

          my_member = c.member_principals.where("users.id=#{current_user.id}").first

          roles_ids = []
          my_member.roles.each do |role|
            roles_ids << role.id
          end
          if my_member && (roles_ids.include?(7)|| roles_ids.include?(9) || roles_ids.include?(3))

            tmpparams = {}
            tmpparams['title'] = params[:title]
            tmpparams['description'] = params[:text]
            tmpparams['sticky'] = 0

            news = News.new(:course => c, :author => current_user)
            #render :layout => 'base_courses'
            news.safe_attributes = tmpparams

            news.save!

            present :status, 0
          else
            present :status, -1
            present :message,"学生不能发布通知"
          end
        end

        desc "发布班级问题"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :text, type: String
        end
        post ':id/publishissue' do
          authenticate!

          c = Course.find("#{params[:id]}")

          boards = c.boards.includes(:last_message => :author).all
          if c.boards.empty?
            board = c.boards.build
            board.name = "班级问答区"
            board.description = c.name.to_s
            board.project_id = -1
            if board.save
              boards = c.boards.includes(:last_message => :author).all
            end
          end

          board = boards.first

          message = Message.new
          message.author = current_user
          message.board = board

          tmpparams = {}
          tmpparams['subject'] = params[:title]
          tmpparams['content'] = params[:text]

          message.safe_attributes = tmpparams

          message.save!

          present :status, 0

        end

        desc "删除班级成员"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :user_id, type: Integer
        end
        post ':id/deletemember' do
          authenticate!

          status = -1

          if(current_user.id != params[:user_id].to_i)
            #权限
            c = Course.find("#{params[:id]}")
            if c.tea_id != params[:user_id].to_i

              my_member = c.member_principals.where("users.id=#{current_user.id}").first

              roles_ids = []
              my_member.roles.each do |role|
                roles_ids << role.id
              end

              if my_member && (roles_ids.include?(3) || roles_ids.include?(7) || roles_ids.include?(9) )
                #删除该成员
                cs = CoursesService.new
                status = cs.delete_course_member(c,params[:user_id].to_i,current_user)
              else
                status = -2
              end
            else
              status = -3
            end
          else
            status = -4
          end

          out = {status: status}
          message = case status
                      when 0; "删除成功"
                      when -1; "您还未登录"
                      when -2; "对不起您没有权限"
                      when -3; "不能删除班级管理员"
                      when -4; "不能删除自己"
                      when 1; "该用户不在该班级中"
                      else; "未知错误，请稍后再试"
                    end
          out.merge(message: message)
        end

        desc "退出班级"
        params do
          requires :id, type: Integer
          requires :token, type: String
        end
        post ':id/quit' do
          authenticate!

          #管理员不能退
          cs = CoursesService.new
          c = Course.find("#{params[:id]}")

          user = current_user

          if c.tea_id != user.id
            status = cs.exit_course({:object_id => params[:id]}, user)
          else
            status = 3
          end
          out = {status: status}
          message = case status
                      when 0; "退出班级成功"
                      when 1; "您不是该班级成员"
                      when 2; "您还未登录"
                      when 3; "管理员不能退出班级"
                      else; "未知错误，请稍后再试"
                    end
          out.merge(message: message)
        end

        desc '获取分班列表'
        params do
          requires :id, type: Integer
          requires :token, type:String
        end
        get 'course_groups/:id' do
          begin
            authenticate!
            course = Course.find(params[:id])
            groups = []
            groups = course.course_groups if course.course_groups
            present :data,groups
            present :status,0
          rescue
            present :status,-1
          end
        end

        desc "加入分班"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :course_group_id, type: Integer
        end
        post 'user_join_coursegroup' do
          begin
            authenticate!
            member = Member.where(:course_id => params[:id], :user_id => current_user.id).first

            raise "你还不是该班级的学生!" unless member

            member.course_group_id = params[:course_group_id].to_i
            member.save
            present :status,0
          rescue  Exception=>e
            present :message,e.message
            present :status,-1
          end
        end

        desc "修改分班"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :course_group_id, type: Integer
          requires :user_id, type: Integer
        end
        post 'user_edit_coursegroup' do
          begin
            authenticate!
            member = Member.where(:course_id => params[:id], :user_id => params[:user_id]).first

            raise "不是该班级的学生!" unless member

            member.course_group_id = params[:course_group_id].to_i
            member.save
            present :status,0
          rescue  Exception=>e
            present :message,e.message
            present :status,-1
          end
        end

        desc '获取分班列表带上学生'
        params do
          requires :id, type: Integer
          requires :token, type:String
        end
        get 'course_groups_withstudent/:id' do
          begin
            authenticate!
            course = Course.find(params[:id])
            groups = []
            groups = course.course_groups if course.course_groups
            present :data,groups, with: Mobile::Entities::CourseGroup
            present :status,0
          rescue
            present :status,-1
          end
        end

        desc "删除分班"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :course_group_id, type: Integer
        end
        post 'delete_coursegroup' do
          begin
            authenticate!
            c = Course.find("#{params[:id]}")
            my_member = c.member_principals.where("users.id=#{current_user.id}").first

            roles_ids = []
            my_member.roles.each do |role|
              roles_ids << role.id
            end

            if my_member && (roles_ids.include?(3) || roles_ids.include?(7) || roles_ids.include?(9) )
            else
              raise "您没有该权限！"
            end
            CourseGroup.delete(params[:course_group_id])
            present :status,0
          rescue  Exception=>e
            present :message,e.message
            present :status,-1
          end
        end


        desc "编辑分班"
        params do
          requires :id, type: Integer
          requires :token, type: String
        end
        post 'edit_coursegroup' do
          begin
            authenticate!
            c = Course.find("#{params[:id]}")
            my_member = c.member_principals.where("users.id=#{current_user.id}").first

            roles_ids = []
            my_member.roles.each do |role|
              roles_ids << role.id
            end

            if my_member && (roles_ids.include?(3) || roles_ids.include?(7) || roles_ids.include?(9) )
            else
              raise "您没有该权限！"
            end

            #增加分班和修改分班名
            modify_groups = params[:modify_groups]
            modify_groups.each do |g|
              group = CourseGroup.find(g.id)
              group.name = g.id.to_s + Time.now.to_i.to_s #只能先另取个名了不然原有的两个互换的话修改不了
              group.save
            end

            modify_groups.each do |g|
              group = CourseGroup.find(g.id)
              group.name = g.name
              group.save
            end

            #增加分班和修改分班名
            add_groups = params[:add_groups]
            add_groups.each do |name|
              group = CourseGroup.new
              group.name = name
              group.course_id = params[:id]
              group.save
            end
            present :status,0
          rescue  Exception=>e
            present :message,e.message
            present :status,-1
          end
        end

      end
    end
  end
end

