# encoding: utf-8
class ManagementsController < ApplicationController
  before_filter :require_business
  before_filter :require_admin, :only => [:shixun_setting_list, :mirror_repository, :mirror_picture_shixuns, :editmd_template,
                                          :editmd_template, :subject_level_system, :subject_setting_list,
                                          :shixun_authorization, :ec_template, :codemirror_template,
                                          :course_guide_template, :shixun_quality_score, :tech_system, :update_notice, :setting_banner,
                                          :training_2018, :create_standard]
  layout 'base_management'
  include ManagementsHelper
  include SortHelper
  include UsersHelper
  include ApplicationHelper
  include AvatarHelper
  include ShixunsHelper
  helper :files
  if RUBY_PLATFORM =~ /linux/
    require 'simple_xlsx_reader'
    require 'roo-xls'
  end

  CODES = %W(2 3 4 5 6 7 8 9 A B C D E F G H J K L N M O P Q R S T U V W X Y Z)

  # 更新实训课程的等级
  def update_level_for_subject
    subject = Subject.find params[:subject_id]
    subject.update_attribute(:subject_level_system_id, params[:level_id])
    render :json => {status: 1}
  end

  def user_agents
    @user_agents = UserAgent.where("user_agents.key is not null")
    @agents_count = @user_agents.count
    limit = 20
    @agents_pages = Paginator.new @agents_count, limit, params['page'] || 1
    @offset ||= @agents_pages.offset
    @user_agents = paginateHelper @user_agents, limit
  end

  # 实训课程等级体系
  def subject_level_system
    @levels = SubjectLevelSystem.all
    respond_to do |format|
      format.js
      format.html
      format.xls{
        time = Time.now.strftime("%Y%m%d")
        filename = "实训课程体系#{time}.xls"
        send_data(export_subject_level_system(), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  # 创建课程等级体系
  def create_subject_level
    raise("名称不能为空") if params[:name].blank?
    repeat_name = SubjectLevelSystem.where(name: params[:name]).count
    raise("名称不能重复") if repeat_name > 0
    level = SubjectLevelSystem.pluck(:level).max.to_i + 1
    SubjectLevelSystem.create(name: params[:name], level: level)
    redirect_to subject_level_system_managements_path(:format => "js")
  end

  # 重命名课程等级
  def rename_subject_level
    raise("名称不能为空!") if params[:name].blank?
    repeat_name = SubjectLevelSystem.where("name = ? and id != ?", params[:name], params[:id]).count
    raise("名称不能重复") if repeat_name > 0
    level = SubjectLevelSystem.find params[:id]
    level.update_attribute(:name, params[:name])
    redirect_to subject_level_system_managements_path(:format => "js")
  end

  # 删除课程等级
  def delete_subject_level
    level = SubjectLevelSystem.find params[:id]
    Subject.where(:subject_level_system_id => level).update_all(:subject_level_system_id => nil)
    levels = SubjectLevelSystem.where("level > ?", level.level)
    levels.each do |l|
      l.update_attribute(:level, l.level-1)
    end
    level.delete
    redirect_to subject_level_system_managements_path(:format => "js")
  end

  # 工程认证视频导入模板
  def ec_template
    @template = EcTemplate.where(nil)
  end

  def add_template
    logger.info("#############################{params}")
    EcTemplate.create(:name => params[:name].strip)
    @template = EcTemplate.where(nil)
  end

  def training_2018
    @search = params[:search]
    @training_type = params[:training_type]
    @pay_type = params[:pay_type]
    @page = params[:page] || 1
    @status = params[:status]
    if User.current.admin?
      @trainings = Training.includes(:training_payinfo)
      if params[:search] && params[:search].strip != ""
        @trainings = @trainings.where("trainings.name like '%#{params[:search]}%'")
      end
      if params[:training_type] && params[:training_type].to_i != -1
        @trainings = @trainings.where("training_type = #{params[:training_type]}")
      end
      if params[:pay_type] && params[:pay_type].to_i != -1
        @trainings = @trainings.where("training_payinfos.pay_type = #{params[:pay_type]}")
      end
      if params[:status] && params[:status].to_i != -1
        @trainings = @trainings.where("training_payinfos.status = #{params[:status]}")
      end
      @page = params[:page] || 1
      @all_trainings = @trainings.reorder("trainings.created_at desc")
      @trainings = paginateHelper @trainings.reorder("trainings.created_at desc"), 50
    else
      render_403
    end
    respond_to do |format|
      format.js
      format.html
      format.xls{
        time = Time.now.strftime("%Y%m%d")
        filename = "#{time}培训会报名列表.xls"
        send_data(training_2018_xls(@all_trainings), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def update_pay_status
    if User.current.admin? || User.current.id == 1
      @training = Training.where(:id => params[:training]).first
      if @training
        @training.training_payinfo.update_attributes(:status => TrainingPayinfo::Status_Payed)
        if @training.phone.present?
          Trustie::Sms.send(mobile: @training.phone.to_s, send_type: "training_pay", user_name: @training.name)
        end
      end
    else
      render_403
    end
  end

  def mul_test
    @menu_type = 3
    @sub_type = 9
    @m_tests = MulTest.where(nil)

    @m_tests_count = @m_tests.count
    @m_tests_pages = Paginator.new @m_tests_count, 20, params['page'] || 1
    @offset ||= @m_tests_pages.offset
    @m_tests = paginateHelper @m_tests, 20
    respond_to do |format|
      format.js
      format.html
    end
  end

  def mul_statics
    @m_tests = MulTest.all.group_by{|o|[o.num, o.shixun_id]}
    # @m_tests_count = @m_tests.count
    # @m_tests_pages = Paginator.new @m_tests_count, 20, params['page'] || 1
    # @offset ||= @m_tests_pages.offset
    # @m_tests = paginateHelper @m_tests, 20
  end

  def update_shixun_usescope
    shixun = Shixun.where(:id => params[:shixun_id]).first
    shixun.update_column(:use_scope, params[:use_scope].to_i)
    render :json => {status: "success"}
  end

  #用户修改
  def myshixuns
    @menu_type = 3
    @sub_type = 8
    @g = Gitlab.client
    if params[:search]
      if params[:search].to_i.to_s == params[:search].to_s
        myshixun_id = Game.where(:myshixun_id => params[:search].to_i).pluck(:myshixun_id)
      else
        myshixun_id = Game.where(:identifier => params[:search]).pluck(:myshixun_id)
      end
      @myshixuns = Myshixun.where(:id => myshixun_id).includes(:shixun)
    else
      @myshixuns = Myshixun.where("0=0").includes(:shixun)
    end
    @myshixuns_count = @myshixuns.count
    limit = 20
    @myshixuns_pages = Paginator.new @myshixuns_count, limit, params['page'] || 1
    @offset ||= @myshixuns_pages.offset
    @myshixuns = paginateHelper @myshixuns, limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  def myshixun_info
    user_id = User.where(:login => params[:login].strip).pluck(:id).first
    shixun_id = Shixun.where(:identifier => params[:shixun_id].strip).pluck(:id).first
    myshixun = Myshixun.where(:user_id => user_id, :shixun_id => shixun_id).first
    game = myshixun.current_task
    @game_url = Setting.protocol + "://" + Setting.host_name + "/tasks/#{game.identifier}"
    @git_url = Redmine::Configuration['gitlab_address']+"/"+myshixun.git_url
  end

  def anomaly_detection

  end

  def account
    @user =  User.find(params[:user_id])
    begin
      if request.post?
        @user.nickname = params[:nickname]
        @user.lastname = params[:lastname]
        @user.business = params[:business].to_i
        @user.firstname = ""
        @user.mail = params[:mail].strip == "" ? nil : params[:mail]
        @user.phone = params[:phone].strip == "" ? nil : params[:phone]
        #@user.password = params[:new_password]
        # if params[:new_password].strip != "" && params[:new_password_confirmation].strip != ""
        #   @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
        # end
        @se = @user.extensions
        @se.school_id = params[:occupation]
        @se.department_id = params[:department_id]
        @se.gender = params[:sex]
        @se.location = params[:province] if params[:province]
        @se.location_city = params[:city] if params[:city]
        @se.identity = params[:identity].to_i if params[:identity]
        if @se.identity == 0
          @se.technical_title = params[:te_technical_title] if params[:te_technical_title]
          @se.student_id = nil
        elsif @se.identity == 1
          @se.student_id = params[:no] if params[:no]
          @se.technical_title = nil
        elsif @se.identity == 2
          @se.technical_title = params[:pro_technical_title] if params[:pro_technical_title]
          @se.student_id = nil
        end
        @se.brief_introduction = params[:brief_introduction]
        @user.save
        @se.save
        us = UsersService.new
        @user = us.change_password params.merge(:current_user_id => @user.id)
        # if @user.save && @se.save
        #   reward_grade(@user, @user.id, 'Account', 500)
        #   # 头像保存
        #   FileUtils.mv diskfile1, diskfile, force: true if File.exist? diskfile1
        #   @user.pref.save
        #   @user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : [])
        #   set_language_if_valid @user.language
        #   flash[:notice] = l(:notice_account_updated)
        #   return
        # else
        #   # @user.login = lg
        # end

      end
        # 不管前面是否有异常,如果文件已存在就删除
    ensure
    end
    # @setting_type = 1

    redirect_to update_user_managements_path(:user => @user)
  end

  # 获取镜像
  def pull_mirror
    #params[:jsonMirrorDetails] = '{"images":[{"imageID":"2367ee7a7d4c","name":"octave-novnc:v1.0"}, {"imageID":"1b9cfba2c4dd","name":"jfinal-mysql55:v1.0"}]}'
    ActiveRecord::Base.transaction do
      begin
        shixun_tomcat = Redmine::Configuration['shixun_tomcat']
        params = {}
        uri = "#{shixun_tomcat}/bridge/docker/images"
        res = uri_exec uri, params
        if (res && res['code'] != 0)
          raise("Pull mirror the repository exception")
        end
        mirrors = res["images"]
        images = [] # 中间层镜像名称的数组
        if mirrors.present?
          mirrors.each do |mirror|
            mirror = JSON.parse(mirror)
            match_rep_mirror_name = MirrorRepository.where(:name => mirror['imageName']).first
            match_rep_mirror_id = MirrorRepository.where(:mirrorID => mirror['imageID']).first
            images << mirror['imageName']
            if match_rep_mirror_name.blank? && match_rep_mirror_id.blank?
              # 镜像不存在、创建镜像
              new_mirror = MirrorRepository.create!(:mirrorID => mirror['imageID'], :name => mirror['imageName'])
              MirrorOperationRecord.create!(:mirror_repository_id => new_mirror.id, :mirror_id => mirror['imageID'], :mirror_name => mirror['imageName'], :status => 0, :user_id => -1)
            elsif match_rep_mirror_name.present? && match_rep_mirror_id.blank?
              # 镜像ID被修改
              match_rep_mirror_name.update_attributes(:status => 2)
              MirrorOperationRecord.create!(:mirror_repository_id => match_rep_mirror_name.id, :mirror_id => mirror['imageID'], :mirror_name => mirror['imageName'], :status => 1, :user_id => -1)
            elsif match_rep_mirror_name.blank? && match_rep_mirror_id.present?
              # 镜像名称被修改
              match_rep_mirror_id.update_attribute(:status, 3)
              MirrorOperationRecord.create!(:mirror_repository_id => match_rep_mirror_id.id, :mirror_id => mirror['imageID'], :mirror_name => mirror['imageName'], :status => 2, :user_id => -1)
            end
          end
        end
        # 判断中间层镜像是否被删除
        edu_mirrors = MirrorRepository.all
        edu_mirrors.each do |mirror|
          if(images.index(mirror.try(:name)).nil? && mirror.try(:name).present?)
            mirror.update_attribute(:status, 4)
            MirrorOperationRecord.create!(:mirror_repository_id => mirror.id, :mirror_id => mirror.try(:mirrorID), :mirror_name => mirror.name, :status => 3, :user_id => -1)
          end
        end
        # end
        redirect_to mirror_repository_managements_path
      rescue Exception => e
        logger.error("pull_mirror error: #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  # 验证镜像名是否重复
  # 判断依据:主类别和小类别可以同名;主类别和小类别各自之间
  def check_mirror_name
    random = CODES.sample(8).join
    mirror_count = MirrorRepository.where("type_name = ? and id != ? and main_type =?", params[:type_name], params[:mirror_id], params[:main_type].to_i).count
    check = (mirror_count > 0 ? true : false)
    render :json => {check: check, random: random}
  end

  # 中间层与edu镜像不一致时,选择镜像一个可用的版本
  def choose_mirror
    @mirror = MirrorRepository.find(params[:mirror_id])
    @new_mirror = MirrorOperationRecord.where(:mirror_repository_id => @mirror.id, :status => 1, :user_id => -1).first
    respond_to do |format|
      format.js
    end
  end

  # flag: 0 更新新ID,1 回退
  # old_id: 平台保存的ID
  # change_id: 用户修改的新ID
  # 选择镜像后,向中间层updateImage  flag: 0 更新新ID,1 回退镜像
  def choose_update_mirror
    old_id = params[:id]
    change_id = params[:mirror_id]
    flag = (old_id == change_id ? 1 : 0)
    ActiveRecord::Base.transaction do
      begin
        mirror = MirrorRepository.where(:mirrorID => old_id).first
        if mirror.blank?
          raise("choose_update_mirror exception")
        end
        #shixun_tomcat = Redmine::Configuration['shixun_tomcat']
        #params = {imageName: mirror.name, imageID: old_id, flag: flag}
        #uri = "#{shixun_tomcat}/bridge/docker/updateImage"
        #res = uri_exec uri, params
       # if (res && res['code'] != 0)
          #raise("choose_update_mirror exception")
        #end
        if flag == 0
          mirror.update_attributes(:mirrorID => change_id, :status => 1)
          # 用户操作的的行为需要记录 user_id, 中间层操作的行为user_id = -1
          MirrorOperationRecord.create!(:mirror_repository_id => mirror.id, :mirror_id => change_id, :mirror_name => mirror.name, :status => 1, :user_id => User.current.id, :old_tag => old_id, :new_tag => change_id)
        else
          mirror.update_attribute(:status, 1)
        end
        respond_to do |format|
          format.js{ redirect_to mirror_repository_managements_path(:reaction => "choose_update_mirror")}
        end
        #format.js{ redirect_to mirror_repository_managements_path(:reaction => "choose_update_mirror")}
      rescue Exception => e
        logger.error("choose_update_mirror error: #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  # 搜索镜像
  def mirror_search
    @scope = []
    if params[:q] && params[:q].lstrip.rstrip != ""
      @scope = MirrorRepository.where("name like ?", "%#{params[:q]}%").map(&:name)
    end
    respond_to do |format|
      format.js
    end
  end

  # 镜像管理
  # REDO: images Get请求不能用Post
  def mirror_repository
    @menu_type = 3
    @sub_type = 5
    @reaction =  params[:reaction] # 如果是局部刷新调用,不需要拉取镜像
    ActiveRecord::Base.transaction do
      begin
        # 重新定向或翻页不需要拉取镜像
        if @reaction.nil? && @_params['page'].nil?
          shixun_tomcat = Redmine::Configuration['shixun_tomcat']
          uri = "#{shixun_tomcat}/bridge/docker/images"
          res = get_url_exec uri
          if (res && res['code'] != 0)
            raise("Pull mirror the repository exception")
          end
          mirrors = res["images"] # 主节点的所有镜像
          sync_mirrors = res['imagesNotSync'] # 子节点镜像异常(主节点有,而子节点却没同步/异常)
          images = [] # 中间层镜像名称的数组
          if sync_mirrors.present?
            sync_mirrors.each do |mirror|
              mirror = JSON.parse(mirror)
              match_rep_mirror_name = MirrorRepository.where(:name => mirror['imageName']).first
             # match_rep_mirror_id = MirrorRepository.where(:mirrorID => mirror['imageID']).first
              if match_rep_mirror_name.present? && match_rep_mirror_name.status == 1
                match_rep_mirror_name.update_attribute(:status, 5)
                MirrorOperationRecord.create!(:mirror_repository_id => match_rep_mirror_name.id, :mirror_id => mirror['imageID'], :mirror_name => mirror['imageName'], :status => 4, :user_id => -1)
              end
            end
          end
          if mirrors.present?
            mirrors.each do |mirror|
              mirror = JSON.parse(mirror)
              match_rep_mirror_name = MirrorRepository.where(:name => mirror['imageName']).first
              match_rep_mirror_id = MirrorRepository.where(:mirrorID => mirror['imageID']).first
              images << mirror['imageName']
              if match_rep_mirror_name.blank?
                # 镜像不存在、创建镜像
                new_mirror = MirrorRepository.create!(:mirrorID => mirror['imageID'], :name => mirror['imageName'])
                MirrorOperationRecord.create!(:mirror_repository_id => new_mirror.id, :mirror_id => mirror['imageID'], :mirror_name => mirror['imageName'], :status => 0, :user_id => -1)
              elsif (match_rep_mirror_name.present? && (mirror['imageID'] != match_rep_mirror_name.mirrorID))
                # 镜像ID被修改
                match_rep_mirror_name.update_attributes(:status => 2)
                MirrorOperationRecord.create!(:mirror_repository_id => match_rep_mirror_name.id, :mirror_id => mirror['imageID'], :mirror_name => mirror['imageName'], :status => 1, :user_id => -1)
              elsif match_rep_mirror_name.blank? && match_rep_mirror_id.present?
                # 镜像名称被修改
                match_rep_mirror_id.update_attribute(:status, 3)
                MirrorOperationRecord.create!(:mirror_repository_id => match_rep_mirror_id.id, :mirror_id => mirror['imageID'], :mirror_name => mirror['imageName'], :status => 2, :user_id => -1)
              end
            end
          end
          # 判断中间层镜像是否被删除
          edu_mirrors = MirrorRepository.all
          edu_mirrors.each do |mirror|
            if(images.index(mirror.try(:name)).nil? && mirror.try(:name).present?)
              mirror.update_attribute(:status, 4)
              MirrorOperationRecord.create!(:mirror_repository_id => mirror.id, :mirror_id => mirror.try(:mirrorID), :mirror_name => mirror.name, :status => 3, :user_id => -1)
            end
          end
          # end
        end
        @error_mirrors = MirrorRepository.where(:status => 5)
        @menu_type = 3
        @sub_type = 4
        @mirrors = MirrorRepository.reorder("status desc, main_type desc, type_name asc")
        @mirrors_count = @mirrors.count
        @limit = 20
        @page = (@_params['page'] || 1).to_i
        @mirrors_pages = Paginator.new @mirrors_count, @limit, @page
        @offset ||= @mirrors_pages.offset
        @mirrors = paginateHelper @mirrors, @limit
        respond_to do |format|
          format.js
          format.html
        end
      rescue Exception => e
        logger.error("pull_mirror error: #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  # 迁移数据与脚本
  # eg: shixun_id 字符类型。eg:shixun_id=61,71
  # res['script'] tpm的模板
  # res['template'] 标准模板
  def migrate_data_and_script
    ActiveRecord::Base.transaction do
      begin
        if params[:shixun_id]
          shixuns = Shixun.where(:id => params[:shixun_id].split(","))
        else
          shixuns = Shixun.where(nil)
        end
        shixuns.find_each do |shixun|
          main_miiror_name, child_miiror_name, secend_miiror_name = "", "", ""
          case shixun.language
            when 'C', 'C++'
              main_miiror_name = 'C/C++'
            when 'MySQL/Java'
              main_miiror_name = 'Java'
              child_miiror_name = 'Mysql'
            when 'MySQL/Python3.6'
              main_miiror_name = 'Python3.6'
              child_miiror_name = 'Mysql'
            when 'PHP/Web'
              main_miiror_name = 'PHP'
              child_miiror_name = 'Mysql'
              secend_miiror_name = 'Web'
            when 'Golang'
              main_miiror_name ='Go'
            when 'Html'
              main_miiror_name = 'Python3.6'
              child_miiror_name = 'Html'
            else
              main_miiror_name = shixun.language
          end
          main_miiror = MirrorRepository.where(:type_name => main_miiror_name).first
          child_miiror = MirrorRepository.where(:type_name => child_miiror_name).first if child_miiror_name.present?
          secend_miiror = MirrorRepository.where(:type_name => secend_miiror_name).first if child_miiror_name.present?
          # 删除实训的关联,重新迁移
          shixun.shixun_mirror_repositories.delete_all if shixun.mirror_repositories.present?
          if main_miiror.present?
            ShixunMirrorRepository.create!(:shixun_id => shixun.id, :mirror_repository_id => main_miiror.id)
          else
            MirrorMigrateError.create(:shixun_id => shixun.id, :game_info => "MainMirror")
            logger.error("main_miiror is miss,shixun_id:#{shixun.id}")
          end
          ShixunMirrorRepository.create!(:shixun_id => shixun.id, :mirror_repository_id => child_miiror.id) if child_miiror.present?
          ShixunMirrorRepository.create!(:shixun_id => shixun.id, :mirror_repository_id => secend_miiror.id) if secend_miiror.present?
          params = {gameInfo: shixun.gameInfo}
          # 根据旧版代码生成新的脚本
          uri = "http://106.75.96.108:8890/bridge/dataTransfer/transferTPMScript"
          res = uri_exec uri, params
          if (res && res['code'] != 0)
            logger.error("migrate_data_and_script 8890 exception;tpmID:#{shixun.id}")
            MirrorMigrateError.create!(:shixun_id => shixun.id, :game_info => shixun.gameInfo)
          end
          template_script = tran_base64_decode64(res['template']) # 标准模板,一类语言一种
          logger.error("##################################game_info: #{shixun.gameInfo}") if template_script.blank?
          shixun.update_column(:evaluate_script, template_script)
          main_miiror.update_column(:script_template, template_script) if main_miiror.present?
        end
        # 监测同步失败的实训
        @ids = Shixun.all.map(&:id) - ShixunMirrorRepository.all.map(&:shixun_id)
        respond_to do |format|
          format.js
        end
      rescue Exception => e
        render :json => {:data => "#{e}"}
        logger.error("migrate_data_and_script error: #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  def modify_script
    @mirror = MirrorRepository.find(params[:mirror_id])
    if params[:script_template].present?
      @mirror.update_attribute(:script_template, params[:script_template])
      redirect_to mirror_repository_managements_path
      return
    end
    respond_to do |format|
      format.html{render :layout => "base_edu"}
    end
  end

  def mirror_replace
    @mirror_id = params[:id]
    @mirror_name = params[:name]
  end

  # 修改此方法慎重:此方法只针对同一镜像出现两条记录,最终需要合并成一条
  # 合并原则:把新的记录合并到老的记录中
  # original_mirror:表示被更新对象即历史老记录
  # current_mirror:表示新增镜像,一般需要被替换掉,替换成功后删除,删除完成后,
  # 后台人员需要删除对应的镜像记录
  def mirror_replace_update
    begin
      original_mirror = MirrorRepository.find(params[:original_mirror_id])
      current_mirror = MirrorRepository.where(:name => params[:mirror_name]).first
      original_mirror.update_attributes!(:name => params[:mirror_name], :mirrorID => current_mirror.mirrorID)
      current_mirror.delete!
    rescue Exception => e
      logger.error(e)
    end
  end

  # 职业路径列表
  def career_list
    @menu_type = 13
    @careers =
        if params[:search]
          Career.includes(career_stages: [career_stage_subjects: :subject]).where("careers.name like '%#{params[:search]}%'").order("created_at desc")
        else
          Career.includes(career_stages: [career_stage_subjects: :subject]).order("created_at desc")
        end
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 发布职业路径
  def published_career
    career = Career.find(params[:id])
    career.update_attribute(:status, true)
    @careers = Career.includes(career_stages: [career_stage_subjects: :subject]).order("created_at desc")
  end

  # 删除职业路径
  def delete_career
    career = Career.find params[:id]
    career.destroy
    @careers = Career.includes(career_stages: [career_stage_subjects: :subject]).order("created_at desc")
  end

  # 工程认证专业信息目录
  def major_information
    @disciplines = EcDiscipline.includes(ec_discipline_firsts: [:ec_majors]).order("ec_disciplines.code asc")
  end

  # 认证单位列表
  def auth_school
    @schools = School.where(:ec_auth => 1).order("updated_at desc")
  end

  # 工程认证单位列表搜索学校
  def search_school
    @schools = School.where("ec_auth != 1 and name like '%#{params[:name]}%'").limit(10)

  end

  # 添加认证学校
  def add_school
    School.where(:id => params[:school_ids]).update_all(:ec_auth => 1)
    render :json => {status: 1}
  end

  # 搜索用户
  def search_manager
    user_ids = EcSchoolUser.where(:school_id => params[:school_id]).pluck(:user_id)
    user_ids = user_ids.present? ? user_ids.join(",") : -1
    @users = User.where("concat(lastname, firstname) like '%#{params[:name]}%' and id not in(#{user_ids})").limit(10)
  end

  # 添加认证学校管理员
  def add_manager
    user_ids = params[:user_ids]
    school_id = params[:school_id]
    user_ids.each do |id|
      EcSchoolUser.create(:user_id => id, :school_id => school_id)
    end
    render :json => {status: 1}
  end

  # 删除学校管理员
  def remove_manager
    manager = EcSchoolUser.where(:school_id => params[:school_id], :user_id => params[:user_id]).first
    manager.destroy
  end

  # 删除认证学校
  def remove_auth_school
    school = School.find params[:school_id]
    school.update_column(:ec_auth, 0)
    school.ec_school_users.delete_all

  end

  # 工程认证: 毕业要求通用标准
  def graduation_standard
    @standards = EcGraduationStandard.all
  end

  # 创建通用标准
  def create_standard
    id = params[:id].to_i
    content = params[:content]
    if id == -1
      EcGraduationStandard.create(:content => content)
    else
      standard = EcGraduationStandard.find params[:id]
      standard.update_attribute(:content, content)
    end
    @standards = EcGraduationStandard.all
  end


  def add_mirror_type
    data = {result: 0}
    if params[:name]
      if MirrorType.where(:name => params[:name]).count == 0
        new_type = MirrorType.new(:user_id => User.current.id, :name => params[:name])
        if new_type.save
          data[:result] = 1
        end
      else
        data[:result] = 2
      end
    end
    render :json => data
  end

  def modify_mirror
    @mirror = MirrorRepository.find params[:mirror_id]
    @mirror_types = MirrorType.where(nil)
  end

  def search_mirror_type
    data = {mirror_types: []}
    search = params[:search]
    MirrorType.where("name like '%#{search}%'").each do |mirror_type|
      option = []
      option << mirror_type.name.to_s
      option << mirror_type.id
      data[:mirror_types] << option
    end
    render :json => data
  end

  def create_mirror
    MirrorRepository.create(:type_name => params[:type_name], :main_type => params[:mirror_type], :description => params[:description], :status => params[:status].to_i)
    respond_to do |format|
      format.js{redirect_to mirror_repository_managements_path(:reaction => "create_mirror")}
    end
  end

  # 更新实训,从未发布到发布需要syncImage同步镜像
  def update_mirror
    ActiveRecord::Base.transaction do
      begin
        @mirror = MirrorRepository.find(@_params[:mirror_id])
        if @_params[:status].to_i == 1 && @mirror.status != 1
          shixun_tomcat = Redmine::Configuration['shixun_tomcat']
          params = {imageName: @mirror.name}
          # 主从节点同步镜像
          #uri = "#{shixun_tomcat}/bridge/docker/syncImage"
          #res = uri_exec uri, params
          #if (res && res['code'] != 0)
          #  raise("Synchronize Mirror exception")
          #end
        end
        if @_params[:type_name] != @mirror.type_name
          MirrorOperationRecord.create!(:mirror_repository_id => @mirror.id, :status => 5,
                                        :user_id => User.current.id, :old_tag => @mirror.type_name,
                                        :new_tag => @_params[:type_name])
        elsif @_params[:status].to_i != @mirror.status
          MirrorOperationRecord.create!(:mirror_repository_id => @mirror.id, :status => 6,
                                        :user_id => User.current.id, :old_tag => @mirror.status,
                                        :new_tag => @_params[:status])
        end
        @mirror.update_attributes(:description => @_params[:description], :status => @_params[:status],
                                  :main_type => @_params[:mirror_type], :type_name => @_params[:type_name],
                                  :resource_limit => @_params[:mirror_resource_limit], :cpu_limit => @_params[:mirror_cpu_limit],
                                  :memory_limit => @_params[:mirror_memory_limit], :time_limit => @_params[:mirror_time_limit])
        @index = MirrorRepository.order("created_at desc").map(&:id).index(@mirror.id)
        respond_to do |format|
          format.js
        end
      rescue Exception => e
        logger.error("update_mirror error: #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  def delete_mirror
    mirror = MirrorRepository.find params[:mirror_id]
    mirror.destroy
    respond_to do |format|
      format.js{redirect_to mirror_repository_managements_path(:reaction => "delete_mirror")}
    end
  end

  # 用户修改界面
  def update_user
    @menu_type = 7
    @sub_type = 1
    # @next_type = 1
    if params[:flag]
      applied_message = AppliedMessage.where(:id => params[:applied_message_id]).first
      applied_message.update_attribute(:viewed, true)
    end
    @user = User.find(params[:user])
    # 创建实训
    @create_num = (@user == User.current ? Shixun.where(:user_id => @user).count : Shixun.where(:user_id => @user).visible.count)
    # 创建课堂
    @create_courses_count = @user.courses.not_deleted_not_end.select{ |course| @user.has_teacher_role(course)}.count
    # 我的所有课程数
    @all_courses_count = @user.courses.not_deleted_not_end.count
    # 参与课堂
    @join_courses_count = @all_courses_count - @create_courses_count
    # 我合作的实训数
    coop_id = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id} and role = 2").map(&:shixun_id)   # 合作者的实训id
    @cooperative_num =  Shixun.where(:id => coop_id).count
    # 我挑战的实训数
    ch_id = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
    @challenge_num = Shixun.where(:id => ch_id).count
    #参与实训
    @join_shixuns = @cooperative_num + @challenge_num
    # 我的关注
    watch_query = User.watched_by(@user.id)
    @user_watchlist_count = watch_query.count()
    # 我的粉丝
    fan_query = @user.watcher_users
    @user_fanlist_count = fan_query.count()
  end

  # 实训留言
  def shixun_feedback
    @menu_type = 9
    @sub_type = 1
    @discusses = Discuss.where(:dis_type => "Shixun").reorder("created_at desc")
    @discusses_count =   @discusses.count
    @limit = 20
    @is_remote = true
    @page = (params['page'] || 1).to_i
    @discusses_pages = Paginator.new @discusses_count, @limit, @page
    @offset ||=  @discusses_pages.offset
    @discusses = paginateHelper @discusses, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 实训反馈
  def shixun_feedback_message
    @menu_type = 8
    @sub_type = 2
    @search = params[:search]
    @beginTime = params[:beginTime]
    @endTime = params[:endTime]
    if @search.present?
      shixun_ids = Shixun.where("name like ?", "%#{params[:search]}%").pluck(:id)
      @discusses = Discuss.where(:dis_type => "Shixun", :dis_id => shixun_ids).reorder("created_at desc")
    else
      @discusses = Discuss.where(:dis_type => "Shixun").reorder("created_at desc")
    end

    if params[:beginTime] && params[:beginTime].strip != ""
      @discusses = @discusses.where("created_at >= '#{Time.parse(params[:beginTime])}'")
    end
    if params[:endTime] && params[:endTime].strip != ""
      @discusses = @discusses.where("created_at <= '#{Time.parse(params[:endTime])}'")
    end

    @all_discusses = @discusses
    @discusses_count =  @discusses.count
    @limit = 20
    @is_remote = true
    @page = (params['page'] || 1).to_i
    @discusses_pages = Paginator.new @discusses_count, @limit, @page
    @offset ||=  @discusses_pages.offset
    @discusses = paginateHelper @discusses, @limit
    respond_to do |format|
      format.js
      format.html
      format.xls{
        shixun_ids = @all_discusses.pluck(:dis_id).uniq
        filename = "#{Time.now.strftime("%Y%m%d")}-实训反馈.xls"
        send_data(shixun_feedback_xls(shixun_ids, @beginTime, @endTime), :type => "text/excel;charset=utf-8; header=present", :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def evaluate_recod_time
    eva = EvaluateRecord.find(params[:record_id])
    @consume_time = eva.consume_time
    @student_work = eva.student_work
    @file_update = eva.file_update
    @git_pull = eva.git_pull
    @create_pod = eva.create_pod
    @pod_execute = eva.pod_execute
    @test_cases = eva.test_cases
    @return_back = eva.return_back
    @brige = eva.brige
    @front_js = eva.front_js
  end

  def evaluate_simple
    page = params[:page]
    @recodes = EvaluateRecord.where("created_at > ?", Time.now - 1.days).reorder("consume_time desc")
    @recodes_count = @recodes.size
    @record_pages = Paginator.new @recodes_count, 20, page || 1
    @offset ||=  @record_pages.offset
    @recodes = paginateHelper @recodes, 20
  end

  # 评测时间列表
  def evaluate_records
    shixun_tomcat = Redmine::Configuration['shixun_tomcat']
    uri = "#{shixun_tomcat}/bridge/monitor/getPodsInfo"
    res = uri_exec uri, params
    if res['code'] == 0
      @pod_num = res['sum']
      @pod_dis = JSON.parse(res['distr']) if res['distr'].present?
    end

    page = (params['page'] || 1).to_i
    search = params[:search]
    keyword = params[:keyword]
    limit = 20

    if search.present?
      if "u_name" == keyword
        @evaluate_recods = EvaluateRecord.joins("join users u on evaluate_records.user_id = u.id").where("concat(u.lastname, u.firstname) like '%#{search}%'")
        # @evaluate_recods = EvaluateRecord.where(user_id: User.where("concat(lastname, firstname) like '%#{search}%'").pluck(:id))
      else
        @evaluate_recods = EvaluateRecord.joins("join user_extensions ue on evaluate_records.user_id = ue.user_id").where("ue.school_id in (select id from schools where name like '%#{search}%')")
        # @evaluate_recods = EvaluateRecord.where(user_id: UserExtensions.where(school_id: School.where("name like '%#{search}%'").pluck(:id)).pluck(:user_id))
      end
    else
      @evaluate_recods = EvaluateRecord.where(nil)
    end

    if params[:beginTime].present?
      endTime = params[:endTime].present? ? params[:endTime] : Time.now
      @evaluate_recods = @evaluate_recods.where("created_at >= ? and created_at <= ?", params[:beginTime], endTime)
    end

    @evaluate_recods_count = @evaluate_recods.count
    @evaluate_recods_pages = Paginator.new @evaluate_recods_count, limit, page
    @evaluate_recods = @evaluate_recods.page(page).per(limit)
    @evaluate_recods = @evaluate_recods.includes(:shixun, :user)
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 作业回复
  def leave_message
    @menu_type = 8
    @sub_type = 1
    @jour = JournalsForMessage.where(:jour_type => 'HomeworkCommon').order("created_on desc")
    @jour_count =   @jour.count
    @page = (params['page'] || 1).to_i
    @limit = 20
    @is_remote = true
    @jour_pages = Paginator.new @jour_count, @limit, params['page'] || 1
    @offset ||=  @jour_pages.offset
    @jour = paginateHelper  @jour, @limit
    respond_to do |format|
      format.html
      format.js
    end
  end

  # 讨论区
  def messages_list
    @menu_type = 8
    @sub_type = 3
    @memo = Memo.where("0=0").order("created_at desc")
    @page = (params['page'] || 1).to_i
    @memo_count = @memo.count
    @limit = 20
    @is_remote = true
    @memo_pages = Paginator.new @memo_count, @limit, params['page'] || 1
    @offset ||=  @memo_pages.offset
    @memo = paginateHelper  @memo, @limit
    respond_to do |format|
      format.html
      format.js
    end
  end

  def course_messages_list
    @menu_type = 8
    @sub_type = 4
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    # @message = Message.find_by_sql("SELECT * FROM messages WHERE board_id IN (SELECT id FROM boards WHERE course_id IS NOT NULL) order by created_on #{@sx_order}")
    @message = Message.includes(:board).where("boards.course_id is not null").order("created_on #{@sx_order}")
    @page = (params['page'] || 1).to_i
    @message_count = @message.count
    @limit = 20
    @is_remote = true
    @message_pages = Paginator.new @message_count, @limit, params['page'] || 1
    @offset ||=  @message_pages.offset
    @message = paginateHelper @message, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end
  # 专业列表
  def profession
    @major=Major.where("0=0")
    # @menu_type = 12
    @sub_type = 1
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    major_level_option = params[:major_level] if params[:major_level]
    discipline_category_option = params[:discipline_category_id] if params[:discipline_category_id]
    first_level_discipline_option = params[:first_level_discipline_id] if params[:first_level_discipline_id]
    if major_level_option && major_level_option != '0'
      @major = @major.where(:major_level => major_level_option)
    end
    if discipline_category_option && discipline_category_option != '0'
      @major=@major.where(:discipline_category_id => discipline_category_option)
    end
    if first_level_discipline_option && first_level_discipline_option != '0'
      @major=@major.where(:first_level_discipline_id => first_level_discipline_option)
    end

    if params[:support_shixuns]
      @major = @major.where(:support_shixuns => params[:support_shixuns].to_i,:major_level=> 2)
    end

    @major = @major.order("created_at #{@sx_order}")
    @major_count =   @major.count
    limit = 20
    @is_remote = true
    @major_pages = Paginator.new @major_count, limit, params['page'] || 1
    @offset ||=  @major_pages.offset
    @major = paginateHelper  @major, limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 新增专业页面
  def new_major
    respond_to do |format|
      format.js
    end
  end

  # 新增专业
  def insert_major
    major_list = Major.create(:name=>params[:major],:first_level_discipline_id=>params[:first_level_discipline_id],:major_level=>params[:major_level],:discipline_category_id=>params[:discipline_category_id],:major_code=>params[:major_code])
    redirect_to profession_managements_path
  end

  # 支撑实训
  def support_shixun
    if params[:syllabus_id]
      major = Major.find params[:syllabus_id]
      major.update_attributes(:support_shixuns => !major.support_shixuns)
    end
  end

  # 实训适用课程
  def applicable_course
    # @menu_type = 12
    @sub_type = 2
    @major = Major.where(:major_level => 2,:support_shixuns => 1)
    @courselist = CourseList.where("0=0")
    search=params[:search]
    unless search.blank?
      @courselist = @courselist.where("name like '%#{search}%'")
    end
    @courselist = @courselist.reorder("created_at desc")
    @courselist_count = @courselist.count

    @limit = 15
    @is_remote = true
    @page = params['page'] ? params['page'].to_i : 1
    @courselist_pages = Paginator.new @courselist_count, @limit, @page
    @offset ||=@courselist_pages.offset
    @courselist = paginateHelper @courselist, @limit
    respond_to do |format|
      format.js
      format.html
    end
end

  # 增加课程
  def add_course
    courselist= CourseList.create(:name => params[:course])
    redirect_to applicable_course_managements_path
  end

  # 增加课程所属专业
  def add_major
    data = {result: 0}
    id = MajorCourse.where(:course_list_id => params[:course_list_id]).first
    if (id.nil?) || (params[:major_id].to_i != '0' && params[:major_id].to_i != id.major_id)
      MajorCourse.create(:course_list_id => params[:course_list_id],:major_id=>params[:major_id])
      data[:result] = 1
    end
    render :json => data
  end

  # 竞赛列表
  def competition
    @menu_type = 5
    @sub_type = 1
    @competitions = Competition.order("created_at desc")
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 竞赛报名列表
  def enroll_list
    @order = params[:order].blank? ? "desc" : params[:order]
    @competition = Competition.where(:id => params[:competition]).first

    @only_teacher = @competition.competition_staffs.count == 1 && @competition.competition_staffs.first.category == 'teacher'

    @team_members = @competition.team_members
    @team_members = @team_members.where("team_members.is_teacher = 0") unless @only_teacher # 只有老师报名时才显示老师,此时老师作为队员

    if params[:school] || params[:location]
      school_ids = School.where("schools.name like '%#{params[:school]}%'").pluck(:id)
      school_ids = school_ids.size == 0 ? "(-1)" : "(" + school_ids.join(",") + ")"
      location = params[:location] && params[:location] != "0" ? params[:location] : ""
      @team_members = @team_members.where("user_extensions.school_id in #{school_ids} and schools.province like '%#{location}%'")
    end
    @page = params[:page] || 1
    @team_members = @team_members.reorder("team_members.created_at #{@order}")
    all_members = @team_members
    @team_members = paginateHelper(@team_members.includes(competition_team: [:user, teachers: :user], user: { user_extensions: :school }), 50)
    respond_to do |format|
      format.js
      format.html
      format.xls{
        filename = "#{Time.now.strftime("%Y%m%d")}-#{@competition.name}.xls"
        send_data(competition_member_xls(all_members, @competition), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def competition_setting
    @menu_type = 5
    @sub_type = 1
    if Competition.where(:identifier => params[:com_id]).blank?
      @competition = Competition.where(:id => params[:com_id]).first
    else
      @competition = Competition.where(:identifier => params[:com_id]).first
    end
  end

  def create_competition_text
    CompetitionTextConfig.create(:name => params[:name], :description => params[:description], :competition_id => params[:competition_id])
    render :json => {:status => 1}
  end

  def delete_competition_text
    ctc = CompetitionTextConfig.find params[:id]
    ctc.destroy
    render :json => {:status => 1}
  end

  # 导入单位部门
  def import_departments
    attachments = params[:attachments]
    attachments.each do |attachment|
      attachment = Attachment.find_by_token_only(attachment[1]['token'])
      if attachment.present?
        attachment.container_id = 1
        attachment.container_type = "ImportDepartment"
        attachment.save
      end
    end

    new_atta = Attachment.where(:container_id => 1, :container_type => "ImportDepartment").last
    if new_atta.present?
      Rails.logger.info("---------------------attachment_id: #{new_atta.id}")

      path = new_atta.disk_directory
      name = new_atta.disk_filename
      if name.split(".").last == "xls"
        begin
          xls = Roo::Spreadsheet.open("files/#{path}/#{name}",extension: :xls)
          worksheet = xls.sheet(0)
          n2 = worksheet.last_row   #最后一行数
          rows = n2 - 1
          count = 0
          rows.times do |r|  #行数
            school_id = worksheet.cell(r+2, 1)
            if school_id.present?
              school = School.where(:id => school_id).first
              if school.present?
                if school.departments.where(:name => worksheet.cell(r+2, 2)).count == 0
                  school.departments << Department.new(:name => worksheet.cell(r+2, 2), :is_auth => 1)
                  count = count + 1
                end
              end
            end
          end
          @status = "已导入#{count}个部门"
        rescue
          @status = "无法完成导入,原因:文件内容无法读取"
        end
      else
        @status = "无法完成导入,原因:文件类型错误(只支持.xls文件)"
      end
      new_atta.destroy
    else
      @status = "无法完成导入,原因:文件不存在"
    end
    respond_to do |format|
      format.js
    end
  end

  # 单位部门列表
  def departments
    @menu_type = 6
    @sub_type = 2
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    @department = Department.where(:is_auth => 1).is_active
    search = params[:search]
    admin = params[:admin].to_i
    url = params[:url].to_i
    if search.blank?
        @department = @department
    else
        apply = School.where("name like '%#{search}%'").map(&:id)
        @department = @department.where(:school_id => apply)
    end
    if admin == 0
      @department = @department
    else
      department_ids = DepartmentMember.pluck(:department_id).uniq
      @department = @department.where(:id => department_ids)
    end

    if url == 1
      @department = @department.where("identifier is not null and identifier != ''")
    end

    @department = @department.reorder("created_at #{@sx_order}")
    @page = (params['page'] || 1).to_i
    @department_count =@department.count
    @limit = 20
    @is_remote = true
    @department_pages = Paginator.new @department_count, @limit, params['page'] || 1
    @offset ||=@department_pages.offset
    @department = paginateHelper @department, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  def partners
    @menu_type = 6
    @sub_type = 3
    if params[:search].blank?
      @partners = Partner.includes(:school).order("partners.created_at desc")
    else
      @partners = Partner.includes(:school).where("schools.name like ? ", "%#{params[:search]}%").order("partners.created_at desc")
    end

    @current_partner = nil
    if params[:partner]
      @current_partner =  @partners.find params[:partner]
    else
      @current_partner =  @partners[0] if @partners.size > 0
    end

    respond_to do |format|
      format.js
      format.html
    end
  end

  def get_partner
    @partner = Partner.find partner

  end

  def delete_partner
    partner = Partner.find params[:partner_id]
    partner.destroy
    @partners = Partner.includes(:school).order("partners.created_at desc")
    @current_partner = nil
  end


  # 添加客户
  def customers_list
    @search = params[:search]
    @province = params[:province]
    partner_id = params[:partner_id]
    @partner = Partner.find partner_id
    @customers = @partner.customers
    existed_school_ids = @customers.pluck(:school_id)
    existed_school_ids = existed_school_ids.present? ? existed_school_ids.join(",") : -1
    @schools = School.where("id not in (#{existed_school_ids})")

    if params[:search]
      @schools = @schools.where("name like ?", "%#{@search}%")
    end

    if params[:province] && params[:province] != '0'
      @schools = @schools.where("province like ?", "%#{@province}%")
    end
    @limit = 10
    @page = params[:page] || 1
    @schools_count = @schools.count

    @total_pages = (@schools_count / 10.0).ceil
    @schools = paginateHelper @schools, @limit
    respond_to do |format|
      format.js
      format.json {
        render json: @schools
      }
    end
  end

  def add_customers
    school_ids = params[:school_ids]
    partner_id = params[:partner_id]
    if school_ids.length > 0 && partner_id.present?
      school_ids.each do |s|
        school = School.where("id = ?",s).first
        if school.present?
          customer = Customer.new(school_id: s)
          customer.save!
          PartnerCustomer.create!(partner_id: partner_id,customer_id: customer.id )
          school.update_attributes(customer_id: customer.id)
        end
      end
      render :json => {status: 1, message: "创建成功!"}
    end
  end

  def delete_customers
    if params[:customer]
      customer = Customer.find(params[:customer])
      @current_partner = Partner.find(params[:partner_id])
      customer.destroy
    end
  end

  # 添加合作伙伴弹框数据
  def all_partners
    @search = params[:search]
    @province = params[:province]
    # 已经选过的合作伙伴不能再再列表中显示
    used_school_ids = Partner.pluck(:school_id)
    used_school_ids = used_school_ids.blank? ? -1 : used_school_ids.join(",")
    @schools = School.where("id not in (#{used_school_ids})")

    if params[:search]
      @schools = @schools.where("name like ?", "%#{@search}%")
    end

    if params[:province] && params[:province] != '0'
      @schools = @schools.where("province like ?", "%#{@province}%")
    end

    @limit = 10
    @page = params[:page] || 1
    @schools_count = @schools.count

    @total_pages = (@schools_count / 10.0).ceil
    @schools = paginateHelper @schools, @limit
    respond_to do |format|
      format.js
      format.json {
        render json: @schools
      }
    end
  end

  def add_partner
    school_ids = params[:school_ids]
    if school_ids.length > 0
      school_ids.each do |s|
        old_partner = Partner.where(:school_id => s)
        if old_partner.blank?
          partner = Partner.new(school_id: s)
          partner.save
        end
      end
    end
    render :json => {status: 1, message: "创建成功!"}
  end

  # 删除部门管理员
  def delete_depart_member
    DepartmentMember.where(:department_id => params[:depart], :user_id => params[:user_id]).destroy_all
  end

  # 添加部门管理员-弹框
  def add_depart_member_box
    @department = Department.where(:id => params[:depart]).first
    #@members = User.where(:id => UserExtensions.where(:school_id => @department.try(:school_id)).map(&:user_id), :certification => 1)

    @members =
        if params[:search]
          User.where("LOWER(concat(lastname, firstname, nickname, mail)) LIKE '%#{params[:search]}%'")
        else
          User.where(:certification => 1)
        end
    @members = paginateHelper @members, 8
  end

  # 添加部门管理员
  def add_depart_member
    if params[:depart] && params[:depart_member]
      @department = Department.where(:id => params[:depart]).first
      params[:depart_member].each do |member|
        @department.department_members << DepartmentMember.new(:user_id => member)
      end
    end
    redirect_to partners_managments_path

    # respond_to do |format|
    #   format.html {render :layout => "base_edu"}
    #   format.js
    # end

  end

  # 添加合作伙伴管理员- 弹框
  def add_partner_member_box
    @partner = Partner.where(:id => params[:partner]).first
    @members =
        if params[:search]
          User.where("LOWER(concat(lastname, firstname, nickname, mail)) LIKE '%#{params[:search]}%' AND partner_id is NULL")
        else
          User.where(:certification => 1, :partner_id => nil )
        end
    @total_pages = (@members.count / 10.0).ceil
    @members = paginateHelper @members, 10
    respond_to do |format|
      format.js
      format.json {
        render json: member_json_data(@members)
      }
    end
  end

  # 合作伙伴添加管理员
  def add_partner_member
    if params[:partner] && params[:partner_member]
      @partner = Partner.find_by_id params[:partner]
      params[:partner_member].each do |member|
        user = User.find_by_id member
        user.update_attributes(partner_id: @partner.id) if !@partner.nil? && !user.nil?
      end
    end
  end

  # 合作伙伴删除管理员
  def delete_partner_member
    if params[:partner] && params[:partner_member]
      @partner = Partner.find_by_id params[:partner]
      user = User.find_by_id params[:partner_member]
      user.update_attributes(partner_id: nil) if !@partner.nil? && !user.nil?
    end
  end


  # check 部门 identifier是否重复
  def check_depart_identifier
    logger.info("###############{params}")
    if params[:depart]
      result = Department.where("id != #{params[:depart]} and identifier = '#{params[:identifier]}'").count == 0 || params[:identifier] == ""
      render :json => {result: result}
    end
  end

  # 更新部门 identifier
  def update_depart_identifier
    if params[:depart] && params[:identifier]
      @department = Department.where(:id => params[:depart]).first
      identifier = params[:identifier].strip.blank? ? nil : params[:identifier].strip
      @department.update_attributes(:identifier => identifier) if @department.present?
    end
  end

  # 更新部门 host_count
  def update_host_count
    if params[:depart] && params[:host_count]
      @department = Department.where(:id => params[:depart]).first
      @department.update_attributes(:host_count => params[:host_count]) if @department.present?
    end
  end

  # 新增
  def create_departments
    dep = Department.order("created_at desc").first
    @latest_school = School.find(dep.try(:school_id)).try(:name)
    @school_id = dep.try(:school_id)

    respond_to do |format|
      format.js
    end
  end

  def add_department
    department = Department.where(:school_id => params[:school], :name => params[:department]).first
    if department.nil?
      department = Department.create(:school_id => params[:school],:name => params[:department],:is_auth => 1)
      ApplyAddDepartment.create(:school_id => params[:school],
                                :status => 1,
                                :name => params[:department],
                                :department_id => department.id,
                                :user_id => User.current.id)
    end
    redirect_to departments_managements_path
  end

  # 更改单位部门列表
  def update_department
    dep = Department.find params[:department_id]
    @edit_id = params[:department_id]
    @search = params[:search]
    if !params[:search].nil?
      search = "%#{params[:search].to_s.strip.downcase}%"
      @departments = Department.where("school_id = #{dep.school_id} and is_auth = 1 and id != #{params[:department_id].to_i} and #{Department.table_name}.name like :p", :p => search)
      #@schools = School.all
    else
      @departments = Department.where("school_id = #{dep.school_id} and is_auth = 1 and id != #{params[:department_id].to_i}")
    end
    respond_to do |format|
      format.js
    end
  end

  # 修改部门名称
  def update_depart_name
    @depart = Department.find(params[:depart_id])
    @depart.update_attributes(:name => params[:depart_name]) if @depart.school.departments.where(name: params[:depart_name]).count == 0
  end

  # 检查是否存在同名的部门
  def check_depart_name
    depart = Department.find(params[:depart_id])
    if depart.school.departments.where(name: params[:depart_name]).count == 0
      render :json => {status: 0, message: ""}
    else
      render :json => {status: -1, message: "该名称已存在"}
    end
  end

  def edit_departments_school
    begin
      dep = Department.find(params[:department_id])
      alter_dep = Department.find(params[:alter_dep_id])
      apply_dep = ApplyAddDepartment.where(:department_id => params[:alter_dep_id])
      if dep && alter_dep && dep != alter_dep
        # users = UserExtensions.where("department_id = #{dep.id}")
        # users.update_all(:department_id => params[:alter_dep_id])
        # dep.destroy
        # apply_dep.update_all(:status => 2)
        # ApplyAddDepartment.where(:department_id =>params[:departments]).update_all(:department_id=>department_id)
        # users = UserExtensions.where("department_id = #{alt_dep.department_id}")
        # users.update_all(:department_id => department.id)
        apply_dep.destroy_all
        users = UserExtensions.where(:department_id =>  params[:alter_dep_id])
        users.update_all(:department_id => dep.id)
        dep.update_attributes(:identifier => alter_dep.identifier) if dep.identifier.nil? && alter_dep.identifier.present?
        alter_dep.destroy
      end
    rescue Exception => e
      puts e
    end
    redirect_to departments_managements_path
  end

  # 单位列表
  def departments_part
    @menu_type = 6
    @sub_type = 1
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    search = params[:search]
    if search.blank?
      @schools = School.where("0=0")
    else
      @schools = School.where("name like ?", "%#{search}%")
    end
    if params[:index] == '8'
      @schools = @schools.reorder("created_at #{@sx_order}")
      @order_type = "created_at"
    elsif params[:index] == '9'
      @schools = @schools.reorder("updated_at #{@sx_order}")
      @order_type = "updated_at"
    elsif params[:index] == "6"
      @order_type = "usercount"
      @schools.each do |school|
        school[:usercount] = UserExtensions.where(:school_id => school.id).count
      end
      @sx_order == "desc" ?  @schools = @schools.sort{|x,y| y[:usercount] <=> x[:usercount]} : @schools = @schools.sort{|x,y| x[:usercount] <=> y[:usercount]}
    else
      @schools = @schools.reorder("created_at #{@sx_order}")
    end

    @page = (params['page'] || 1).to_i
    @schools_count = @schools.count
    @limit = 20
    @is_remote = true
    @schools_pages = Paginator.new @schools_count, @limit, params['page'] || 1
    @offset ||= @schools_pages.offset
    @schools= paginateHelper @schools, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end


  # 新增部门名称
  def add_departments_part

  end

  # 修改单位名称
  def upload_logo
    @menu_type = 6
    @sub_type = 1
    @next_type = 1
    @school = School.find(params[:school])

  end

  # 添加学校视频描述
  def add_contents_for_school
    school = School.find params[:school_id]
    school.update_attributes(:video_desc => params[:video_desc], :video_name => params[:video_name])
    render :json => {status: 1, message: "创建成功!"}
  end

  # 添加学校课程信息
  def add_course_info_for_school
    school = School.find params[:school_id]
    school.update_attributes(:course_link => params[:course_link], :course_name => params[:course_name])
    render :json => {status: 1, message: "创建成功!"}
  end

  # 修改单位名称为其他
  def school_upload_logo
    school = School.where(:id => params[:applied_id]).first
    ApplyAddSchools.where(:school_id => params[:applied_id]).destroy_all
    before_apply_departments = Department.where(:school_id => params[:applied_id])
    before_apply_departments.each do |department|
      after_dep = Department.where(:school_id => params[:school_id], :name => department.name).first
      if after_dep
        UserExtensions.where(:school_id => params[:applied_id], :department_id => department.id).update_all(:department_id => after_dep.id)
        department.apply_add_departments.destroy_all
        department.destroy
      else
        department.apply_add_departments.update_all(:school_id => params[:school_id])
        department.update_attribute(:school_id, params[:school_id])
      end
    end
    UserExtensions.where(:school_id => params[:applied_id]).update_all(:school_id => params[:school_id])
    school.destroy
    redirect_to departments_part_managements_path
  end

  # 修改单位信息
  def school_message_update
    school_name = params[:schoolname]
    school_id = params[:school_id]
    School.where(:id => school_id).update_all(:name => school_name,:province => params[:province],:city =>params[:city],:address => params[:address],:shool_code => params[:school_code], :identifier => params[:identifier])
    redirect_to departments_part_managements_path

  end

  # 删除单位
  def delete_school
    school = School.where(:id => params[:school]).first
    UserExtensions.where(:school_id => params[:school]).update_all(:school_id => nil, :department_id => nil)
    ApplyAddSchools.where(:school_id => params[:school]).destroy_all
    ApplyAddDepartment.where(:school_id => params[:school]).destroy_all
    school.destroy
    redirect_to departments_part_managements_path
  end

  def save_school
    uploaded_io = params[:logo]
    school_pinyin = Pinyin.t(params[:schoolname].strip, splitter: '')
    sl = School.create(:name => params[:schoolname],:province => params[:province],:city => params[:city],:address => params[:address],:pinyin =>school_pinyin)
    # unless uploaded_io.nil?
    #   File.open(Rails.root.join('public', 'images', 'school', sl.id.to_s+'.png'), 'wb') do |file|
    #     file.write(uploaded_io.read)
    #   end
    #   sl.logo_link  = '/images/school/'+sl.id.to_s+'.png'
    #   sl.save
    # end

    @user = User.current
    @se = @user.extensions

    # if @user.save && @se.save
    #   diskfile1 = disk_filename('school', sl.id , 'id')
    #   diskfileID = diskfile1 + 'temp'
    #   begin
    #     FileUtils.mv diskfileID, diskfile1, force: true if File.exist? diskfileID
    #   ensure
    #     File.delete(diskfileID) if File.exist?(diskfileID)
    #   end
    # end
    redirect_to departments_part_managements_path
  end

  # 部门审核
  def depart
    @menu_type = 10
    @sub_type = 3
    search = params[:search]
    @apply_status = ApplyAddDepartment.where(:status=>0)
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    if search.blank?
      @apply_status = @apply_status.where("0=0")
    else
      @apply_status= @apply_status.where("name like '%#{search}%'")
    end
    @apply_status = @apply_status.order("created_at #{@sx_order}")
    @apply_status_count = @apply_status.count
    limit = 20
    @is_remote = true
    @apply_status_pages = Paginator.new @apply_status_count, limit, params['page'] || 1
    @offset ||=@apply_status_pages.offset
    @apply_status = paginateHelper @apply_status, limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 批准
  def approve_applied_departments
    applied_department = ApplyAddDepartment.find(params[:id])
    applied_message = AppliedMessage.where(:applied_id => applied_department.id, :applied_type => "ApplyAddDepartment")
    applied_message.update_all(:status => 1)
    if applied_department.department
      applied_department.department.update_attributes(:is_auth => 1)
    end
    applied_department.update_attribute(:status, 1) unless applied_department.nil?
    # AppliedMessage.create(:user_id => applied_department.user_id, :status => 1, :viewed => 0, :applied_id => applied_department.id, :applied_type => "ApplyAddDepartment", :name => applied_department.name )
    UserExtensions.where(:user_id => applied_department.user_id).update_all(:department_id => applied_department.department_id)
    Tiding.where(:user_id => 1, :trigger_user_id => applied_department.user_id, :container_id => applied_department.id, :container_type => 'ApplyAddDepartment', :status => 0, :tiding_type => "Apply").update_all(:status => 1)
    Tiding.create(:user_id => applied_department.user_id, :trigger_user_id => 0, :container_id => applied_department.id, :container_type =>'ApplyAddDepartment', :belong_container_id => applied_department.department.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 1)

    respond_to do |format|
      format.html{ redirect_to depart_managements_path }
    end
  end

  # 删除
  def delete_applied_departments
    applied_department = ApplyAddDepartment.find params[:depart_id]
    applied_message = AppliedMessage.where(:applied_id => applied_department.id, :applied_type => "ApplyAddDepartment")
    applied_message.update_all(:status => 3)
    applied_department.update_attribute(:status, 3)
    # 未审批删除
    if params[:tip] == "unapplied"
      # AppliedMessage.create(:user_id => applied_department.user_id, :status => 3, :viewed => 0, :applied_id => applied_department.id, :applied_type => "ApplyAddDepartment", :name => applied_department.name )
      Tiding.where(:user_id => 1, :trigger_user_id => applied_department.user_id, :container_id => applied_department.id, :container_type => 'ApplyAddDepartment', :status => 0, :tiding_type => "Apply").update_all(:status => 1)
      Tiding.create(:user_id => applied_department.user_id, :trigger_user_id => 0, :container_id => applied_department.id, :container_type =>'ApplyAddDepartment', :belong_container_id => applied_department.department.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 2, :extra => params[:reason])
      # 删除学校的用户
      users = UserExtensions.where("department_id = #{applied_department.department_id}")
      users.update_all(:department_id => nil)
      applied_department.department.destroy
      # 已审批删除
    elsif params[:tip] == "applied"
      applied_department.destroy
    end
    respond_to do |format|
      format.html{ redirect_to depart_managements_path }
    end
  end

  # 部门修改
  def all_department
    @edit_id = params[:department_id]
    @search = params[:search]
    dep = ApplyAddDepartment.where(:id => @edit_id).first
    if !params[:search].nil?
      search = "%#{params[:search].to_s.strip.downcase}%"
      @department = dep.school.departments.where("is_auth = 1 and #{Department.table_name}.name like :p", :p => search)
    else
      @department = dep.school.departments.where(:is_auth => 1)
    end
    respond_to do |format|
      format.js
    end
    # redirect_to unit_managements_path
  end

  # 修改
  def edit_applied_department
    aas =ApplyAddDepartment.find(params[:applied_id])
    # aas.update_attribute(:name, params[:name])
    #applied_add_school = ApplyAddSchools.where(:name => aas.name)
    department =Department.find params[:department_id]
    begin
      #更新消息表的status
      if aas.department_id != department.id.to_i
        apply_depart_id = aas.department_id
        applied_message = AppliedMessage.where(:applied_id => apply_depart_id, :applied_type => "ApplyAddDepartment")
        applied_message.update_all(:status => 4)
        aas.update_attribute(:status, 2)
        aas.tidings.update_all(:status => 1)
        extra = department.name + "(#{department.school.try(:name)})"
        Tiding.create(:user_id => aas.user_id, :trigger_user_id => 0, :container_id => aas.id, :container_type =>'ApplyAddDepartment', :belong_container_id => department.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 3, :extra => extra)
        # AppliedMessage.create(:user_id => aas.user_id, :status => 2, :viewed => 0, :applied_id => aas.id, :applied_type => "ApplyAddDepartment", :name =>department.name )
        users = UserExtensions.where("department_id = #{aas.department_id}")
        users.update_all(:department_id => department.id)
        aas.department.destroy
        ApplyAddDepartment.where(:department_id => aas.department_id).update_all(:department_id => department.id)
        Department.where(:department_id => aas.department_id).destroy_all
        aas.destroy_all
      end
    rescue Exception => e
      puts e
    end
    redirect_to depart_managements_path
  end

  # 单位审批
  def unit
    @menu_type = 10
    @sub_type = 4
    search = params[:search]
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    @apply_status = ApplyAddSchools.where(:status=>0)
    if search.blank?
      @apply_status = @apply_status.where("0=0")
    else
      @apply_status= @apply_status.where("name like '%#{search}%'")
    end
    @apply_status = @apply_status.order("created_at #{@sx_order}")
    @apply_status_count = @apply_status.count
    limit = 20
    @is_remote = true
    @apply_status_pages = Paginator.new @apply_status_count, limit, params['page'] || 1
    @offset ||= @apply_status_pages.offset
    @apply_status = paginateHelper @apply_status, limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 单位审批批准
  def approve_applied_schools
    applied_school = ApplyAddSchools.where(:id =>params[:id]).first
    applied_message_id = applied_school.school_id
    applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
    applied_message.update_all(:status => 1)
    unless applied_school.nil?
      applied_school.update_column('status', 1)
    end
    school = applied_school.school
    school.update_attribute("province", applied_school.province)
    AppliedMessage.create(:user_id => applied_school.user_id, :status => 1, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
    Tiding.where(:user_id => 1, :trigger_user_id => applied_school.user_id, :container_id => applied_school.id, :container_type => 'ApplyAddSchools', :status => 0, :tiding_type => "Apply").update_all(:status => 1)
    Tiding.create(:user_id => applied_school.user_id, :trigger_user_id => 0, :container_id => applied_school.id, :container_type =>'ApplyAddSchools', :belong_container_id => applied_school.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 1)
    redirect_to unit_managements_path
    end

  # 删除
  def delete_applied_schools
    applied_school = ApplyAddSchools.find(params[:school_id])
    applied_message_id = applied_school.school_id
    applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
    applied_message.update_all(:status => 3)
    applied_school.update_attribute(:status, 3)
    # 单位对应的部门审核也应做删除处理
    applied_departments = ApplyAddDepartment.where(:school_id => applied_school.school_id)
    applied_departments.update_all(:status => 3)
    AppliedMessage.where(:applied_id => applied_departments.map(&:id), :applied_type => "ApplyAddDepartment").update_all(:status => 3)

    # 删除学校的用户
    users = UserExtensions.where("school_id = #{applied_school.school_id}")

    # 申请了职业认证的用户撤销申请
    apply_user_auth = ApplyUserAuthentication.where(:user_id => users.map(&:user_id), :auth_type => 2, :status => 0)
    apply_user_auth.each do |apply|
      apply.tidings.destroy_all
      apply.update_attribute('status', 3)
      diskfile2 = disk_auth_filename('UserAuthentication', apply.user_id, 'PRO')
      diskfilePRO = diskfile2 + 'temp'
      File.delete(diskfilePRO) if File.exist?(diskfilePRO)
      File.delete(diskfile2) if File.exist?(diskfile2)
    end

    users.update_all(:school_id => nil, :department_id => nil)

    # 未审批删除
    if params[:tip] == "unapplied"
      # AppliedMessage.create(:user_id => applied_school.user_id, :status => 3, :viewed => 0, :applied_id => applied_school.id, :applied_type => "ApplyAddSchools", :name => applied_school.name )
      Tiding.where(:user_id => 1, :trigger_user_id => applied_school.user_id, :container_id => applied_school.id, :container_type => 'ApplyAddSchools', :status => 0, :tiding_type => "Apply").update_all(:status => 1)
      Tiding.create(:user_id => applied_school.user_id, :trigger_user_id => 0, :container_id => applied_school.id, :container_type =>'ApplyAddSchools', :belong_container_id => applied_school.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 2, :extra => params[:reason])

      Tiding.where(:user_id => 1, :container_id => applied_departments.map(&:id), :container_type => 'ApplyAddDepartment', :status => 0, :tiding_type => "Apply").update_all(:status => 1)
      if applied_departments.first
        Tiding.create(:user_id => applied_departments.first.user_id, :trigger_user_id => 0, :container_id => applied_departments.first.id, :container_type =>'ApplyAddDepartment', :belong_container_id => applied_school.school_id, :belong_container_type=> 'School', :tiding_type => "System", :status => 2)
        AppliedMessage.create(:user_id => applied_departments.first.user_id, :status => 3, :viewed => 0, :applied_id => applied_departments.first.id, :applied_type => "ApplyAddDepartment", :name => applied_departments.first.name )
      end
      applied_school.school.destroy
      applied_school.school.departments.destroy_all
      redirect_to unit_managements_path
      # 已审批删除
    elsif params[:tip] == "applied"
      applied_departments.destroy_all
      applied_school.destroy
      redirect_to unit_managements_path
    end
  end

  # 单位审批修改
  def all_schools
    apply_schools = ApplyAddSchools.where("status = 0")
    apply_school_ids = apply_schools.empty? ? "(#{params[:school_id].to_i})" : "(" + apply_schools.map{|sc| sc.school_id}.join(',') + ")"
    if !params[:search].nil?
      search = "%#{params[:search].to_s.strip.downcase}%"
      @schools = School.where("id not in #{apply_school_ids} and id != #{params[:school_id].to_i} and #{School.table_name}.name like :p", :p => search)
    else
      @schools = School.where("id not in #{apply_school_ids} and id != #{params[:school_id].to_i}")
    end
    @edit_id = params[:school_id]
    @search = params[:search]
    @upload = params[:upload]
    respond_to do |format|
      format.js
    end
  end

  # 修改
  def edit_applied_schools
    aas = ApplyAddSchools.find(params[:applied_id])
    school = School.find params[:school_id]
    begin
      #更新消息表的status
      if aas.school_id != school.id.to_i
        applied_message_id = aas.school_id
        applied_message = AppliedMessage.where(:applied_id => applied_message_id, :applied_type => "ApplyAddSchools")
        applied_message.update_all(:status => 4)
        Tiding.where(:user_id => 1, :trigger_user_id => aas.user_id, :container_id => aas.id, :container_type => 'ApplyAddSchools', :status => 0, :tiding_type => "Apply").update_all(:status => 1)

        aas.update_attribute(:status, 2)
        # AppliedMessage.create(:user_id => aas.user_id, :status => 2, :viewed => 0, :applied_id => aas.id, :applied_type => "ApplyAddSchools", :name => school.name )
        extra = school.try(:name).to_s
        Tiding.create(:user_id => aas.user_id, :trigger_user_id => 0, :container_id => aas.id, :container_type =>'ApplyAddSchools', :belong_container_id => school.id, :belong_container_type=> 'School', :tiding_type => "System", :status => 3, :extra => extra)
        users = UserExtensions.where("school_id = #{aas.school_id}")
        users.update_all(:school_id => school.id)
        ApplyAddDepartment.where(:school_id => aas.school_id).update_all(:school_id => school.id)
        # 判断重复
        before_apply_departments = Department.where(:school_id => aas.school_id)
        before_apply_departments.each do |department|
          after_dep = Department.where(:school_id => params[:school_id], :name => department.name).first
          if after_dep.present?
            UserExtensions.where(:school_id => aas.school_id, :department_id => department.id).update_all(:department_id => after_dep.id)
            department.destroy
            department.apply_add_departments.destroy_all
          else
            department.apply_add_departments.update_all(:school_id => school.id)
            department.update_attribute(:school_id, school.id)
          end
        end
        UserExtensions.where(:school_id => aas.school_id).update_all(:school_id => params[:school_id])

        # Department.where(:school_id => aas.school_id).update_all(:school_id => school.id)
        aas.school.destroy
        aas.update_attribute(:school_id, school.id)
      end
    rescue Exception => e
      puts e
    end
    redirect_to unit_managements_path
  end

  # 课程列表
  def classroom
    @menu_type = 2
    @sub_type = 1
    @courselist = CourseList.where("0=0")
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    keyword = params[:keyword]
    search = params[:search]

    if params[:support_shixuns_search_title]
      @courselist = @courselist.where(:support_shixuns_search => params[:support_shixuns_search_title].to_i)
    end
    if search.blank?
      @courselist = @courselist
    else
        if "u_name" == keyword
          # user_id = User.where("concat(lastname, firstname) like '%#{search}%'")
          @courselist  = @courselist.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'")
        else
          @courselist = @courselist.where("name like '%#{search}%'")
        end
    end
    @courselist = @courselist.order("course_lists.id #{@sx_order}")
    @page = (params[:page] || 1).to_i
    @courselist_count = @courselist.count
    @limit = 20
    @courselist_pages = Paginator.new @courselist_count, @limit, @page
    @offset ||=  @courselist_pages.offset
    @courselist = paginateHelper @courselist,@limit

    # @courselist = @courselist.order("courselist.created_at #{@sx_order}")
    respond_to do |format|
      format.js
      format.html
    end
  end

  def rename_class
    @page = params[:page]
    @courselist = CourseList.where(:id => params[:course_list]).first
    if request.get?
      respond_to do |format|
        format.js
      end
    else
      if @courselist
        o_courselist = CourseList.where(:name => params[:name]).first
        if o_courselist
          @courselist.courses.each do |course|
            course.update_attributes(:name => course.name.sub(@courselist.name, params[:name]), :course_list_id => o_courselist.id)
          end
          @courselist.shixun_major_courses.update_all(:course_list_id => o_courselist.id, :major_id => @courselist.major_courses.first.try(:major_id))
          @courselist.destroy
        else
          @courselist.courses.each do |course|
            course.update_attribute(:name, course.name.sub(@courselist.name, params[:name]))
          end
          @courselist.update_attributes(:name => params[:name])
        end
      end
      redirect_to classroom_managements_path(:page => params[:page])
    end
  end

  def migrate_class
    @page = params[:page]
    @courselist = CourseList.where(:id => params[:course_list]).first
    if request.get?
      respond_to do |format|
        format.js
      end
    else
      if @courselist
        o_courselist = CourseList.where(:name => params[:name]).first
        if o_courselist
          @courselist.courses.each do |course|
            course.update_column(:course_list_id, o_courselist.id)
          end
          @courselist.shixun_major_courses.update_all(:course_list_id => o_courselist.id, :major_id => @courselist.major_courses.first.try(:major_id))
          @courselist.destroy
        else
          @courselist.update_column(:name, params[:name])
        end
      end
      redirect_to classroom_managements_path(:page => params[:page])
    end
  end

  # 支撑实训检索
  def support_shixuns_search
    if params[:shixun_id]
      courselist = CourseList.find params[:shixun_id]
      courselist.update_attributes(:support_shixuns_search => !courselist.support_shixuns_search)
    end
  end

  # 课堂列表
  def classroom_classment
    @menu_type = 2
    @sub_type = 2
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    @courses = Course.where(:is_delete => 0)
    @timing=Course.where(:is_end=>false).count
    @end=Course.where(:is_end=>true).count
    # unless params[:school_id] || params[:search] || params[:keyword] || params[:status]
    #   user_exs = UserExtensions.where(:school_id=> @courses.map(&:school_id))
    #   @schools = School.where(:id =>user_exs.map(&:school_id))
    # end
    @search  = params[:search]                                 # 搜索字
    @keyword = params[:keyword].blank? ? "c_name" : params[:keyword]    # 根据姓名/课程名搜索
    @status  = params[:status]
    @school_id = params[:school_id]

    if params[:school_id] && params[:school_id] != ''
      @courses = @courses.joins("join user_extensions ue on courses.tea_id = ue.user_id").where("ue.school_id = #{params[:school_id]}")
    end

    if params[:homepage_show]
      @courses = @courses.where(:homepage_show => params[:homepage_show].to_i)
    end

    if params[:course_list] && params[:course_list] != ''
      course_name = "%#{params[:course_list].strip}%"
      course_lists = CourseList.where("name like '#{course_name}'").map(&:id)
      @courses = @courses.where(:course_list_id => course_lists)
    end

    if params[:status] && params[:status]!=''
      @courses = @courses.where(:is_end => @status.to_i)
    end
    if "c_name" == @keyword
      @courses = @courses.where("name like ?", "%#{@search}%")
    elsif "u_name" == @keyword
      if @search.blank?
        @courses = @courses
      else
        # user_id = User.where("concat(lastname, firstname) like '%#{@search}%'")
        @courses = @courses.joins("join users u on courses.tea_id = u.id").where("concat(u.lastname, u.firstname) like '%#{@search}%'")
      end
    elsif "dep_name" == @keyword
      school = School.where("name like '%#{@search}%'").map(&:id)
      @courses = @courses.where(:school_id => school)
      # @courses= @courses.where("name like '%#{@search}%'")
    end
    @courses = @courses.select("courses.*,(SELECT MAX(updated_at)  FROM `course_activities` WHERE course_activities.course_id = courses.id) AS updatetime").order("updatetime desc")
    @page = (params['page'] || 1).to_i
    @export_courses = @courses
    @courses_count = @courses.count
    @limit = 20
    @is_remote = true
    @courses_pages = Paginator.new @courses_count, @limit, params['page'] || 1
    @offset ||=  @courses_pages.offset
    @courses = paginateHelper @courses, @limit
    respond_to do |format|
      format.js
      format.html
      format.xls{
        @export_courses = @export_courses.all
        filename = "#{l(:label_course_list_xls)}.xls"
        send_data(course_list_xls(@export_courses), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def hidden_course
    @course = Course.where(:id => params[:course_id]).first
    @course.update_attributes(:is_hidden => !@course.is_hidden) if @course.present?
  end

  def shixun_task
    @menu_type = 2
    @sub_type = 3

    homework_commons = HomeworkCommon.where(:homework_type => 4)
    @shixun_task = Course.where(:id => homework_commons.map(&:course_id))
    @keyword = params[:keyword]
    @search = params[:search]
    @school_id = params[:school_id]
    if params[:school_id] && params[:school_id] != ''
      @shixun_task = @shixun_task.joins("join users u on courses.tea_id = u.id").joins("join user_extensions ue on u.id = ue.user_id").where("ue.school_id = #{params[:school_id]}")
      # @shixun_task = @shixun_task.includes(:user => {:user_extensions => []}).where("user_extensions.school_id = #{params[:school_id]}")
    end

    unless @search.blank?
      if "u_name" == @keyword
        user_id = User.where("concat(lastname, firstname) like '%#{@search}%'")
        @shixun_task = @shixun_task.joins("join users u on courses.tea_id = u.id").where("concat(u.lastname, u.firstname) like '%#{@search}%'")
      else
        @shixun_task = @shixun_task.where("courses.name like '%#{@search}%'")
      end
    end

     # @shixun_task = @shixun_task.select("courses.*, (select h.publish_time from homework_commons h where h.course_id = courses.id group by courses.id) AS publish_time").reorder("publish_time desc")
    @page = (params['page'] || 1).to_i
    @shixun_task_count =  @shixun_task.size
    @export_shixun_task = @shixun_task
    @limit = 20
    @is_remote = true
    @shixun_task_pages = Paginator.new @shixun_task_count, @limit, params['page'] || 1
    @offset ||= @shixun_task_pages.offset
    @shixun_task = paginateHelper @shixun_task, @limit
    @shixun_task = @shixun_task.includes(:homework_commons => {:student_works => [], :homework_detail_manual => [], :shixuns => []}, :teacher => {:user_extensions => []})
    respond_to do |format|
      format.js
      format.html
      format.xls{
        # @export_shixun_task = @export_shixun_task.all
        filename = "#{l(:label_shixun_task_xls)}.xls"
        send_data(shixun_task_xls(@export_shixun_task), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def project_list
    @menu_type = 2
    @sub_type = 4
    @pr_order = params[:pr_order].blank? ? "desc" : params[:pr_order]
    @search  = params[:search].to_s
    @projects = Project.where("name like '%#{@search}%'").order("created_on #{@pr_order}")
    @limit = 20
    @page = (params['page'] || 1).to_i
    @projects = paginateHelper @projects, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 班级首页显示
  def course_homepage_show
    if params[:course_id]
      course = Course.find params[:course_id]
      course.update_attributes(:homepage_show => !course.homepage_show)
    end
  end

  # 课程实训
  def class_shixuns
    @menu_type = 4
    @sub_type = 1
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    @edit_class_sx_num=Subject.where(:status => 0).count
    @audit_class_sx_num=Subject.where(:status => 1).count
    @publish_class_sx_num=Subject.where(:status => 2).count
    @repertories = Repertoire.where(nil).order("CONVERT( name USING gbk ) COLLATE gbk_chinese_ci ASC")
    search  = params[:search]                                          # 搜索字
    keyword = params[:keyword].blank? ? "u_name" : params[:keyword]    # 根据姓名/课程名搜索
    status   = params[:status].to_i
    if params[:school_id] && params[:school_id] != '0'
      @c_shixuns = Subject.includes(:user => {:user_extensions => []}).where("user_extensions.school_id = #{params[:school_id]}")
    else
      @c_shixuns = Subject.where("0=0")
    end
    if params[:status] && params[:status]!=''
      @c_shixuns= @c_shixuns.where(:status =>status)
    end
    if search.blank?
      @c_shixuns = @c_shixuns
    else
      if "u_name" == keyword
        # user_id = User.where("concat(lastname, firstname) like '%#{search}%'")
        @c_shixuns  = @c_shixuns.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'")
      else
        @c_shixuns= @c_shixuns.where("name like '%#{search}%'")
      end
    end
    unless params[:school_id] || params[:search] || params[:keyword] || params[:status]
       user_exs = UserExtensions.where(:user_id => @c_shixuns.map(&:user_id))
       @schools = School.where(:id => user_exs.map(&:school_id))
    end
    @c_shixuns = @c_shixuns.order("subjects.created_at #{@sx_order}")
    @page = (params['page'] || 1).to_i
    @c_shixuns_count = @c_shixuns.count
    @limit = 20
    @c_shixuns_pages = Paginator.new @c_shixuns_count, @limit, @page
    @c_shixuns = paginateHelper @c_shixuns, @limit
    @offset ||= @c_shixuns_pages.offset
    respond_to do |format|
      format.js
      format.html
    end
  end

  def subject_setting_list
    @menu_type = 4
    @sub_type = 2
    @sx_order = params[:sx_order].blank? ? "desc" : params[:sx_order]
    @edit_class_sx_num=Subject.where(:status => 0).count
    @audit_class_sx_num=Subject.where(:status => 1).count
    @publish_class_sx_num=Subject.where(:status => 2).count
    @repertories = Repertoire.where(nil).order("CONVERT( name USING gbk ) COLLATE gbk_chinese_ci ASC")
    @levels = SubjectLevelSystem.all
    search  = params[:search]                                          # 搜索字
    keyword = params[:keyword].blank? ? "u_name" : params[:keyword]    # 根据姓名/课程名搜索
    status   = params[:status].to_i
    if params[:school_id] && params[:school_id] != '0'
      @c_shixuns = Subject.includes(:user => {:user_extensions => []}).where("user_extensions.school_id = #{params[:school_id]}")
    else
      @c_shixuns = Subject.where("0=0")
    end
    if params[:status] && params[:status]!=''
      @c_shixuns= @c_shixuns.where(:status =>status)
    end
    if search.blank?
      @c_shixuns = @c_shixuns
    else
      if "u_name" == keyword
        # user_id = User.where("concat(lastname, firstname) like '%#{search}%'")
        @c_shixuns = @c_shixuns.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'")
      else
        @c_shixuns = @c_shixuns.where("name like '%#{search}%'")
      end
    end
    unless params[:school_id] || params[:search] || params[:keyword] || params[:status]
      user_exs = UserExtensions.where(:user_id => @c_shixuns.map(&:user_id))
      @schools = School.where(:id => user_exs.map(&:school_id))
    end
    if params[:search_homepage_show]
      @c_shixuns = @c_shixuns.where(:homepage_show => params[:search_homepage_show].to_i)
    end
    @c_shixuns = @c_shixuns.order("subjects.created_at #{@sx_order}")
    @page = (params['page'] || 1).to_i
    @c_shixuns_count = @c_shixuns.count
    @limit = 20
    @c_shixuns_pages = Paginator.new @c_shixuns_count, @limit, params['page'] || 1
    @c_shixuns = paginateHelper @c_shixuns, @limit
    @offset ||= @c_shixuns_pages.offset
    respond_to do |format|
      format.js
      format.html
    end
  end

  def update_repertoire_of_subject
    subject = Subject.find(params[:subject_id])
    subject.update_attribute(:repertoire_id, params[:rep_id])

    render :json =>{ :data => "success"}
  end

  def update_subject_hidden
    @subject = Subject.find(params[:subject_id])
    @subject.update_column(:hidden, !@subject.hidden)
  end

  # 已发布课程实训
  def class_publish_shixuns
    @menu_type = 4
    @sub_type = 3
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    search  = params[:search]                                          # 搜索字
    keyword = params[:keyword].blank? ? "u_name" : params[:keyword]    # 根据姓名/课程名搜索
    if params[:school_id] && params[:school_id] != '0'
      @c_shixuns = Subject.includes(:user => {:user_extensions => []}).where("subjects.status = 2 and user_extensions.school_id = #{params[:school_id]}")
    else
      @c_shixuns = Subject.where(:status => 2)
    end
    if params[:beginTime] && params[:beginTime].strip != ""
      @c_shixuns = @c_shixuns.where("publish_time >= '#{Time.parse(params[:beginTime])}'")
    end
    if params[:endTime] && params[:endTime].strip != ""
      @c_shixuns = @c_shixuns.where("publish_time <= '#{Time.parse(params[:endTime])}'")
    end
    if search.blank?
      elsif "u_name" == keyword
        # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user
         user_id = User.where("concat(lastname, firstname) like '%#{search}%'")
        @c_shixuns  = @c_shixuns.includes(:user).where("concat(users.lastname, users.firstname) like '%#{search}%'")
      else
        @c_shixuns= @c_shixuns.where("name like '%#{search}%'")
      end
    unless params[:school_id] || params[:search] || params[:keyword]
      user_exs = UserExtensions.where(:user_id => @c_shixuns.map(&:user_id))
      @schools = School.where(:id => user_exs.map(&:school_id))
    end
    @page = (params['page'] || 1).to_i
    @c_shixuns = @c_shixuns.order("subjects.publish_time #{@sx_order}")
    @c_shixuns_count = @c_shixuns.count
    all_subjects = @c_shixuns.includes(stages: [:stage_shixuns])
    Rails.logger.warn("##########all_subjects:#{all_subjects.count}")
    @limit = 20
    @c_shixuns_pages = Paginator.new @c_shixuns_count, @limit, params['page'] || 1
    @offset ||= @c_shixuns_pages.offset
    @c_shixuns = paginateHelper @c_shixuns, @limit
    respond_to do |format|
      format.js
      format.html
      format.xls {
        filename = "已发布实训课程-#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}.xls"
        send_data(published_subject_xls(all_subjects), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  # 已发布实训路径首页显示
  def subject_homepage_show
    if params[:subject_id]
      subject = Subject.find params[:subject_id]
      subject.update_attributes(:homepage_show => !subject.homepage_show)
    end
  end

  # 导出excel
  def export_excel
    @course = params[:course]
    respond_to do |format|
      format.xls {
        @course = @course.reorder("#{Tracker.table_name}.position, #{Course.table_name}.id").all
        filename = "#{l(:label_course_list_xls)}.xls"
        send_data(course_list_xls(@course), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  # 0 全部;1 活动的; 2 已注册; 3 锁定
  def users
    @menu_type = 7
    @sub_type = 1
    status     = params[:user_status].nil? ? 0 : params[:user_status].to_i
    @us_order  = params[:us_order].blank? ? "desc" : params[:us_order]         # 排序
    @order_key = params[:order_key].blank? ? "last_login_on" : params[:order_key] # 排序关键字
    condition  = (params[:research_condition].nil? || params[:research_condition] == "name") ? "concat(lastname, firstname)" : params[:research_condition]
    if 0 == status
      if params[:research_condition] == "phone" && params[:research_contents].blank?
        @users =  User.where(nil)
      else
        @users =  User.where("#{condition} like '%#{params[:research_contents]}%'")
      end
    else
      if params[:research_condition] == "phone" && params[:research_contents].blank?
        @users =  User.where(:status => status)
      else
        @users = User.where("status = #{status} and #{condition} like '%#{params[:research_contents]}%'")
      end
    end

    if params[:identity] && params[:identity].to_i != -1
      @users = @users.includes(:user_extensions).where("user_extensions.identity = ?", params[:identity].to_i)
    end

    if params[:auto_school] && params[:auto_school].to_i != 0
      @users = @users.includes(:user_extensions => [:school]).where("schools.auto_users_trial = ?", params[:auto_school].to_i == 1 ? 1 : 0)
    end

    if params[:school] && params[:school] != ''
      school_name = params[:school]
      school = School.where("name like '%#{school_name}%'")
      school_id = school.map(&:id)
      user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
      @users = @users.where(:id => user_id)
    end

    @users = @users.order("#{@order_key} #{@us_order}")

    @page = (params['page'] || 1).to_i
    @users_count =  @users.count
    @limit = 20
    @is_remote = true
    @users_pages = Paginator.new @users_count, @limit, params['page'] || 1
    @offset ||= @users_pages.offset
    @users = paginateHelper @users, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  def shixuns
    @menu_type = 3
    @sub_type = 1
    @sx_status = (params[:status].blank? || params[:status].class == Array) ? [0, 1, 2, 3] : params[:status].to_i # 搜索实训的状态
    @keyword   = params[:keyword].blank? ? "u_name" : params[:keyword]        # 根据姓名/实训名搜索
    @search    = params[:search]                                              # 搜索的字
    @tech = params[:tech]
    @shixun_tag_id = params[:shixun_tag]
    @tech_system = MirrorRepository.where(nil).map(&:type_name).reject(&:blank?).sort()
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]       # 排序

    if "u_name" == @keyword
      # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user
      if @search.blank?
        @shixuns = Shixun.where(:status => @sx_status).order("created_at #{@sx_order}")
      else
        user_id = User.where("concat(lastname, firstname) like '%#{@search}%'")
        @shixuns = Shixun.where(:user_id => user_id, :status => @sx_status).order("created_at #{@sx_order}")
      end
    else
      if params[:keyword]  == "sx_name"
        @shixuns = Shixun.where("name like '%#{@search}%'").where(:status => @sx_status).order("created_at #{@sx_order}")
      else
        school_id = School.where("name like '%#{@search}%'").map(&:id)
        user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
        @shixuns = Shixun.where(:user_id => user_id).where(:status => @sx_status).order("created_at #{@sx_order}")
      end
    end
    #@shixuns = @shixuns.includes(:mirror_repositories).where("mirror_repositories.name like '%#{@tech}%'") if @tech.present?
    if @tech.present?
      shixuns_id = MirrorRepository.where(:type_name => @tech).first.try(:shixuns)
      @shixuns = @shixuns.where(:id => shixuns_id)
    end

    # shixun_tag_id: -1时 搜索没有技术标签的实训
    if @shixun_tag_id.present?
      if @shixun_tag_id.to_i == -1
        shixuns_id = ShixunTagRepertoire.where(nil).map(&:shixun_id)
        if shixuns_id.present?
          shixuns_id = @shixuns.map(&:id) - shixuns_id
          @shixuns = @shixuns.where(:id => shixuns_id)
        end
      else
        shixuns_id = ShixunTagRepertoire.where(:tag_repertoire_id => @shixun_tag_id).map(&:shixun_id)
        @shixuns = @shixuns.where(:id => shixuns_id)
      end
    end

    @shixun_xls = @shixuns
    @edit_sx_num = Shixun.where(:status => 0).count
    @audit_sx_num = Shixun.where(:status => 1).count
    @publish_sx_num =Shixun.where(:status => 2).count
    @close_sx_num = Shixun.where(:status => 3).count
    @page = (params['page'] || 1).to_i
    @shixuns_count = @shixuns.count
    @limit = 20
    @shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
    @offset ||= @shixuns_pages.offset
    @shixuns = paginateHelper @shixuns, @limit
    @shixun_tags = TagRepertoire.where(nil).order("name asc")
    respond_to do |format|
      format.js
      format.html
      format.xls{
        # @export_shixun_task = @export_shixun_task.all
        filename = "实训详情_#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}.xls"
        send_data(shixun_list_xls(@shixun_xls), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def shixun_setting_list
    @menu_type = 3
    @sub_type = 2
    @sx_status = (params[:status].blank? || params[:status].class == Array) ? [0, 1, 2, 3] : params[:status].to_i # 搜索实训的状态
    @keyword   = params[:keyword].blank? ? "u_name" : params[:keyword]        # 根据姓名/实训名搜索
    @search    = params[:search]                                              # 搜索的字
    @tech = params[:tech]
    @shixun_tag_id = params[:shixun_tag]
    @tech_system = MirrorRepository.where(nil).map(&:type_name).reject(&:blank?).sort()
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]       # 排序
    close      = params[:close]                                           # 关闭实训,参数是实训的Id
    unless close.blank?
      Shixun.find(close).update_attributes(:status => 3, :closer_id => User.current.id, :end_time => Time.now)
    end
    if "u_name" == @keyword
      # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user
      if @search.blank?
        @shixuns = Shixun.where(:status => @sx_status).order("created_at #{@sx_order}")
      else
        user_id = User.where("concat(lastname, firstname) like '%#{@search}%'")
        @shixuns = Shixun.where(:user_id => user_id, :status => @sx_status).order("created_at #{@sx_order}")
      end
    else
      if params[:keyword]  == "sx_name"
        @shixuns = Shixun.where("name like '%#{@search}%'").where(:status => @sx_status).order("created_at #{@sx_order}")
      else
        school_id = School.where("name like '%#{@search}%'").map(&:id)
        user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
        @shixuns = Shixun.where(:user_id => user_id).where(:status => @sx_status).order("created_at #{@sx_order}")
      end
    end
    #@shixuns = @shixuns.includes(:mirror_repositories).where("mirror_repositories.name like '%#{@tech}%'") if @tech.present?
    if @tech.present?
      shixuns_id = MirrorRepository.where(:type_name => @tech).first.try(:shixuns)
      @shixuns = @shixuns.where(:id => shixuns_id)
    end

    # shixun_tag_id: -1时 搜索没有技术标签的实训
    if @shixun_tag_id.present?
      if @shixun_tag_id.to_i == -1
        shixuns_id = ShixunTagRepertoire.where(nil).map(&:shixun_id)
        if shixuns_id.present?
          shixuns_id = @shixuns.map(&:id) - shixuns_id
          @shixuns = @shixuns.where(:id => shixuns_id)
        end
      else
        shixuns_id = ShixunTagRepertoire.where(:tag_repertoire_id => @shixun_tag_id).map(&:shixun_id)
        @shixuns = @shixuns.where(:id => shixuns_id)
      end
    end

    if params[:can_copy]
      @shixuns = @shixuns.where(:can_copy => params[:can_copy].to_i)
    end

    if params[:webssh]
      @shixuns = @shixuns.where(:webssh => params[:webssh].to_i)
    end

    if params[:hidden]
      @shixuns = @shixuns.where(:hidden => params[:hidden].to_i)
    end

    if params[:homepage_show]
      @shixuns = @shixuns.where(:homepage_show => params[:homepage_show].to_i)
    end

    if params[:task_pass]
      @shixuns = @shixuns.where(:task_pass => params[:task_pass].to_i)
    end

    if params[:code_hidden]
      @shixuns = @shixuns.where(:code_hidden => params[:code_hidden].to_i)
    end

    @shixun_xls = @shixuns
    @edit_sx_num = Shixun.where(:status => 0).count
    @audit_sx_num = Shixun.where(:status => 1).count
    @publish_sx_num =Shixun.where(:status => 2).count
    @close_sx_num = Shixun.where(:status => 3).count
    @page = (params['page'] || 1).to_i
    @shixuns_count = @shixuns.count
    @limit = 20
    @shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
    @offset ||= @shixuns_pages.offset
    @shixuns = paginateHelper @shixuns, @limit
    @shixun_tags = TagRepertoire.where(nil).order("name asc")
    respond_to do |format|
      format.js
      format.html
      format.xls{
        # @export_shixun_task = @export_shixun_task.all
        filename = "实训详情_#{Time.now}.xls"
        send_data(shixun_list_xls(@shixun_xls), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def update_shixun_task_pass
    shixun = Shixun.find(params[:shixun_id])
    shixun.update_column(:task_pass, !shixun.task_pass)
  end

  def update_shixun_code_hidden
    shixun = Shixun.find(params[:shixun_id])
    shixun.update_column(:code_hidden, !shixun.code_hidden)
  end

  def update_shixun_excute_time
    shixun = Shixun.find(params[:shixun_id])
    shixun.update_column(:excute_time, params[:excute_time].strip == "" ? nil : params[:excute_time].strip)
  end

  def shixun_update_image_text
    image_text = params[:values].strip
    shixun = Shixun.find params[:id]
    shixun.update_column(:image_text, image_text)
    render :json => {success: "true"}
  end

  def build_shixun_and_repertore_relationship
    logger.info("#################{params}")
    tag_id = params[:tag_id].to_i
    shixun_id = params[:shixun_id]
    status = params[:status].to_i
    shixun_tags_count = ShixunTagRepertoire.where(:shixun_id => shixun_id).count
    logger.info("#################{shixun_tags_count}")
    if shixun_tags_count > 3
      render :json => {data: "error"}
    else
      shixun_tags = ShixunTagRepertoire.where(:shixun_id => shixun_id, :tag_repertoire_id => tag_id).first
      if status == 0
        shixun_tags.destroy if shixun_tags.present?
      else
        if shixun_tags.present?
          shixun_tags.update_attribute(:tag_repertoire_id, tag_id)
        else
          ShixunTagRepertoire.create!(:tag_repertoire_id => tag_id, :shixun_id => shixun_id)
        end
      end
      render :json => {data: "success"}
    end
  end

  def update_shixun_hidden
    @shixun = Shixun.find(params[:shixun_id])
    @shixun.update_column(:hidden, !@shixun.hidden)
  end

  # 已发布的实训
  def publish_shixuns
    logger.info("####################{params}")
    @menu_type = 3
    @sub_type = 3
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]    # 排序
    index = params[:index]   # 排序
    @search     = params[:search]                                          # 搜索字
    @keyword    = params[:keyword].blank? ? "u_name" : params[:keyword]    # 根据姓名/实训名搜索
    @tech = params[:tech]
    @beginTime = params[:beginTime]
    @endTime = params[:endTime]
    @tech_system = MirrorRepository.where(nil).map(&:type_name).reject(&:blank?).sort()

    if "u_name" == @keyword
      # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user
      if @search.blank?
        @shixuns = Shixun.where(:status => 2)
        @shixuns = sort_shixun index, @shixuns, @sx_order
      else
        user_id = User.where("concat(lastname, firstname) like '%#{@search}%'")
        @shixuns = Shixun.where(:user_id => user_id, :status => 2)
        @shixuns = sort_shixun index, @shixuns, @sx_order
      end
    else
        @shixuns = Shixun.where("name like '%#{@search}%'").where(:status => 2)
        @shixuns = sort_shixun index, @shixuns, @sx_order
    end
    if params[:homepage_show]
      @shixuns = @shixuns.where(:homepage_show => params[:homepage_show].to_i)
      @shixuns = sort_shixun index, @shixuns, @sx_order
    end
    if params[:tech] && params[:tech] !=''
      @shixuns = @shixuns.where("language like '#{@tech}'")
      @shixuns = sort_shixun index, @shixuns, @sx_order
    end

    if @tech.present?
      shixuns_id = MirrorRepository.where(:type_name => @tech).first.try(:shixuns)
      @shixuns = @shixuns.where(:id => shixuns_id)
    end

    if params[:beginTime].present?
      logger.info("#############------------------")
      endTime = params[:endTime].present? ? params[:endTime] : Time.now
      @shixuns = @shixuns.where("publish_time >= ? and publish_time <= ?", params[:beginTime], endTime)
    end

    if index == '6'
      @op_order = @sx_order
      @sx_order = ""
    else
      @sx_order = @sx_order
      @op_order = ""
    end

    @page = (params['page'] || 1).to_i
    @shixuns_count = @shixuns.count
    @shixun_xls = @shixuns
    @limit = 20
    @shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
    @offset ||= @shixuns_pages.offset
    @shixuns = paginateHelper @shixuns, @limit
    respond_to do |format|
      format.js
      format.html
      format.xls{
        filename = "已发布的实训_#{format_time Time.now}.xls"
        send_data(publish_shixun_list(@shixun_xls), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end
  # 实训首页显示
  def shixun_homepage_show
    if params[:shixun_id]
      shixun = Shixun.find params[:shixun_id]
      shixun.update_attributes(:homepage_show => !shixun.homepage_show)
    end
  end

  # 允许复制
  def shixun_can_copy
    if params[:shixun_id]
      shixun = Shixun.find params[:shixun_id]
      shixun.update_attributes(:can_copy => !shixun.can_copy)
    end
  end

  # 已关闭的实训
  def close_shixuns
    @menu_type = 3
    @sub_type = 4
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]    # 排序
    search     = params[:search]                                          # 搜索字
    keyword    = params[:keyword].blank? ? "u_name" : params[:keyword]    # 根据姓名/实训名搜索
    reopen      = params[:reopen]                                         # 从新开启实训,参数是实训的Id
    tech = params[:tech]
    @tech_system = MirrorRepository.where(nil).map(&:type_name).reject(&:blank?).sort()
    unless reopen.blank?
      Shixun.find(reopen).update_attribute(:status, 2)
    end
    if "u_name" == keyword
      # 如果用户搜索为空,不用遍历user表,直接查找所有实训, 有搜索时才查找user
      if search.blank?
        @shixuns = Shixun.where(:status => 3).order("updated_at #{@sx_order}")
      else
        user_id = User.where("concat(lastname, firstname) like '%#{search}%'")
        @shixuns = Shixun.where(:user_id => user_id, :status => 3).order("updated_at #{@sx_order}")
      end
    else
      @shixuns = Shixun.where("name like '%#{search}%'").where(:status => 3).order("updated_at #{@sx_order}")
    end
    if params[:tech].present?
      shixuns_id = MirrorRepository.where(:type_name => tech).first.try(:shixuns)
      @shixuns = @shixuns.where(:id => shixuns_id)
    end
    @page = (params['page'] || 1).to_i
    @shixuns_count = @shixuns.count
    @limit = 20
    @shixuns_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
    @offset ||= @shixuns_pages.offset
    @shixuns = paginateHelper @shixuns, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 镜像类别图片
  def mirror_picture_shixuns
    @main_mirror = MirrorRepository.where(nil)
    @repertoire = Repertoire.where(nil)
    @menu_type = 3
    @sub_type = 7
    search = params[:search]
    if params[:search] && params[:search] != ''
      @main_mirror = @main_mirror.where("type_name like '%#{search}%'")
    end
    @page = (params['page'] || 1).to_i
    @main_mirror_count = @main_mirror.count
    @limit = 20
    @main_mirror_pages = Paginator.new @main_mirror_count, @limit, params['page'] || 1
    @offset ||= @main_mirror_pages.offset
    @main_mirror = paginateHelper @main_mirror, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  def update_mirror_picture
    if params[:res] == "1"
      mirror = MirrorRepository.where(:id => params[:mirror_id]).first
      MirrorRepository.where(:id => params[:mirror_id]).update_all(:repertoire_id => params[:use_scope], :sub_repertoire_id => nil)
    else
      MirrorRepository.where(:id => params[:mirror_id]).update_all(:sub_repertoire_id => params[:use_scope])
    end
    redirect_to mirror_picture_shixuns_managements_path(:page => params[:page])
  end

  # 实训成员列表
  def shixun_member
    @menu_type = 3
    @sub_type = 6
    @shixun_member = Myshixun.where("0=0").order("created_at desc")
    keyword = params[:keyword]
    search = params[:search]
    member = params[:member]
    if search.blank?
      @shixun_member = @shixun_member
    else
      if "u_name" == keyword
        user_id = User.where("concat(lastname, firstname) like '%#{search}%'")
        @shixun_member = @shixun_member.where(:user_id => user_id)
      elsif keyword == "u_id"
        user_id = User.where("login like '%#{search}%'")
        @shixun_member = @shixun_member.where(:user_id => user_id)
      elsif keyword == "sx_name"
        @shixun_member = @shixun_member.joins(:shixun).where("shixuns.name like '%#{search}%'")
      else
        school_id = School.where("name like '%#{search}%'").blank? ? "(-1)" : "(" + School.where("name like '%#{search}%'").map(&:id).join(",") + ")"
        user_id = UserExtensions.where("school_id in #{school_id}").blank? ? "(-1)" : "(" + UserExtensions.where("school_id in #{school_id}").map(&:user_id).join(",") + ")"
        @shixun_member = @shixun_member.where("user_id in #{user_id}")

      end
    end

    if member && member != ''
      user_id = User.where("concat(lastname, firstname) like '%#{member}%'").blank? ? "(-1)" : "(" + User.where("concat(lastname, firstname) like '%#{member}%'").map(&:id).join(",") + ")"
      @shixun_member = @shixun_member.joins(:shixun).where("shixuns.user_id in #{user_id}")
    end

    @page = (params['page'] || 1).to_i
    @shixun_member_count = @shixun_member.count
    @limit = 20
    @is_remote = true
    @shixun_member_pages = Paginator.new @shixun_member_count, @limit, params['page'] || 1
    @offset ||= @shixun_member_pages.offset
    @shixun_member = paginateHelper @shixun_member, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  def users_trial
    @menu_type = 7
    @sub_type = 2
    @sx_order  = params[:sx_order].blank? ? "desc" : params[:sx_order]
    sql =
        if params[:t].to_i == 1 && params[:e].to_i == 1
          "status = 1 and homepage_teacher = 1 and homepage_engineer = 1"
        elsif params[:t].to_i == 1
          "status = 1 and homepage_teacher = 1"
        elsif params[:e].to_i == 1
          "status = 1 and homepage_engineer = 1"
        else
          "status = 1"
        end
    @users = User.where("#{sql}").includes(:real_name_authentication_apply, :professional_authentication_apply,
                                           user_extensions: [:department, :school]).order("last_login_on #{@sx_order}")
    @has_cer_count = User.where(:status => 1, :certification => 1).count
    @reject_cer_count = User.where(:status => 1, :certification => 2).count
    @deal_cer_count = ApplyAction.where(:status => 0).select("distinct user_id").count

    subquery = UserDayCertification.where("created_at > ?", Time.now.ago(1.days)).select(:user_id).to_sql
    @trial_cer_count = User.where("status = 1 and certification != 1 and id in (#{subquery})").count

    apply_subquery = ApplyAction.where(container_type: "TrialAuthorization").select(:user_id).to_sql
    @nonn_cer_count = User.where("status = 1 and certification = 0 and id not in (#{apply_subquery}) ").count

    @page = (params['page'] || 1).to_i
    @users_count =  @users.count
    @limit = 20
    @users_pages = Paginator.new @users_count, @limit, params['page'] || 1
    @offset ||= @users_pages.offset
    @users = paginateHelper @users, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end


  def user_homepage_show
    user = User.find params[:user_id]
    if params[:homepage] == "homepage_teacher"
      user.update_attributes(:homepage_teacher => !user.homepage_teacher)
    else
      user.update_attributes(:homepage_engineer => !user.homepage_engineer)
    end
  end

  def shixun_sigle_training
    begin
      shixun = Shixun.find(params[:shixun_id])
      shixun.update_column(:sigle_training, !shixun.sigle_training)
      render :json => {:status => 1}
    rescue Exception => e
      logger.error(e.message)
    end
  end

  def import_course_members
    attachments = params[:attachments]
    @status = 0
    member_count = 0
    attachments.each do |attachment|
      attachment = Attachment.find_by_token_only(attachment[1]['token'])
      attachment.container_id = User.current.id
      attachment.container_type = "ImportCourseMember"
      attachment.save
      path = attachment.disk_directory
      name = attachment.disk_filename
      if name.split(".").last == "xls"
        begin
        xls = Roo::Spreadsheet.open("files/#{path}/#{name}",extension: :xls)
        worksheet = xls.sheet(0)
        rows = worksheet.last_row   #最后一行数
        if rows < 2
          @status = 0
          @message = "请按照模板格式导入"
        else
          for row in 2 .. rows
            student_id = worksheet.cell(row, 1)
            student_id = student_id.is_a?(Float) ? student_id.to_i : student_id
            member_role = worksheet.cell(row, 4).to_i
            course_id = worksheet.cell(row, 3)
            group_name = worksheet.cell(row, 5)
            school_id = worksheet.cell(row, 6).is_a?(Float) ? worksheet.cell(row, 6).to_i : worksheet.cell(row, 6)
            if student_id && member_role && [9, 7, 10].include?(member_role) && course_id && school_id
              user = User.find_by_sql("SELECT u.* FROM `users` u, `user_extensions` ue where u.id = ue.user_id and
                      ue.student_id = '#{student_id}' and ue.school_id= #{school_id}").first
              course = Course.where(:id => course_id).first
              # 判断用户和课堂是否都存在,存在则判断该用户是否已是课堂成员,不是则加入课堂
              if user.present? && course.present?
                course_group = CourseGroup.where(:course_id => course.id, :name => group_name).first ||
                    CourseGroup.create(:name => group_name, :course_id => course.id) if group_name

                member = course.members.where(:user_id => user.id).first
                # 如果已是课堂成员且是学生身份and不在指定的分班则移动到该分班
                if member.present? && member.member_roles.pluck(:role_id).include?(10) && member.course_group_id != course_group.try(:id).to_i
                  member.update_column("course_group_id", course_group.try(:id).to_i)
                  member_count += 1
                elsif !member.present?
                  member = Member.new(:role_ids => [member_role], :user_id => user.id)
                  if member_role == 10
                    StudentsForCourse.create(:student_id => user.id, :course_id => course.id)
                  end
                  Tiding.create(:user_id => user.id, :trigger_user_id => course.tea_id, :container_id => course.id, :container_type => 'TeacherJoinCourse',
                                :belong_container_id => course.id, :belong_container_type => "Course", :tiding_type => "System", :extra => member_role)
                  member.course_group_id = course_group.try(:id).to_i
                  course.members << member

                  member_count += 1
                end
              end
            end
          end
          @status = 1
          @message = "已导入/更新#{member_count}个成员"
        end
        rescue
          @status = 0
          @message = "文件内容无法读取"
        end
      else
        @status = 0
        @message = "只支持xls文件的导入"
      end
      attachment.destroy
    end
  end

  def import_student_accounts
    attachments = params[:attachments]
    @status = 0
    attachments.each do |attachment|
      attachment = Attachment.find_by_token_only(attachment[1]['token'])
      attachment.container_id = User.current.id
      attachment.container_type = "ImportStudentAccount"
      attachment.save
      path = attachment.disk_directory
      name = attachment.disk_filename
      if name.split(".").last == "xlsx"
        # lists = readXlsData("files/baolong.xlsx")
        lists = readXlsData("files/#{path}/#{name}")
        school_id = nil
        prefix = ""
        lists.each_with_index do |list, index|
          if list[0]
            # logger.info("#{list[0]}---#{list[1]}---#{list[2]}")
            if index == 0
              school_id = list[0]
            elsif index == 1
              prefix = list[0]
            elsif index != 2 && list[3] && [0, 1, 2].include?(list[3].to_i)
              if list[3].to_i == 1
                user = User.find_by_sql("SELECT u.* FROM `users` u, `user_extensions` ue where u.id = ue.user_id and ue.identity = 1 and ue.student_id = '#{list[0]}' and ue.school_id= #{school_id.to_i}").first
              else
                user = User.find_by_sql("SELECT u.* FROM `users` u, `user_extensions` ue where u.id = ue.user_id and ue.identity = '#{list[3]}' and ue.technical_title = '#{list[4]}' and CONCAT(u.lastname,u.firstname) ='#{list[1]}' and ue.school_id= #{school_id.to_i}").first
              end
              school = School.where(:id => school_id).first
              # 用户不存在则创建账号
              if !user.present? && school.present?
                department = school.departments.where(:name => list[2]).first
                user = User.new
                user.admin = false
                user.activate
                user.login = prefix + list[0]
                user.lastname = list[1]
                user.nickname = list[1]
                user.professional_certification = 1
                user.certification = 1
                user.grade = 0
                user.password = "12345678"
                if user.save
                  ue = UserExtensions.new(:user_id => user.id, :gender => 0, :school_id => school_id, :location => school.province, :location_city => school.city, :identity => list[3], :student_id => list[0], :department_id => department.try(:id))
                  if list[3] && list[3].to_i == 0
                    ue.technical_title = ["教授", "副教授", "讲师", "助教"].include?(list[4]) ? list[4] : "讲师"
                  elsif list[3] && list[3].to_i == 2
                    ue.technical_title = ["企业管理者", "部门管理者", "高级工程师", "工程师", "助理工程师"].include?(list[4]) ? list[4] : "助理工程师"
                  end
                  ue.save
                end
              elsif user.present?
                user.update_column("certification", 1)
              end
            end
          end
        end
        @status = 1
      end
    end
  end

  # 自动授权列表
  def auto_users_trial
    @menu_type = 7
    @sub_type = 3
    # @apply_action = School.where(:auto_users_trial => 1).order('authorization_time desc')
    @apply_action = School.find_by_sql("select s.*, count(ue.user_id) as user_count From schools s left join user_extensions ue on s.id = ue.school_id
                                        where s.auto_users_trial =1 group by s.id order by user_count desc;")

    @auto_school_ids = @apply_action.empty? ? "(-1)" : "(" + @apply_action.map(&:id).join(",") + ")"
    @page = (params['page'] || 1).to_i
    @apply_action_count = @apply_action.count
    @limit = 20
    @is_remote = true
    @apply_action_pages = Paginator.new @apply_action_count, @limit, params['page'] || 1
    @offset ||= @apply_action_pages.offset
    @apply_action = paginateHelper @apply_action, @limit
    respond_to do |format|
      format.html
      format.js
    end
  end

  def search_authorization_school
    school_name = params[:contents]
    @sx_order = params[:order]
    @apply_action = School.authorization.where("name like '%#{school_name}%'").order("authorization_time #{@sx_order}")
    @page = (params['page'] || 1).to_i
    @apply_action_count = @apply_action.count
    @limit = 20
    @is_remote = true
    @apply_action_pages = Paginator.new @apply_action_count, @limit, params['page'] || 1
    @offset ||= @apply_action_pages.offset
    @apply_action = paginateHelper @apply_action, @limit

  end

  # 过关任务模板
  def editmd_template
    @menu_type = 3
    @samples_type = params[:samples_type]
    @samples_type == "taskPass" ? @sub_type = 1 : ( @samples_type == "introduction" ? @sub_type = 2 : @sub_type = 3 )
    @sample = PlatformSample.where(:samples_type => @samples_type).first
    unless params[:template].nil?
      if @sample.nil?
        @sample = PlatformSample.create(:samples_type => @samples_type, :contents => params[:template])
      else
        @sample.update_attribute(:contents, params[:template])
      end
    end
    respond_to do |format|
      format.html
      format.js
    end
  end

  #  新课导语模板
  def course_guide_template
    @menu_type = 12
    @sub_type = 5
    @samples_type = params[:samples_type]
    @sample = PlatformSample.where(:samples_type => @samples_type).first
    if request.post?
      unless params[:platform_sample][:contents].nil?
        if @sample.nil?
          PlatformSample.create(:samples_type => @samples_type, :contents => params[:platform_sample][:contents])
        else
          @sample.update_attribute(:contents, params[:platform_sample][:contents])
        end
      end
    end
    @sample = @sample || PlatformSample.new
    respond_to do |format|
      format.html
    end
  end

  # 实训评分
  def shixun_quality_score
    @menu_type = 12
    @sub_type = 6
    @shixun_scores = ScoreSet.where(nil).order("created_at asc")
    respond_to do |format|
      format.js
      format.html
    end
  end

  def new_score_sets
    name = params[:type_name]
    level = params[:level]
    lower = params[:lower]
    upper = params[:upper]
    ActiveRecord::Base.transaction do
      begin
        score_set = ScoreSet.create!(:name => name)
        level.each_with_index do |l, index|
          ScoreIndicatorQuality.create!(:name => l, :upper_limit => upper[index], :lower_limit => lower[index], :score_set_id => score_set.id, :position => index+1) if l.present?
        end
      rescue Exception => e
        logger.error("new_score_sets failed #{e}")
        raise ActiveRecord::Rollback
      end
    end
    redirect_to shixun_quality_score_managements_path
  end

  def new_score_indicator
    @shixun_scores = ScoreSet.find(params[:score_set_id])
    @score_qualities = @shixun_scores.score_indicator_qualities

  end

  def edit_score_indicator
    @indicator = ScoreIndicator.find(params[:score_indicator_id])
    @shixun_scores = @indicator.score_set
    @score_qualities = @shixun_scores.score_indicator_qualities

  end

  def create_score_indicator
    score_set_id = params[:score_set_id]
    name = params[:name]
    description = params[:description]
    desc_name = params[:description_name]
    scale = params[:scale]
    ActiveRecord::Base.transaction do
      begin
        indicator = ScoreIndicator.create!(:name => name, :score_set_id => score_set_id, :scale => scale, :description => description)
        desc_name.each_with_index do |name, index|
          ScoreQualityDescription.create!(:name => name, :score_indicator_id => indicator.id, :position => index+1)
        end
      rescue Exception => e
        logger.error("create_score_indicator failed #{e}")
        raise ActiveRecord::Rollback
      end
    end
    redirect_to shixun_quality_score_managements_path
  end

  def update_score_indicator
    score_indicator_id = params[:score_indicator_id]
    name = params[:name]
    description = params[:description]
    scale = params[:scale]
    description_name = params[:description_name]
    @indicator = ScoreIndicator.find(score_indicator_id)
    ActiveRecord::Base.transaction do
      begin
        if name != @indicator.name || description != @indicator.description || scale != @indicator.scale
          @indicator.update_attributes(:name => name, :description => description, :scale => scale) if name.present?
        end

        description_name.each_with_index do |name, index|
          des = @indicator.score_quality_descriptions.where(:position => index+1).first
          if name != des.try(:name)
            if des.present?
              des.update_attribute(:name, name)
            else
              ScoreQualityDescription.create!(:name => name, :score_indicator_id => @indicator.id, :position => index+1)
            end
          end
        end
        redirect_to shixun_quality_score_managements_path
      rescue Exception => e
        logger.error("update_score_indicator failed #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  def edit_score_set
    @shixun_score = ScoreSet.find(params[:score_set_id])
    @qualities = @shixun_score.score_indicator_qualities
  end

  def update_score_sets
    score_set_name = params[:type_name]
    qualities_id = params[:quality]
    level = params[:level]
    create_level = params[:create_level]
    lower = params[:lower]
    create_lower = params[:create_lower]
    upper = params[:upper]
    create_upper = params[:create_upper]
    shixun_score = ScoreSet.find(params[:score_set_id])
    quality_id = shixun_score.score_indicator_qualities.map(&:id)
    delete_quality_id = quality_id - qualities_id.map(&:to_i)
    ActiveRecord::Base.transaction do
      begin
        # 更新Score_set
        if shixun_score.name != score_set_name && score_set_name.present?
          shixun_score.update_attribute(:name, score_set_name)
        end

        # 更新score_indicator_quality
        qualities_id.each_with_index do |id, index|
          quality = ScoreIndicatorQuality.find(id)
          quality.update_attributes(:name => level[index],
                                    :lower_limit => lower[index],
                                    :upper_limit => upper[index],
                                    :position => index + 1) if level[index].present?
        end

        # 删除score_indicator_quality
        delete_qualities = ScoreIndicatorQuality.where(:id => delete_quality_id)
        delete_qualities.destroy_all if delete_qualities.present?

        # 创建新增score_indicator_quality
        index_count = qualities_id.size
        create_level.try(:each_with_index) do |name, index|
          ScoreIndicatorQuality.create!(:name => name,
                                        :lower_limit => create_lower[index],
                                        :upper_limit => create_upper[index],
                                        :position => index_count + index + 1, :score_set_id => shixun_score.id) if create_lower[index].present?
        end

        # 删除超出position的score_indicator_descrition
        max_position = shixun_score.score_indicator_qualities.maximum(:position)
        shixun_score.score_indicators.each do |indicator|
          description = ScoreQualityDescription.where("score_indicator_id = ? and position > ?", indicator.id, max_position)
          description.destroy_all if description.present?
        end

        redirect_to shixun_quality_score_managements_path
      rescue Exception => e
        logger.error("update_score_sets failed #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  def delete_score_set
    score_set = ScoreSet.find(params[:score_set_id])
    score_set.destroy
    redirect_to shixun_quality_score_managements_path
  end

  def delete_score_indicator
    indicator = ScoreIndicator.find(params[:score_indicator_id])
    indicator.destroy
    redirect_to shixun_quality_score_managements_path
  end

  # 添加
  def create_auto_users_trial
   school = School.find params[:school]
   school.update_attributes(:auto_users_trial => 1, :authorization_time => Time.now)
   user_exs = UserExtensions.where(:school_id => params[:school])
   day_cer = UserDayCertification.where(:user_id => user_exs.map(&:user_id))
   users = User.where(:id => day_cer.map(&:user_id))
   users.update_all("certification = 1")
   ApplyAction.where(:user_id => users.map(&:id), :container_type => "TrialAuthorization", :status => 0).update_all(:status => 1)
   redirect_to auto_users_trial_managements_path
  end

  # 删除
  def update_auto_users_trial
    School.where(:id => params[:school]).update_all(:auto_users_trial => 0)
    redirect_to auto_users_trial_managements_path
  end

  def search_user
    if params[:member_ids] && params[:trial_whether] == "trial_agree"
      aUser = User.where(:id => params[:member_ids]).includes(:user_extensions)
      aUser.update_all(:certification => 1)
      # 授权的教师加入示例课堂
      aUser.each do |user|
        join_ex_course(user) if user.user_extensions.identity == 0
      end
      apply_user = ApplyAction.where(:user_id => params[:member_ids], :container_type => "TrialAuthorization")
      apply_user.update_all(:status => 1) unless apply_user.blank?
    elsif params[:member_ids] && params[:trial_whether] == "trial_cancel"
      User.where(:id => params[:member_ids]).update_all(:certification => 0)
      apply_user = ApplyAction.where(:user_id => params[:member_ids], :container_type => "TrialAuthorization")
      apply_user.update_all(:status => 2) unless apply_user.blank?
    end

    if params[:member_ids] && params[:occupation] == "occupation_agree"
      User.where(:id => params[:member_ids]).update_all(:professional_certification => true)
      apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 2)
      unless apply_user.blank?
        apply_user.update_all(:status => 1)
      end
    elsif params[:member_ids] && params[:realname] == "realname_agree"
      User.where(:id => params[:member_ids]).update_all(:authentication => true)
      apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 1)
      unless apply_user.blank?
        apply_user.update_all(:status => 1)
      end
    elsif params[:member_ids] && params[:occupation] == "occupation_cancel"
      users = User.where(:id => params[:member_ids])
      users.update_all(:professional_certification => false)
      # 取消了职业认证给用户发消息
      users.each do |user|
        Tiding.create(:user_id => user.id, :trigger_user_id => 0, :container_id => user.id, :container_type =>'CancelUserProCertification', :belong_container_id => user.id, :belong_container_type =>'User', :tiding_type => "System")
      end
      apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 2)
      unless apply_user.blank?
        apply_user.update_all(:status => 2)
      end
    elsif params[:member_ids] && params[:realname] == "realname_cancel"
      users = User.where(:id => params[:member_ids])
      users.update_all(:authentication => false)
      # 取消了实名认证给用户发消息
      users.each do |user|
        Tiding.create(:user_id => user.id, :trigger_user_id => 0, :container_id => user.id, :container_type =>'CancelUserAuthentication', :belong_container_id => user.id, :belong_container_type =>'User', :tiding_type => "System")
      end
      apply_user = ApplyUserAuthentication.where(:user_id => params[:member_ids], :auth_type => 1)
      unless apply_user.blank?
        apply_user.update_all(:status => 2)
      end
    end

    users = User.where(nil)
    if params[:trial] == "-1"
      users = users.where(status: 1, certification: 0)
                .joins('LEFT JOIN apply_actions ON apply_actions.user_id = users.id AND apply_actions.container_type = "TrialAuthorization"')
                .where('apply_actions.user_id IS NULL')
    elsif params[:trial] == "-2"
      users = users.where(status: 1)
    elsif params[:trial] == "0"
      users = users.joins('LEFT JOIN apply_actions ON apply_actions.user_id = users.id').where(apply_actions: { status: 0 })
    elsif params[:trial] == "3"
      users = users.joins('LEFT JOIN user_day_certifications udc ON udc.user_id = users.id')
                .where('users.certification != 1').where('udc.created_at > ?', Time.now.ago(1.days))
    else
      users = users.where(status: 1, certification: params[:trial])
    end

    users = users.joins('LEFT JOIN user_extensions ON user_extensions.user_id = users.id')
              .joins('LEFT JOIN departments ON departments.id = user_extensions.department_id')
              .joins('LEFT JOIN schools ON schools.id = user_extensions.school_id')

    if params[:school].present?
      users = users.where("schools.name LIKE ?", "%#{params[:school]}%")
    end

    if params[:department].present?
      users = users.where("departments.name LIKE ?", "%#{params[:department]}%")
    end

    if params[:identity] == "1" || (params[:identity] == "0" && params[:te_technical_title] == "0") || (params[:identity] == "2" && params[:pro_technical_title] == "0")
      users = users.where(user_extensions: { identity: params[:identity] })
    elsif (params[:identity] == "0" && params[:te_technical_title] != "0") || (params[:identity] == "2" && params[:pro_technical_title] != "0")
      technical_title = params[:identity] == "0" ? params[:te_technical_title] : params[:pro_technical_title]
      users = users.where(user_extensions: { identity: params[:identity], technical_title: technical_title })
    end

    if params[:student_id].present?
      users = users.where('user_extensions.student_id like ?', "%#{params[:student_id]}%")
    end

    if params[:research_contents].present?
      keyword = "%#{params[:research_contents]}%"
      if params[:research_condition] == "name"
        users = users.where('concat(lastname, firstname) like ?', keyword)
      elsif params[:research_condition] == "email"
        users = users.where("mail like ?", keyword)
      elsif params[:research_condition] == "phone"
        users = users.where("phone like ?", keyword)
      elsif params[:research_condition] == "nickname"
        users = users.where("nickname like ?", keyword)
      elsif params[:research_condition] == "login"
        users = users.where("login like ?", keyword)
      end
    end

    if params[:province].present?
      users = users.where(schools: { province: params[:province] })
    end

    users = users.select('distinct users.*').order("last_login_on desc")

    @page = (params['page'] || 1).to_i
    @users_count = users.count
    @limit = 20
    @is_remote = true
    @users_pages = Paginator.new @users_count, @limit, params['page'] || 1
    @offset ||= @users_pages.offset
    @users = paginateHelper users.preload(:real_name_authentication_apply, :professional_authentication_apply,
                                           user_extensions: [:department, :school]), @limit

    respond_to do |format|
      format.js
      format.xls{
        # @export_shixun_task = @export_shixun_task.all
        @xls_users = users.reorder("created_on desc").limit(3000) #导出excel用户
        @xls_users = @xls_users.includes(:real_name_authentication_apply, :professional_authentication_apply,
                             user_extensions: [:department, :school])
        filename = "用户列表.xls"
        send_data(user_list_xls(@xls_users), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end
  end

  def update_webssh
    webssh = params[:status] == "true" ? true : false
    @shixuns = Shixun.find(params[:shixun_id])
    @shixuns.update_column(:webssh, webssh)
    respond_to do |format|
      format.js
    end
  end

  def affirm_cancel_auth
    user_id = params[:users]
  end

  # 升级通知
  def update_notice
    @menu_type = 12
    @sub_type = 8
    @notice = SystemUpdateNotice.last
  end

  def edit_update_notice
    notice = SystemUpdateNotice.last
    if notice.present? && notice.end_time > Time.now
      notice.update_attributes(:end_time => params[:end_time], :start_time => params[:start_time], :subject => params[:subject], :notes => params[:notes])
      UserSystemNotice.where(:notice_type => notice.notice_type).destroy_all
    else
      notice_type = UserSystemNotice.find_by_sql("select max(notice_type) as max_notice_type from user_system_notices").first.try(:max_notice_type).to_i + 1
      SystemUpdateNotice.create(:end_time => params[:end_time], :start_time => params[:start_time], :subject => params[:subject], :notes => params[:notes], :notice_type => notice_type)
    end
    redirect_to update_notice_managements_path
  end

  def trial_authorization
    @menu_type =10
    @sub_type = 2
    name_search = params[:search]
    @status = trial_authorization_status(params[:status])
    # @status = (params[:status].blank? || params[:status] == "0") ? 0 : [1,2]
    user_id = []
    search = false
    @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => @status)

    unless name_search.blank?
      new_user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{name_search}%'").map(&:id)
      user_id = user_id.size == 0 ? new_user_id : user_id & new_user_id
      search = true
    end

    if params[:sname] && params[:sname].strip != ''
      school_id =  School.where("name like '%#{params[:sname]}%'")
      new_user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
      user_id = user_id.size == 0 ? new_user_id : user_id & new_user_id
      search = true
    end

    if params[:identity] && params[:identity].to_i != -1
      new_user_id = UserExtensions.where(:identity => params[:identity].to_i).map(&:user_id)
      user_id = user_id.size == 0 ? new_user_id : user_id & new_user_id
      search = true
    end

    if params[:auto_school] && params[:auto_school].to_i != 0
      school_id = School.where(auto_users_trial: params[:auto_school].to_i == 1 ? 1 : 0)
      new_user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
      user_id = user_id.size == 0 ? new_user_id : user_id & new_user_id
      search = true
    end

    @authorizations = user_id.size == 0 && !search ? @authorizations.order("updated_at desc") : @authorizations.where(:user_id => user_id.uniq).order("updated_at desc")

    @autu_count = @authorizations.count
    @limit = 15
    @is_remote = true
    @autu_pages = Paginator.new @autu_count, @limit, params['page'] || 1
    @offset ||= @autu_pages.offset
    @authorizations = paginateHelper @authorizations, @limit

    @authorizations = @authorizations.includes(:user)
    respond_to do |format|
      format.js
      format.html
    end


  end

  # 批量授权
  def batch_authorization

  end

  # params[:type] 1:拒绝 0:同意
  # authentication 会有一个初始值,不同的值代表不同的权限
  # REDO: 后面权限改了后,一并要改
  def trial_authorization_operation
    logger.warn("####trial_authorization_operation: #{format_time(Time.now)}")
    apply_action = ApplyAction.find(params[:apply_id])
    type = params[:type]
    search = params[:search]
    if type == "0"
      authentication_user = AuthenticationsUsers.where(user_id: apply_action.user_id).first
      if authentication_user.blank?
        AuthenticationsUsers.create(:user_id => apply_action.user_id, :authentication_id => 1)
      end
      begin
        logger.warn("trial_authorization_operation begin send: #{format_time(format_time(Time.now))}")
        # verification_code = code.sample(6).join
        if apply_action.user.phone.present?
          status = Trustie::Sms.send(mobile: apply_action.user.phone.to_s, code: '1', send_type:'trial_authorization', user_name:apply_action.user.show_name, result:'已通过')
        end
        logger.warn("trial_authorization_operation complete send: #{format_time(Time.now)}")
      rescue => e
        Rails.logger.error "发送验证码出错: #{e}"
      end
      # 授权的教师加入示例课堂
      join_ex_course(apply_action.user) if apply_action.user.user_extensions.identity == 0
      logger.warn("####trial_authorization_operation teacher joined: #{format_time(Time.now)}")
    else
      begin
        # verification_code = code.sample(6).join
        if apply_action.user.phone.present?
          status = Trustie::Sms.send(mobile: apply_action.user.phone.to_s, code: '1', send_type:'trial_authorization', user_name:apply_action.user.show_name, result:'未通过')
        end
      rescue => e
        Rails.logger.error "发送验证码出错: #{e}"
      end
    end
    Tiding.where(:user_id => 1, :trigger_user_id => apply_action.user_id, :container_id => apply_action.id, :container_type => 'ApplyAction', :tiding_type => "Apply", :status => 0).update_all(:status => 1)
    Tiding.create(:user_id => apply_action.user_id, :trigger_user_id => 0, :container_id => apply_action.id, :container_type => 'ApplyAction',
                  :parent_container_id => apply_action.container_id, :parent_container_type => apply_action.container_type, :belong_container_id => apply_action.container_id, :belong_container_type => "User", :tiding_type => "System", :status => type == "0" ? 1 : 2)

    reject_reason = Array(params[:reasons]).join(';')
    apply_action.update_attributes(status: (params[:type] == "1" ? 2 : 1), reason: reject_reason, reject_description: params[:reject_description], dealer_id: User.current.id, noticed: false)

    User.where(:id => apply_action.user_id).first.update_attributes(:certification => (params[:type] == "1" ? 2 : 1))

    if params[:reject_type] != "revocation"
      user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{search}%'")
      @authorizations = ApplyAction.where(:container_type => "TrialAuthorization", :status => 0, :user_id => user_id).includes(:user)
      @autu_count = @authorizations.count
      @limit = 15
      @is_remote = true
      @autu_pages = Paginator.new @autu_count, @limit, params['page'] || 1
      @offset ||= @autu_pages.offset
      @authorizations = paginateHelper @authorizations, @limit
    end
    respond_to do |format|
      format.js
    end
  end

  def index

  end

  # copy from admin
  def identity_authentication
    @menu_type = 10
    @sub_type = 1
    @type = trial_authorization_status(params[:type])
    type = params[:type] || 0 # 存在type 就用type 没有就为 0
    user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{params[:name]}%'")
    @unapproved_user = ApplyUserAuthentication.where(:status => @type, :user_id => user_id, :auth_type => 1).order("updated_at desc")
    if params[:sname] && params[:sname] != ''
      school_id =  School.where("name like '%#{params[:sname]}%'")
      user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
      @unapproved_user = @unapproved_user.where(:user_id => user_id).order("updated_at desc")
    end

    @unapproved_user_count = @unapproved_user.count
    @limit = 15
    @is_remote = true
    @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
    @offset ||= @unapproved_user_pages.offset
    @unapproved_user = paginateHelper @unapproved_user, @limit
    respond_to do |format|
      format.html
      format.js
    end
  end

  def professional_authentication
    @menu_type = 10
    @sub_type = 7
    @type = trial_authorization_status(params[:type])
    type = params[:type] || 0 # 存在type 就用type 没有就为 0
    user_id = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{params[:name]}%'")
    # @unapproved_user = ApplyUserAuthentication.where(:status => @type, :user_id => user_id, :auth_type => 2).find_by_sql("SELECT s.*, TIMESTAMPDIFF(SECOND, s.updated_at, now()) diff FROM `apply_user_authentications` s order by diff asc")
    @unapproved_user = ApplyUserAuthentication.where(:status => @type, :user_id => user_id, :auth_type => 2)
    if params[:sname] && params[:sname] != ''
      school_id =  School.where("name like '%#{params[:sname]}%'")
      user_id = UserExtensions.where(:school_id => school_id).map(&:user_id)
      @unapproved_user = @unapproved_user.where(:user_id => user_id)
    end

    if params[:identity] && params[:identity] != "" && params[:identity] != "-1"
      user_id = UserExtensions.where(:identity => params[:identity]).map(&:user_id)
      @unapproved_user = @unapproved_user.where(:user_id => user_id)
    end
    @unapproved_user = @unapproved_user.order("updated_at desc")
    @unapproved_user_count = @unapproved_user.count
    @limit = 15
    @is_remote = true
    @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
    @offset ||= @unapproved_user_pages.offset
    @unapproved_user = paginateHelper @unapproved_user, @limit
    respond_to do |format|
      format.html
      format.js
    end
  end

  # 拒绝身份认证
  # copy from admin
  def reject_authentication
    apply_user = ApplyUserAuthentication.where(:id => params[:apply_id], :auth_type => 1).first
    reason = apply_user.update_attributes(:status => 2, :remarks => params[:reject_reason])
=begin
    begin
      if apply_user.user.phone.present?
        status = Trustie::Sms.send(mobile: apply_user.user.phone.to_s, code: '1', send_type:'authentication',user_name:apply_user.user.show_name, result:'未通过')
      end
    rescue => e
      Rails.logger.error "发送验证码出错: #{e}"
    end
=end
    diskfile1 = disk_filename("UserAuthentication", apply_user.user_id) +"ID"
    apply_user.update_attributes(:is_delete => true)
    File.delete(diskfile1)

    apply_user.tidings.where(:tiding_type => "Apply").update_all(:status => 1)
    Tiding.create(:user_id => apply_user.user_id ,:trigger_user_id => 0, :container_id => apply_user.id, :container_type => "ApplyUserAuthentication", :belong_container_id => apply_user.user_id, :belong_container_type =>'User', :status => 2, :tiding_type => "System")
    render :json => {success: reason}
  end

  # 同意身份认证
  # copy from admin
  def agree_authentication
    apply_user = ApplyUserAuthentication.where(:id => params[:apply_id], :auth_type => 1).first
    user = User.find(apply_user.user_id)
    apply_user.update_attribute(:status, 1)
    user.update_attribute(:authentication, true)
    grade_record = Grade.where(:container_id => user.id, :container_type => "Authentication").first
    unless grade_record
      user.update_attribute(:grade, user.grade + 500)
      Grade.create(:user_id => user.id, :container_id => user.id, :container_type => "Authentication", :score => 500)
    end

    diskfile1 = disk_filename("UserAuthentication", apply_user.user_id) +"ID"
    apply_user.update_attributes(:is_delete => true)
    File.delete(diskfile1)

=begin
    begin
      if apply_user.user.phone.present?
        status = Trustie::Sms.send(mobile: apply_user.user.phone.to_s, code: '1', send_type:'authentication',user_name:apply_user.user.show_name, result:'已通过')
      end
    rescue => e
      Rails.logger.error "发送验证码出错: #{e}"
    end
=end

    apply_user.tidings.where(:tiding_type => "Apply").update_all(:status => 1)
    Tiding.create(:user_id => apply_user.user_id ,:trigger_user_id => 0, :container_id => apply_user.id, :container_type => "ApplyUserAuthentication", :belong_container_id => apply_user.user_id, :belong_container_type =>'User', :status => 1, :tiding_type => "System")

    @unapproved_user = ApplyUserAuthentication.where(:status => 0, :auth_type => 1).order("updated_at desc")
    @unapproved_user_count = @unapproved_user.count
    @limit = 15
    @is_remote = true
    @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
    @offset ||= @unapproved_user_pages.offset
    @unapproved_user = paginateHelper @unapproved_user, @limit
    respond_to do |format|
      format.js
    end
  end

  # 拒绝职业认证
  def reject_authentication_pro
    apply_user = ApplyUserAuthentication.where(:id => params[:apply_id], :auth_type => 2).first
    if apply_user.present? && apply_user.status == 0
      reason = apply_user.update_attributes(:status => 2, :remarks => params[:reject_reason])
      diskfile1 = disk_filename("UserAuthentication", apply_user.user_id) +"PRO"
      apply_user.update_attributes(:is_delete => true)
      File.delete(diskfile1)
=begin
      begin
        if apply_user.user.phone.present?
          status = Trustie::Sms.send(mobile: apply_user.user.phone.to_s, code: '1', send_type:'authentication_pro',user_name:apply_user.user.show_name, result:'未通过')
        end
      rescue => e
        Rails.logger.error "发送验证码出错: #{e}"
      end
=end
      apply_user.tidings.where(:tiding_type => "Apply").update_all(:status => 1)
      Tiding.create(:user_id => apply_user.user_id ,:trigger_user_id => 0, :container_id => apply_user.id, :container_type => "ApplyUserAuthentication", :belong_container_id => apply_user.user_id, :belong_container_type =>'User', :status => 2, :tiding_type => "System")

      render :json => {success: reason}
    end
  end

  # 同意职业认证
  def agree_authentication_pro
    apply_user = ApplyUserAuthentication.where(:id => params[:apply_id], :auth_type => 2).first
    user = User.find(apply_user.user_id)
    apply_user.update_attribute(:status, 1)
    user.update_attribute(:professional_certification, true)
    grade_record = Grade.where(:container_id => user.id, :container_type => "Professional").first
    unless grade_record
      user.update_attribute(:grade, user.grade + 500)
      Grade.create(:user_id => user.id, :container_id => user.id, :container_type => "Professional", :score => 500)
    end

    diskfile1 = disk_filename("UserAuthentication", apply_user.user_id) +"PRO"
    apply_user.update_attributes(:is_delete => true)
    File.delete(diskfile1)

=begin
    begin
      if apply_user.user.phone.present?
        status = Trustie::Sms.send(mobile: apply_user.user.phone.to_s, code: '1', send_type:'authentication_pro',user_name:apply_user.user.show_name, result:'已通过')
      end
    rescue => e
      Rails.logger.error "发送验证码出错: #{e}"
    end
=end
    apply_user.tidings.where(:tiding_type => "Apply").update_all(:status => 1)
    Tiding.create(:user_id => apply_user.user_id ,:trigger_user_id => 0, :container_id => apply_user.id, :container_type => "ApplyUserAuthentication", :belong_container_id => apply_user.user_id, :belong_container_type =>'User', :status => 1, :tiding_type => "System")

    @unapproved_user = ApplyUserAuthentication.where(:status => 0, :auth_type => 2).order("updated_at desc")
    @unapproved_user_count = @unapproved_user.count
    @limit = 15
    @is_remote = true
    @unapproved_user_pages = Paginator.new @unapproved_user_count, @limit, params['page'] || 1
    @offset ||= @unapproved_user_pages.offset
    @unapproved_user = paginateHelper @unapproved_user, @limit
    respond_to do |format|
      format.js
    end
  end

  def subject_authorization
    @menu_type = 10
    @sub_type = 6
    @type = trial_authorization_status params[:type]
    @authorizations = ApplyAction.where(:container_type => "ApplySubject", :status => @type).order("created_at desc")
    # @subject=Subject.all

    @authorizations_count = @authorizations.count
    @limit = 15
    @is_remote = true
    @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1
    @offset ||= @authorizations_pages.offset
    @authorizations = paginateHelper @authorizations, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  def shixun_authorization
    @menu_type = 10
    @sub_type =  5
    @type = trial_authorization_status params[:type]
    # sql = select * from apply_actions where dealer_id is null
    @authorizations = ApplyAction.where(:container_type => "ApplyShixun", :status => @type).order("created_at desc")
    search = params[:search]
    unless search.blank?
      @authorizations = @authorizations.where(:container_id => Shixun.where(:id => @authorizations.map(&:container_id)).where("name like '%#{search}%'").map(&:id)).order("created_at desc")
    end

    @authorizations_count = @authorizations.count
    @limit = 15
    @is_remote = true
    @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1
    @offset ||= @authorizations_pages.offset
    @authorizations = paginateHelper @authorizations, @limit
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 课程实训发布审批
  def deal_subject_authorization
    apply_action = ApplyAction.find(params[:apply_id])
    type = params[:type].to_i
    subject = Subject.find apply_action.container_id
    if type == 0   #拒绝
      subject.update_column('status', 0)
      apply_action.update_attributes(:status => 2, :reason => params[:reject_reason], :dealer_id => User.current.id)
      # notes = "您所在团队提交的课程实训发布申请:<a href='#{subject_path(subject)}'>#{subject.name}</a>,审核未通过。<br/>原因:#{params[:reject_reason]}"
      #   JournalsForMessage.create(:jour_id => subject.user_id, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
=begin
      begin
        # verification_code = code.sample(6).join
        if subject.owner.phone.present?
          status = Trustie::Sms.send(mobile: subject.owner.phone.to_s, code: '1', send_type:'subject_authorization', name:subject.name, user_name:subject.owner.show_name, result:'未通过')
        end
      rescue => e
        Rails.logger.error "发送验证码出错: #{e}"
      end
=end

    else   #同意
      subject.update_attributes(:status =>2, :publish_time => Time.now)
      apply_action.update_attributes(:status => 1, :dealer_id => User.current.id)
=begin
      begin
        unless subject.owner.phone.present?
          status = Trustie::Sms.send(mobile: subject.owner.phone.to_s, code: '1', send_type:'subject_authorization', name:subject.name, user_name:subject.owner.show_name, result:'已通过')
        end
      rescue => e
        Rails.logger.error "发送验证码出错: #{e}"
      end
=end
    end
    Tiding.where(:user_id => 1 ,:trigger_user_id => apply_action.user_id, :container_id => apply_action.id, :container_type => 'ApplyAction', :tiding_type => "Apply", :status => 0).update_all(:status => 1)
    Tiding.create(:user_id => apply_action.user_id, :trigger_user_id => 0, :container_id => apply_action.id, :container_type => 'ApplyAction',
                  :parent_container_id => apply_action.container_id, :parent_container_type => apply_action.container_type, :belong_container_id => apply_action.container_id, :belong_container_type => "Subject", :tiding_type => "System", :status => type == 0 ? 2 : 1)

    @authorizations = ApplyAction.where(:container_type => "ApplySubject", :status => 0)
    @authorizations_count = @authorizations.count
    @limit = 15
    @is_remote = true
    @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1
    @offset ||= @authorizations_pages.offset
    @authorizations = paginateHelper @authorizations, @limit
    respond_to do |format|
      format.js
    end
  end

  # 项目实训发布审批
  def deal_shixun_authorization
    apply_action = ApplyAction.find(params[:apply_id])
    type = params[:type].to_i
    shixun = Shixun.find apply_action.container_id
    shixun_creator =  shixun.owner
    if type == 0   #拒绝
      shixun.update_column('status', 0)
      apply_action.update_attributes(:status => 2, :reason => params[:reject_reason], :dealer_id => User.current.id)
=begin
      begin
        if shixun_creator.phone.present?
          status = Trustie::Sms.send(mobile: shixun_creator.phone.to_s, code: '1', send_type:'shixun_authorization', name:shixun.name, user_name:shixun_creator.show_name, result:'未通过')
        end
      rescue => e
        Rails.logger.error "发送验证码出错: #{e}"
      end
=end

    else   #同意
      # 给实训制作者奖励“金币/经验” (奖励数额:实训关卡的金币的总数)
      score = shixun.all_score
      grade = Grade.where(:user_id => shixun.user_id, :container_id => shixun.id, :container_type => "shixunPublish").first
      if grade.blank? # 防止多条创建
        Grade.create(:user_id => shixun.user_id, :container_id => shixun.id, :container_type => "shixunPublish", :score => score)
        Experience.create(:user_id => shixun.user_id, :container_id => shixun.id, :container_type => "shixunPublish", :score => score)
        shixun_creator.update_attributes(:grade => shixun_creator.grade + score, :experience => shixun_creator.experience + score)
      end

      shixun.update_column('status', 2)
      apply_action.update_attributes(:status => 1, :dealer_id => User.current.id)
      shixun = Shixun.where(:id => apply_action.container_id).first
      shixun.update_attribute(:publish_time, Time.now)
      # 实训通关则给实训制作者相应的金币奖励

      shixun_modify_status_without_publish shixun, 1
=begin
      begin
        if shixun_creator.phone.present?
          status = Trustie::Sms.send(mobile: shixun.owner.phone.to_s, code: '1', send_type:'shixun_authorization', name:shixun.name, user_name:shixun.owner.show_name, result:'已通过')
        end
      rescue => e
        Rails.logger.error "发送验证码出错: #{e}"
      end
=end
    end
    Tiding.where(:user_id => 1 ,:trigger_user_id => apply_action.user_id, :container_id => apply_action.id, :container_type => 'ApplyAction', :tiding_type => "Apply", :status => 0).update_all(:status => 1)
    Tiding.create(:user_id => apply_action.user_id, :trigger_user_id => 0, :container_id => apply_action.id, :container_type => 'ApplyAction',
                  :parent_container_id => apply_action.container_id, :parent_container_type => apply_action.container_type, :belong_container_id => apply_action.container_id, :belong_container_type => "Shixun", :tiding_type => "System", :status => type == 0 ? 2 : 1)


    @authorizations = ApplyAction.where(:container_type => "ApplyShixun", :status => 0)
    @authorizations_count = @authorizations.count
    @limit = 15
    @is_remote = true
    @authorizations_pages = Paginator.new @authorizations_count, @limit, params['page'] || 1
    @offset ||= @authorizations_pages.offset
    @authorizations = paginateHelper @authorizations, @limit
    respond_to do |format|
      format.js
    end
  end

  def tech_system
    @menu_type = 12
    @sub_type = 5
    @tech_system = Repertoire.where(nil).order("updated_at asc")
    respond_to do |format|
      format.js
      format.html
    end
  end

  # 创建体系
  def create_system
    rep_name = params[:repertoire]
    sub_rep_name = params[:sub_repertoire]
    tags_name = params[:tag_repertoire]
    ActiveRecord::Base.transaction do
      begin
        rep = Repertoire.create!(:name => rep_name)
        sub_rep = SubRepertoire.create!(:name => sub_rep_name, :repertoire_id => rep.id)
        tags_name.each do |tag|
          TagRepertoire.create!(:name => tag, :sub_repertoire_id => sub_rep.id)
        end
        redirect_to tech_system_managements_path
      rescue Exception => e
        logger.error("create_system error: #{e}")
        raise ActiveRecord::Rollback
      end
    end
  end

  # 更新tag_repertores的名称
  def update_tag_name
    tag = TagRepertoire.find(params[:id])
    if params[:name].blank?
      tag.destroy
    else
      if tag.name == params[:name].strip
        tag.update_column(:updated_at, Time.now)
      else
        tag.update_attribute(:name, params[:name])
      end
    end
    render :json => {success: "true"}
  end

  # 更新sub_repertores的名称
  def update_sub_name
    sub = SubRepertoire.find(params[:id])
    if params[:name].blank?
      sub.destroy
    else
      if sub.name == params[:name].strip
        sub.update_column(:updated_at, Time.now)
      else
        sub.update_attribute(:name, params[:name])
      end
    end
    render :json => {success: "true"}
  end

  def update_rep_name
    rep = Repertoire.find(params[:id])
    if params[:name].blank?
      rep.destroy
    else
      if rep.name == params[:name].strip
        rep.update_column(:updated_at, Time.now)
      else
        rep.update_attribute(:name, params[:name])
      end
    end
    render :json => {success: "true"}
  end

  # type: 1表示新建sub_repertoire, 2表示新建tag_repertoire
  def create_sub_or_tag_repertoire
    type = params[:type].to_i
    if type == 1
      SubRepertoire.create(:name => params[:name], :repertoire_id => params[:id])
    elsif type == 2
      TagRepertoire.create(:name =>params[:name], :sub_repertoire_id => params[:id])
    end
    respond_to do |format|
      format.js{redirect_to tech_system_managements_path}
    end
  end

  def delete_sub_tech_system
    sub_tech = SubRepertoire.where(:id => params[:sub_res]).first
    tech = Repertoire.where(:id => params[:sub_res]).first
    if sub_tech.present?
      sub_tech.destroy
    else
      tech.destroy
    end
    redirect_to tech_system_managements_path
  end

  def create_tech_system
    if params[:index] == "1"
      Repertoire.create(:name => params[:res_tech])
    else
      SubRepertoire.create(:name => params[:sub_tech], :repertoire_id => params[:tech])
    end
    redirect_to tech_system_managements_path
  end

  def rename_tech_system
    @sub_res = SubRepertoire.where(:id => params[:sub_res]).present? ? SubRepertoire.where(:id => params[:sub_res]).first : "0"
    @res = Repertoire.where(:id => params[:res]).first
    respond_to do |format|
      format.js
    end
  end

  def update_tech_system
    if params[:sub_tech] == "0"
      Repertoire.where(:id => params[:res]).update_all(:name => params[:update_res])
    else
      Repertoire.where(:id => params[:res]).update_all(:name => params[:update_res])
      SubRepertoire.where(:id => params[:sub_res]).update_all(:name => params[:update_sub_res])
    end
    redirect_to tech_system_managements_path
  end

  def setting_banner
    @images = PortalImage.order("position asc")
    respond_to do |format|
      format.js
      format.html
    end
  end

  def create_portal_image
    PortalImage.create(:name => params[:name], :position => params[:position], :link => params[:link])
    redirect_to setting_banner_managements_path
  end

  def create_school_image
    @school = School.find params[:school_id]
    SchoolImage.create(:name => params[:name], :position => params[:position], :link => params[:link], :school_id => params[:school_id])
  end

  def update_school_image
    image = SchoolImage.find params[:id]
    image.update_attributes(:name => params[:name], :position => params[:position], :link => params[:link])
    @school = image.school
  end

  def up_or_down_image
    image = PortalImage.find params[:id]
    image.update_attribute(:status, params[:status])
    redirect_to setting_banner_managements_path
  end

  def up_or_down_school_image
    image = SchoolImage.find params[:id]
    image.update_attribute(:status, params[:status])
    @school = image.school
  end


  def update_portal_image
    image = PortalImage.find params[:id]
    image.update_attributes(:name => params[:name], :position => params[:position], :link => params[:link])
    redirect_to setting_banner_managements_path
  end

  def delete_portal_image
    image = PortalImage.find params[:id]
    image.destroy
    redirect_to setting_banner_managements_path
  end

  def delete_school_image
    image = SchoolImage.find params[:id]
    @school = image.school
    image.destroy
  end

  # 课程删除
  before_filter :find_courselist, :only => [:destroy]

  # 课程列表的删除
  def destroy
    if @courselist
      CourseList.where(:id => @courselist.id).destroy_all
      respond_to do |format|
        format.js
      end
    end
  end
  private
  # Find courselist of id params[:id]
  def find_courselist
    @courselist = CourseList.find_by_id(params[:id])
    render_404 if @courselist.nil?
  rescue ActiveRecord::RecordNotFound
    render_404
  end

  def shixun_list_xls shixuns
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "sheet"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["实训ID","实训名称","技术平台", "Fork源", "实践任务","选择题任务","挑战人数", "通关人数", "状态","创建者", "单位", "职业",  "关卡序号","关卡名称","技能标签"])
    count_row = 1
    shixuns.find_each do |shixun|
      sheet1[count_row, 0] = shixun.identifier
      sheet1[count_row, 1] = shixun.name
      sheet1[count_row, 2] = shixun.shixun_main_name
      sheet1[count_row, 3] = shixun.fork_identifier
      sheet1[count_row, 4] = shixun.challenges.practice_type.count
      sheet1[count_row, 5] = shixun.challenges.choose_type.count
      sheet1[count_row, 6] = shixun.myshixuns.count
      sheet1[count_row, 7] = shixun.myshixuns.finished.count
      sheet1[count_row, 8] = shixun.shixun_status
      sheet1[count_row, 9] = shixun.owner.show_real_name
      sheet1[count_row, 10] = shixun.owner.school_name
      sheet1[count_row, 11] = shixun.owner.identity
      shixun.challenges.each do |challenge|
        sheet1[count_row, 12] = "第#{challenge.position}关"
        sheet1[count_row, 13] = challenge.subject
        sheet1[count_row, 14] = challenge.tags_show
        count_row += 1
      end
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def publish_shixun_list shixuns
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "sheet"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["序号","创建者","发布时间", "ID", "实训名称","技术平台","fork源", "实践任务", "实训链接"])
    count_row = 1
    shixuns.find_each do |shixun|
      sheet1[count_row, 0] = count_row
      sheet1[count_row, 1] = shixun.owner.try(:show_real_name)
      sheet1[count_row, 2] = format_time shixun.publish_time
      sheet1[count_row, 3] = shixun.identifier
      sheet1[count_row, 4] = shixun.name
      sheet1[count_row, 5] = show_shixun_mirror(shixun)
      sheet1[count_row, 6] = shixun.fork_identifier
      sheet1[count_row, 7] = shixun.challenges.count
      sheet1[count_row, 8] = Setting.server_url + shixun_path(shixun)
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def training_2018_xls trainings
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "sheet"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["姓名", "手机号","邮箱","单位名称", "职位","专业", "学号", '授课/研究领域', "支付方式","支付状态","支付时间", "发票类型", "发票抬头","税务登记号", "发票内容", "备注", "微信支付单号", "报名时间"])
    count_row = 1
    trainings.find_each do |t|
      sheet1[count_row, 0] = t.name
      sheet1[count_row, 1] = t.phone
      sheet1[count_row, 2] = t.email
      sheet1[count_row, 3] = t.school
      sheet1[count_row, 4] = t.position
      sheet1[count_row, 5] = t.major
      sheet1[count_row, 6] = t.student_id
      sheet1[count_row, 7] = t.research_field
      sheet1[count_row, 8] = t.training_payinfo.try(:pay_type_str)
      sheet1[count_row, 9] = t.training_payinfo.try(:pay_status_str)
      sheet1[count_row, 10] = format_time t.training_payinfo.try(:pay_time)
      sheet1[count_row, 11] = t.training_payinfo.try(:invoice_title).present? ? '需要' : '不需要'
      sheet1[count_row, 12] = t.training_payinfo.try(:invoice_title)
      sheet1[count_row, 13] = t.training_payinfo.try(:invoice_no)
      sheet1[count_row, 14] = t.training_payinfo.try(:invoice_content)
      sheet1[count_row, 15] = t.training_payinfo.try(:info)
      sheet1[count_row, 16] = t.training_payinfo.try(:out_trade_no)
      sheet1[count_row, 17] = format_time t.created_at
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def user_list_xls users
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "users"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["用户姓名","性别","职业","职称","地区","	单位","子单位","注册时间","最后登录时间","授权", "邮箱"])
    count_row = 1
    users.each do |user|
      sheet1[count_row,0] = user.try(:show_real_name)
      sheet1[count_row,1] = user.sex
      sheet1[count_row,2] = user.user_extensions.try(:show_identity)
      sheet1[count_row,3] = user.job_title
      sheet1[count_row,4] = user.region_name
      sheet1[count_row,5] = user.user_extensions.try(:school).try(:name)
      sheet1[count_row,6] = user.user_extensions.try(:department).try(:name)
      sheet1[count_row,7] = format_time user.created_on
      sheet1[count_row,8] = format_time user.last_login_on
      sheet1[count_row,9] = user.trial_authorization
      sheet1[count_row,10] = user.mail
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def course_list_xls courses
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "course"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["ID","课堂名称","成员","资源","普通作业","	实训作业","试卷","评测次数", "私有","状态","创建者单位","创建者","动态时间","创建时间"])
    count_row = 1
    courses.each do |course|
      school = course.teacher.try(:user_extensions).try(:school).try(:name).blank? ? "--" : course.teacher.school_name
      teacher_name = course.teacher ? course.teacher.show_real_name : ""
      sheet1[count_row,0] = course.id
      sheet1[count_row,1] = course.name
      sheet1[count_row,2] = course.members.count
      sheet1[count_row,3] = course.attachments.count
      sheet1[count_row,4] = course.homework_commons.where(:homework_type => 1).count
      sheet1[count_row,5] = course.homework_commons.where(:homework_type => 4).count
      sheet1[count_row,6] = course.exercises.count
      sheet1[count_row,7] = course.evaluate_count
      sheet1[count_row,8] = course.is_public.to_i == 1 ? '否' : '是'
      sheet1[count_row,9] = course.is_end ? "已结束" : "正在进行"
      sheet1[count_row,10] = school
      sheet1[count_row,11] = teacher_name
      sheet1[count_row,12] = format_time(course.updatetime)
      sheet1[count_row,13] = format_time(course.created_at)
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def shixun_task_xls shixun_task
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "course"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["ID","课堂名称","创建者","学生","实训作业","序号", "ID", "关卡数","作业名称","发布时间","截至时间","已提交作品","有效作品","通关","状态"])
    count_row = 1
    shixun_task.each_with_index do |shixun_task,index|
      teacher_name = shixun_task.teacher ? shixun_task.teacher.show_real_name : ""
      sheet1[count_row,0] = shixun_task.id
      sheet1[count_row,1] = shixun_task.name
      sheet1[count_row,2] = teacher_name
      sheet1[count_row,3] = shixun_task.student.count
      sheet1[count_row,4] = get_shixun_task(shixun_task.id).count
      get_shixun_task(shixun_task.id).each_with_index do |gst, j|
        sheet1[count_row,5] = get_hw_index(gst, @is_teacher, 4) + 1
        sheet1[count_row,6] = gst.shixun.try(:identifier).nil? ? "--" : gst.shixun.try(:identifier)
        sheet1[count_row,7] = gst.shixun.challenges.count
        sheet1[count_row,8] = gst.name
        sheet1[count_row,9] = format_time(gst.publish_time)
        sheet1[count_row,10] = format_time(gst.end_time)
        sheet1[count_row,11] = had_commit_studentwork_count(gst)
        sheet1[count_row,12] = effective_shixun_work_count gst
        sheet1[count_row,13] = tongguan_shixun_work_count gst
        sheet1[count_row,14] = if HomeworkDetailManual.where(:homework_common_id => gst.id).first.comment_status == 0
            "未发布"
            elsif HomeworkDetailManual.where(:homework_common_id => gst.id).first.comment_status == 1
            "提交中"
            elsif HomeworkDetailManual.where(:homework_common_id => gst.id).first.comment_status == 3
            "匿评中"
            elsif HomeworkDetailManual.where(:homework_common_id => gst.id).first.comment_status == 4
            "申诉中"
            elsif HomeworkDetailManual.where(:homework_common_id => gst.id).first.comment_status == 5
            "评阅中"
            else HomeworkDetailManual.where(:homework_common_id => gst.id).first.comment_status == 6
            "已结束"
            end
        count_row += 1
      end
    end
    book.write xls_report
    xls_report.string
  end

  def readXlsData(xlsx)
    doc = SimpleXlsxReader.open(xlsx)
    sheet = doc.sheets.first
    return sheet.rows
  end

  def export_subject_level_system
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "实训课程等级体系"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    count_row = 1
    sheet1.row(0).concat(["序号", "等级", "实训课程名称", "实训课程url", "实训名称"])
    levels = SubjectLevelSystem.includes(subjects: [stage_shixuns: :shixun]).where(nil)
    levels.each_with_index do |level, i|
      sheet1[count_row, 0] = i + 1
      sheet1[count_row, 1] = level.name
      level.subjects.each do |subject|
        sheet1[count_row, 2] = subject.name
        sheet1[count_row, 3] = "#{Setting.protocol}://#{Setting.host_name}#{subject_path(subject)}"
        count_row += 1
        subject.shixuns.each do |shixun|
          sheet1[count_row, 4] = shixun.name
          count_row += 1
        end
      end
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def shixun_feedback_xls shixun_ids, beginTime, endTime
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "实训反馈"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    count_row = 1
    shixuns = Shixun.where(:id => shixun_ids).includes(discusses: [:user])
    sheet1.row(0).concat(["序号", "实训ID", "实训名称", "实训作者", "作者单位", "评论数", "评论内容", "关卡", "评论者", "评论者职业",
                          "评论者单位", "评论时间", "社区导师是否已回复", "我的账号回复内容", "回复时间"])
    shixuns.each_with_index do |shixun, i|
      discusses = shixun.discusses.where("user_id != ?", 1)
      if beginTime.present?
        discusses = discusses.where("created_at >= '#{beginTime}'")
      end
      if endTime.present?
        discusses = discusses.where("created_at <= '#{endTime}'")
      end
      sheet1[count_row, 0] = i + 1
      sheet1[count_row, 1] = shixun.identifier
      sheet1[count_row, 2] = shixun.name
      sheet1[count_row, 3] = shixun.owner.show_real_name
      sheet1[count_row, 4] = shixun.owner.school_name
      sheet1[count_row, 5] = discusses.count
      discusses.each_with_index do |discuss, j|
        user = discuss.user
        content = discuss.content.gsub(/<img.*\/>/, "【图片评论】").gsub(/!\[\].+\)/, "【图片评论】")
        myself_discuss = discuss.children.where(user_id: User.current.id).last
        sheet1[count_row, 6] = strip_html content
        sheet1[count_row, 7] = "第#{discuss.position}关"
        sheet1[count_row, 8] = user.show_real_name
        sheet1[count_row, 9] = user.identity
        sheet1[count_row, 10] = user.school_name
        sheet1[count_row, 11] = format_time discuss.created_at
        sheet1[count_row, 12] = discuss.children.pluck(:user_id).include?(1) ? "是" : "否"
        sheet1[count_row, 13] = myself_discuss.try(:content)
        sheet1[count_row, 14] = myself_discuss ? (format_time myself_discuss.created_at) : ""
        count_row += 1
      end
      #count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def competition_member_xls members, competition
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "报名列表"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    count_row = 1
    records = competition.competition_teams
    if competition.identifier == "gcc-annotation-2018"
      records.each do |team|
        team[:s_score] = team.competition_scores.where(:competition_id => competition.id).first.try(:score).to_f.try(:round, 3)
      end
      records = records.sort do |a, b|
        [b[:s_score]] <=> [a[:s_score]]
      end
    elsif competition.identifier == "gcc-dev-2018"
      pre_stage = competition.competition_stages.where(:name => "预赛").first
      final_stage = competition.competition_stages.where(:name => "决赛").first
      records.each do |team|
        # 决赛记录
        f_score = team.competition_scores.where(:competition_stage_id => final_stage.try(:id)).first
        # 预赛记录
        p_score = team.competition_scores.where(:competition_stage_id => pre_stage.try(:id)).first
        team[:s_score] = (f_score.try(:score).to_f * 0.85 + p_score.try(:score).to_f * 0.15).try(:round, 2)
        team[:s_spend_time] = f_score.try(:cost_time).to_i + p_score.try(:cost_time).to_i
      end
      records = records.sort do |a, b|
        [b[:s_score], a[:s_spend_time]] <=> [a[:s_score], b[:s_spend_time]]
      end
    elsif competition.identifier == 'hn'
      pre_stage = competition.competition_stages.where(:name => "预赛").first
      final_stage = competition.competition_stages.where(:name => "决赛").first
      records.each do |team|
        f_score = team.competition_scores.where(:competition_stage_id => final_stage.try(:id)).first
        p_score = team.competition_scores.where(:competition_stage_id => pre_stage.try(:id)).first
        team[:s_score] = (f_score.try(:score).to_f * 0.8 + p_score.try(:score).to_f * 0.2).try(:round, 2)
        team[:s_spend_time] = f_score.try(:cost_time).to_i + p_score.try(:cost_time).to_i
      end
      records = records.sort do |a, b|
        [b[:s_score], a[:s_spend_time]] <=> [a[:s_score], b[:s_spend_time]]
      end
    end
    if competition.max_num > 1
      sheet1.row(0).concat(["序号", "战队ID", "战队名称", "战队创建者", "指导老师", "队员姓名", "手机号", "邮箱", "学号", "实名认证", "职业认证", "学校名称", "地区", "报名时间", "排名"])
      members.each_with_index do |member, index|
        member_user = member.user
        sheet1[count_row,0] = index + 1
        sheet1[count_row,1] = member.competition_team.try(:id)
        sheet1[count_row,2] = member.competition_team.try(:name)
        sheet1[count_row,3] = member.competition_team.user.try(:show_real_name)
        sheet1[count_row,4] = member.competition_team.teacher.try(:show_real_name)
        sheet1[count_row,5] = member_user.try(:show_real_name)
        sheet1[count_row,6] = member_user.try(:phone)
        sheet1[count_row,7] = member_user.try(:mail)
        sheet1[count_row,8] = member_user.try(:student_id)
        sheet1[count_row,9] = member_user.try(:authentication_status)
        sheet1[count_row,10] = member_user.try(:professional_status)
        sheet1[count_row,11] = member_user.try(:school_name)
        sheet1[count_row,12] = member_user.user_extensions.school.try(:province)
        sheet1[count_row,13] = format_time member.created_at
        sheet1[count_row,14] = records.present? ? (records.map(&:id).index(member.competition_team_id).to_i + 1) : "--"
        count_row += 1
      end
    else
      sheet1.row(0).concat(["序号","姓名","学号","实名认证", "职业认证", "学校名称","地区", "报名时间", "排名"])
      members.each_with_index do |member, index|
        member_user = member.user
        sheet1[count_row,0] = index + 1
        sheet1[count_row,1] = member_user.try(:show_real_name)
        sheet1[count_row,2] = member_user.try(:student_id)
        sheet1[count_row,3] = member_user.try(:authentication_status)
        sheet1[count_row,4] = member_user.try(:professional_status)
        sheet1[count_row,5] = member_user.try(:school_name)
        sheet1[count_row,6] = member_user.user_extensions.school.try(:province)
        sheet1[count_row,7] = format_time member.created_at
        sheet1[count_row,8] = records.present? ? (records.map(&:id).index(member.competition_team_id).to_i + 1) : "--"
        count_row += 1
      end
    end
    book.write xls_report
    xls_report.string
  end

  def published_subject_xls subjects
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "已发布实训课程"
    count_row = 2
    sheet1.row(1).concat(["", "地址", "实训课程名称","章节名称", "实训组成", "关卡数", "状态", "实训发布时间", "课程等级", "更新时间", "发布时间", ])
    Rails.logger.warn("##########subjects:#{subjects.count}")
    subjects.each do |subject|
      sheet1[count_row,1] = "paths/"+subject.id.to_s
      sheet1[count_row,2] = subject.name
      if subject.stages.count > 0
        subject.stages.each_with_index do |stage, s_index|
          sheet1[count_row,3] = stage.name
          if stage.shixuns.count > 0
            stage.shixuns.each_with_index do |shixun, index|
              sheet1[count_row,4] = "#{s_index + 1}-#{index + 1}  #{shixun.name}"
              sheet1[count_row,5] = shixun.challenges.count
              sheet1[count_row,6] = shixun.shixun_status
              sheet1[count_row,7] = shixun.publish_time
              if s_index == 0 && index == 0
                sheet1[count_row,8] = subject.subject_level_system.try(:name) || "--"
                sheet1[count_row,9] = format_time subject.updated_at
                sheet1[count_row,10] = format_time subject.publish_time
              end
              count_row += 1
            end
          else
            if s_index == 0
              sheet1[count_row,8] = subject.subject_level_system.try(:name) || "--"
              sheet1[count_row,9] = format_time subject.updated_at
              sheet1[count_row,10] = format_time subject.publish_time
            end
            count_row += 1
          end
        end
      else
        sheet1[count_row,8] = subject.subject_level_system.try(:name) || "--"
        sheet1[count_row,9] = format_time subject.updated_at
        sheet1[count_row,10] = format_time subject.publish_time
        count_row += 1
      end
    end
    book.write xls_report
    xls_report.string
  end

  def member_json_data mmebers
    mmebers.map do |member|
      real_name = member.show_real_name
      identity = member.identity
      school_name = member.school_name
      user_phone = member.phone || ""
      member.attributes.dup.except("login", "hashed_password", "salt", "status", "mail", "experience", "grade",
                                   "authentication", "professional_certification").merge({real_name: real_name,
                                                                                          identity: identity,
                                                                                          school_name: school_name,
                                                                                          user_phone: user_phone})
    end
  end

end