class SchoolController < ApplicationController
  layout 'course_base'
  before_filter :require_admin, :only => :upload_logo
  
  def upload
    uploaded_io = params[:logo]
    school_id ||= params[:id]
    s1 = School.find(school_id)
    unless uploaded_io.nil? 
      File.open(Rails.root.join('public', 'images', 'school', school_id.to_s+'.png'), 'wb') do |file|
        file.write(uploaded_io.read)
      end

      s1.logo_link  = '/images/school/'+school_id.to_s+'.png'

    end
    s1.name = params[:name] unless params[:name].blank?
    s1.province = params[:province] unless params[:province].blank?
    s1.save
    redirect_to admin_schools_url(:school_name => params[:school_name])
  end  

  def upload_logo
    @school = School.find params[:id]
    @school_name = params[:school_name]
  end

  #获取制定学校开设的课程数
  def course_count school_id
     School.find(school_id).courses.count
  end
  
  
  def index
    
  end

  def get_province
    @provinces = School.find_by_sql("select distinct province from schools")

    options = ""

    @provinces.each do |p|
      options << "<option value = '#{p.province}' >#{p.province}</option>"
    end

    # 取id取学校名
    # 连接子表: 查询已添加用户的学校
    school = School.select("id, name").
              joins("RIGHT JOIN (
                      SELECT DISTINCT school_id 
                      FROM #{UserExtensions.table_name} 
                      WHERE school_id IS NOT NULL) AS sids ON schools.id = sids.school_id").
              where("#{School.table_name}.id IS NOT NULL")

    options_s = ""
    school.each do |s|
      options_s << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id, this.text)'>#{s.name}</a></li>"
    end

    res = Hash.new
    res[:text] = options
    res[:text_s] = options_s

    render :json => res


  end
  
  def get_options
    @school = School.where("province = ?", params[:province])
    p = params[:province]
    ##@school = School.all
    options = ""
    
    @school.each do |s|
      #options << "<option value=#{s.id}>#{s.name}</option>"
      options << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id, this.text)'>#{s.name}</a></li>"
    end
    
    
    render :text => options
    
  end

  def get_schoollist
     @school = School.where("province = ?", params[:province])
     
     options = ""
     @school.each do |s|
       options << "<li style = 'width: 33%; float: left'><a style='cursor: pointer;' id=#{s.id} onclick='test(this.id)'>#{s.name}</a></li>"
     end
     
     render :text => options
  end
  
  def search_school
    q = "%#{params[:key_word].strip}%"
    
    @school = School.where("name LIKE ?", q)
    @school = @school.where("province = ?", params[:province]) if (params[:province] != '0' )

    options = ""
    @school.each do |s|
      options << "<li style = 'width: 33%; float: left'> <a style='cursor: pointer;' id=#{s.id} onclick='test(this.id)'>#{s.name}</a></li>"
    end

    options = "<div class='flash error' id='flash_error'>#{l(:label_school_not_fount)}</div>" if options.blank?

    render :text => options    
  end

  #根据学校名字或者拼音来查询
  def on_search
    condition = "#{params[:name].strip}".gsub(" ","")
    #将条件截断为汉字和拼音（全汉字 或者 全拼音 或者 汉字和拼音），
      #获取拼音的第一次出现的位置
      chinese = []
      pinyin  = []
    condition.scan(/./).each_with_index  do |char,index|
         if char =~ /[a-zA-Z0-9]/
           pinyin << char
         elsif char =~ /\'/
         else
           chinese << char
         end
    end
    if(condition == '')
      @school = School.reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
      @school_count = School.count
    else
      @school = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").reorder('pinyin').page((params[:page].to_i || 1) - 1).per(100)
      @school_count = School.where("name like '%#{chinese.join("")}%' and pinyin like '%#{pinyin.join("")}%'").count
    end

    result = []
    # @school.each do |sc|
    #   result << {:value=>sc.name,:data=>sc.id}
    # end
   render :json =>{ :schools => @school,:count=>@school_count}.to_json
  end

  #添加学校
  def add_school
    @school = School.new
    @school.name = params[:name].strip
    @school.pinyin = Pinyin.t(params[:name].strip, splitter: '')
    @school.save
    respond_to do |format|
      format.js
    end
  end

  #申请高校(单位) name:名称 province:省 city:市 address:地址 remarks:备注
  def apply_add_school

    data = {result:0,name:params[:name],school_id:0}
    #0 成功 1参数错误 2名称已存在 3.失败
    data[:result] = 0

    #检验参数
    if params[:name] == "" || params[:province] == "" || params[:city] == "" || params[:address] == ""
      data[:result] = 1
    else
      school = School.where("name = '#{params[:name]}'").first
      if school
        data[:result] = 2
      else
        school = School.new
        school.name = params[:name].strip
        school.pinyin = Pinyin.t(params[:name].strip, splitter: '')
        school.province = params[:province]

        #status  0未处理 1通过 2拒绝
        applyschool = ApplyAddSchools.new

        #用belongs_to 可以一起存数据库
        applyschool.school = school
        applyschool.name = school.name
        applyschool.province = params[:province]
        applyschool.city = params[:city]
        applyschool.address = params[:address]
        applyschool.remarks = params[:remarks]
        applyschool.user_id = User.current.id
        if applyschool.save
          data[:school_id] = school.id
          user_extention=  User.current.extensions
          user_extention.school_id = school.id
          user_extention.save!

          # 向管理员发送信息
          users = User.where(:admin => 1)
          users.each do |user|
            AppliedMessage.create(:user_id => user.id, :status => 0, :applied_user_id => User.current.id, :viewed => 0, :applied_id => school.id, :applied_type => "ApplyAddSchools", :name => school.name )
          end

        else
          data[:result] = 3
        end
      end
    end
    render :json =>data
  end

  def search_repeat_schoolname
    status = 0  #没有重复的
    name = params[:name]

    if name
      school = School.where("name = '#{name}'").first

      if school
        status = 1 #有重复的
      end
    end


    render :json =>status
  end

  def edit_apply_name
    name = params[:name] || ""
    status = -1

    if name != ""
      applyschool = ApplyAddSchools.where("id=?",params[:id]).first

      applyschool.name = name.strip

      if applyschool.school
        applyschool.school.name = name
        applyschool.school.pinyin = Pinyin.t(name.strip, splitter: '')
        applyschool.school.save!
      end
      applyschool.save!
      status = 0
    end

    render :json=>{:status=>status,:id=>params[:id],:name=>name}
  end

  def edit_apply_address
    address = params[:address] || ""

    status = -1

    if address != ""
      applyschool = ApplyAddSchools.where("id=?",params[:id]).first
      applyschool.address = address
      applyschool.save!
      status = 0
    end

    render :json=>{:status=>status,:id=>params[:id],:address=>address}
  end

  def edit_apply_province
    province = params[:province] || ""
    city = params[:city] || ""
    status = -1

    if(province != "") &&(city != "")
      applyschool = ApplyAddSchools.where("id=?",params[:id]).first
      applyschool.province = province
      applyschool.city = city

      if applyschool.school
        applyschool.school.province = province
        applyschool.school.save!
      end
      applyschool.save!

      if applyschool.user_id && applyschool.user_id != 0
        user = User.find(applyschool.user_id)
        user_extention=  user.extensions
        user_extention.location = province
        user_extention.location_city = city
        user_extention.save!
      end
      status = 0
    end

    render :json=>{:status=>status,:id=>params[:id],:province=>province,:city=>city}
  end
end
