class GraduationTopicsController < ApplicationController
  before_action :require_login, :check_auth, except: [:index]
  before_action :find_course
  before_action :teacher_allowed, only: [:new, :create, :update, :edit, :destroys, :set_public,
                                         :refuse_student_topic, :accept_student_topic, :export]
  before_action :find_graduation_topic, except: [:index, :create, :new, :set_public, :destroys, :export, :add_to_bank]
  before_action :find_course_teachers, only: [:new, :edit]
  before_action :user_course_identity, only: [:index, :show, :show_detail, :show_comment]

  include ExportHelper


  # 毕设选题列表
  def index
    @graduation_topic = @course.graduation_topics
    @current_user = current_user
    # 搜索
    if params[:search]
      @graduation_topic = @graduation_topic.search_by_name(params[:search])
    end

    if params[:status]
      @graduation_topic = @graduation_topic.search_by_status(params[:status])
    end

    # 当前用户是否已经选过题
    @user_selected = @course.student_graduation_topics.where(user_id: current_user.id, status: [0, 1]).count  > 0 #6.12 -hs
    ## 分页参数
    page  = params[:page]  || 1
    limit = params[:limit] || 15
    @graduation_topic_count = @graduation_topic.count
    @graduation_topic = @graduation_topic.order("created_at desc").page(page).per(limit)
  end

  # 课题列表
  def show
    @student_graduation_topics =
        if @user_course_identity > Course::STUDENT && !@graduation_topic.is_public
          StudentGraduationTopic.none
        else
          @graduation_topic.student_graduation_topics.includes(:user, :course_member => [:course_group])
              .order("student_graduation_topics.created_at desc")
        end
    ## 分页参数
    @current_user = current_user
    user_graduation_topics = @course.student_graduation_topics.where(user_id: current_user.id,
                                                                     status: [0, 1])
    @user_selected = user_graduation_topics.size > 0
    page  = params[:page]  || 1
    limit = params[:limit] || 50
    @users_count = @student_graduation_topics.try(:count).to_i
    @student_graduation_topics = @student_graduation_topics.page(page).per(limit)
  end

  # 课题详情
  def show_detail
    @attachments = @graduation_topic.attachments
  end

  # 课题详情回复接口
  def show_comment
    @page = params[:page] || 1
    @limit = params[:limit] || 10
    @parent = params[:parent_id]
    @current_user = current_user
    @messages = @graduation_topic.journals_for_messages
    if @parent
      @messages = @messages.where(m_parent_id: @parent).order("created_on desc")
    else
      @messages = @messages.parent_comment.order("created_on asc")
    end

    @messages_count = @messages.count

    @messages = @messages.page(@page).per(@limit)
  end


  # 新建课题
  def new
    #6.11 新增，-hs
    left_banner_content = @course.course_modules.search_by_module_type("graduation")
    if left_banner_content.present?
      @left_banner_id = left_banner_content.first.course_second_categories.first.id
      @left_banner_name = left_banner_content.first.course_second_categories.first.name
    else
      normal_status(-1,"左侧导航不存在！")
    end
  end

  # 创建课题
  # POST: /graduation_topics
  def create
    @graduation_topic = GraduationTopic.new(graduation_topic_params)
    @graduation_topic.course_id = @course.id
    @graduation_topic.user_id = current_user.id
    @graduation_topic.save!
    Attachment.associate_container(params[:attachment_ids], @graduation_topic.id, @graduation_topic.class) if params[:attachment_ids]

  end

  # 更新课程
  def update
    @graduation_topic.update_attributes(graduation_topic_params)
    Attachment.associate_container(params[:attachment_ids], @graduation_topic.id, @graduation_topic.class) if params[:attachment_ids]
  end

  def edit
    @attachments = @graduation_topic.attachments
    left_banner_content = @course.course_modules.search_by_module_type("graduation")
    if left_banner_content.present?
      @left_banner_id = left_banner_content.first.course_second_categories.first.id
      @left_banner_name = left_banner_content.first.course_second_categories.first.name
    end
  end

  def destroys
    tip_exception(-1, "graduation_topic_ids不能为空") if params[:graduation_topic_ids].nil?
    @graduation_topics = GraduationTopic.where(:id => params[:graduation_topic_ids])
    @graduation_topics.destroy_all
    normal_status("删除成功")
  end

  def set_public
    tip_exception(-1, "私有课程不能设置毕设选题为公开") if @course.is_public == 0
    tip_exception(-1, "graduation_topic_ids不能为空") if params[:graduation_topic_ids].nil?
    @graduation_topics = GraduationTopic.where(id: params[:graduation_topic_ids])
    @graduation_topics.update_all(is_public: true)
    normal_status("设置成功")
  end

  # 拒绝课题
  def refuse_student_topic
    begin
      student_graduation_topic = @graduation_topic.student_graduation_topics
                                     .find_by(id: params[:student_graduation_topic])
      if student_graduation_topic.present?
        # 更新学生选题和老师选题的状态
        student_graduation_topic.update_attributes(:status => 2)
        update_graduation_topic_status

        # 拒绝后将该学生移动到未分班中
        student_member = @course.course_members.where(:user_id => student_graduation_topic.user_id).first
        student_member.update_attributes(:course_group_id => 0) if student_member.present?

        student_graduation_topic.tidings.update_all(:status => 1)
        Tiding.create(:user_id => student_graduation_topic.user_id, :trigger_user_id => current_user.id,
                      :container_id => student_graduation_topic.id, :container_type => "DealStudentTopicSelect",
                      :parent_container_id => @graduation_topic.id, :parent_container_type => "GraduationTopic",
                      :belong_container_id => @graduation_topic.course_id, :belong_container_type => "Course",
                      :viewed => 0, :tiding_type => "GraduationTopic", :status => 2)
      end
      normal_status("拒绝成功")
    rescue Exception => e
      uid_logger(e.message)
      tip_exception(-1, "操作失败")
    end
  end

  # 接受课题
  def accept_student_topic
    student_graduation_topic = @graduation_topic.student_graduation_topics
                                   .where(:id => params[:student_graduation_topic_id]).first
    if student_graduation_topic.present?
      # 更新学生选题和老师选题的状态
      student_graduation_topic.update_attributes(:status => 1)
      update_graduation_topic_status

      # 将学生加入到老师的第一个具有管理权限的分班（没有则创建一个“XXX老师组”分班并弹框提醒）
      teacher_group = @course.teacher_course_groups.where(:user_id => @graduation_topic.tea_id, :id => params[:group_id]).first
      unless teacher_group.present?
        member = @course.course_members.where(:user_id => @graduation_topic.tea_id).first
        tip_exception("分班名称不能为空") if params[:course_group_name].blank?
        course_group = CourseGroup.create(:name => params[:course_group_name], :course_id => @course.id)
        teacher_group = TeacherCourseGroup.create(:course_id => @course.id, :course_member_id => member.try(:id),
                                                  :user_id => @graduation_topic.tea_id,
                                                  :course_group_id => course_group.try(:id))
      end
      student_member = @course.course_members.where(:user_id => student_graduation_topic.user_id).first
      student_member.update_attributes(:course_group_id => teacher_group.course_group_id) if student_member.present?

      student_graduation_topic.tidings.update_all(:status => 1)
      Tiding.create(:user_id => student_graduation_topic.user_id, :trigger_user_id => current_user.id,
                    :container_id => student_graduation_topic.id, :container_type => "DealStudentTopicSelect",
                    :parent_container_id => @graduation_topic.id, :parent_container_type => "GraduationTopic",
                    :belong_container_id => @graduation_topic.course_id, :belong_container_type => "Course",
                    :viewed => 0, :tiding_type => "GraduationTopic", :status => 1)
    end
    normal_status("同意成功")
  end

  # 学生选题
  def student_select_topic
    user_unaccept_topics = @course.student_graduation_topics.where(user_id: current_user.id, status: [0, 1])
    if user_unaccept_topics.size == 0
      member = @course.course_members.find_by_user_id(current_user.id)
      StudentGraduationTopic.create(course_id: @course.id, user_id: current_user.id, course_member_id: member.try(:id),
                                    graduation_topic_id: @graduation_topic.id)
      @graduation_topic.update_attribute(:status, 1)
      normal_status("选题成功")
    else
      normal_status("已经选过题，无法重复选题")
    end
  end

  # 学生取消选题
  def student_cancel_topic
    user_unaccept_topics = @course.student_graduation_topics.where(user_id: current_user.id, status: [0, 1])
    user_unaccept_topics.destroy_all
    update_graduation_topic_status
    normal_status(0,"取消成功")
  end

  # 加入题库
  def add_to_bank
    ActiveRecord::Base.transaction do
      begin
        topics = @course.graduation_topics.where(id: params[:topic_ids])

        topics.each do |topic|
          topic_bank = current_user.gtopic_banks.find_by(graduation_topic_id: topic.id)

          # 已加入的更新，未加入的新建
          if topic_bank.present?
            topic_bank.update_attributes(name: topic.name, description: topic.description,
                                         topic_source: topic.topic_source,
                                         topic_property_first: topic.topic_property_first,
                                         topic_property_second: topic.topic_property_second,
                                         source_unit: topic.source_unit,
                                         topic_repeat: topic.topic_repeat,
                                         province: topic.province,
                                         city: topic.city,
                                         course_list_id:  @course.course_list_id)
            topic_bank.attachments.destroy_all
          else
            topic_bank = GtopicBank.new(name: topic.name, description: topic.description,
                                        topic_source: topic.topic_source,
                                        topic_property_first: topic.topic_property_first,
                                        topic_property_second: topic.topic_property_second,
                                        source_unit: topic.source_unit,
                                        topic_repeat: topic.topic_repeat,
                                        province: topic.province,
                                        city: topic.city,
                                        course_list_id:  @course.course_list_id,
                                        user_id: current_user.id,
                                        graduation_topic_id: topic.id)

            topic_bank.save!
          end
          topic.attachments.each do |attachment|
            att = attachment.copy
            att.author_id = topic_bank.user_id
            att.copy_from = attachment.id
            topic_bank.attachments << att
          end
        end

        normal_status(0,"加入题库成功")
      rescue Exception => e
        uid_logger(e.message)
        tip_exception(e.message)
        raise ActiveRecord::Rollback
      end
    end
  end

  # 导出功能
  def export
    begin
      course = @course
      students = course.students.joins(user: :user_extension).order("user_extensions.student_id")
      graduation_topic_to_xlsx(students,course)
      topic_export_name_ = "#{current_user.real_name}_#{course.name}_毕设选题_#{Time.now.strftime('%Y%m%d_%H%M%S')}"
      if params[:export].present? && params[:export]
        normal_status(0,"正在下载中")
      else
        set_export_cookies
        render xlsx: "#{topic_export_name_.strip}",template: "graduation_topics/export.xlsx.axlsx",locals: {table_columns:@topic_head_cells,topic_users:@topic_body_cells}
      end
    rescue Exception => e
      uid_logger(e.message)
      missing_template
    end
  end

  private
  def find_graduation_topic
    begin
    @graduation_topic = GraduationTopic.find params[:id]
    rescue Exception => e
      uid_logger(e.message)
      missing_template
    end
  end

  def find_course_teachers
    @teachers = @course.teachers.joins(:user).order("users.id = #{current_user.id} desc,
                                                     CONVERT(users.lastname USING gbk) COLLATE gbk_chinese_ci asc")
  end

  # 创建允许参数
  def graduation_topic_params
    params.require(:graduation_topic).permit(:tea_id, :name, :topic_type, :topic_source, :topic_property_first,
                                             :description, :topic_property_second, :status, :source_unit, :topic_repeat,
                                             :province, :city, :is_public)
  end

  # 更新选题的状态
  def update_graduation_topic_status
    status = @graduation_topic.student_graduation_topic_status
    @graduation_topic.update_attribute(:status, status)
  end
end
