# encoding=utf-8
# Redmine - project management software
# Copyright (C) 2006-2013  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

class WelcomeController < ApplicationController
  # layout "base_welcome"
  include ApplicationHelper
  include WelcomeHelper
  helper :project_score
  caches_action :robots, :course, :contest,  expires_in: 2.hours, layout: false
  #before_filter :find_first_page, :only => [:index]
  # before_filter :fake, :only => [:index, :course]
  before_filter :entry_select, :only => [:index]
  skip_before_filter :check_authentication, :only => [:index]

  require 'simple_xlsx_reader'

  DCODES = %W(2 3 4 5 6 7 8 9 a b c f e f g h i j k l m n o p q r s t u v w x y z)
  def local_init
    LocalShixun.delete_all
    LocalMirrorRepository.delete_all
    LocalShixunTagRepertoire.delete_all
    LocalChallenge.delete_all
    LocalTestSet.delete_all
    LocalChallengeTag.delete_all
    render :json => {status: 0, message: "success"}
  end

  # 运营引流个人数据展示
  def user_agents
    @user_agents = UserAgent.where(key: params[:edu])
    @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
    respond_to do |format|
      format.js
      format.html{ render :layout=>'users_base'}
    end
  end

  def join_private_courses
    @invitation_code = params[:invitation_code]
    respond_to do |format|
      format.js
    end
  end

  def shixun_to_local
    identifiers = params[:identifiers].split(",")
    shixuns = Shixun.where(identifier: identifiers)
    # 不重复导入
    ActiveRecord::Base.transaction do
      begin
        shixuns.each do |shixun|
          if LocalShixun.where(shixun_id: shixun.id).blank?

            local_shixun = LocalShixun.create!(name: shixun.name, description: shixun.description, user_id: User.current.id, status: 0,
                                               trainee: shixun.trainee, webssh: shixun.webssh, multi_webssh: shixun.multi_webssh,
                                               can_copy: shixun.can_copy, identifier: generate_identifier, shixun_id: shixun.id,
                                               use_scope: shixun.use_scope, visits: 1, evaluate_script: shixun.evaluate_script,
                                               local_giturl: shixun.git_url)

            # 同步镜像
            if shixun.mirror_repositories.present?
              shixun.mirror_repositories.each do |mirror|
                # 本地版的mirror id和线上的可能不一样,所以按名字取,然后再存
                # local_mirror = MirrorRepository.where(type_name: mirror.type_name).first.try(:id)
                LocalMirrorRepository.create!(:local_shixun_id => local_shixun.id, :mirror_repository_id => mirror.id, type_name: mirror.type_name)
              end
            end

            # 同步技术标签
            shixun.shixun_tag_repertoires.each do |str|
              LocalShixunTagRepertoire.create!(:tag_repertoire_id => str.tag_repertoire_id, :local_shixun_id => local_shixun.id)
            end

            # 不需要同步版本库,版本库应该是从本地导入到线上的时候由线上版本创建的

            # 同步复制关卡
            if shixun.challenges.present?
              shixun.challenges.each do |challenge|
                new_challenge = LocalChallenge.new
                new_challenge.attributes = challenge.attributes.dup.except("id","shixun_id","user_id", "test_set_score")
                new_challenge.local_shixun_id = local_shixun.id
                new_challenge.save!
                # 评测题,选择题暂时不考虑
                # 同步测试集
                if challenge.test_sets.present?
                  challenge.test_sets.each do |test_set|
                    new_test_set = LocalTestSet.new
                    new_test_set.attributes = test_set.attributes.dup.except("id","challenge_id")
                    new_test_set.local_challenge_id = new_challenge.id
                    new_test_set.save!
                  end
                end
                # 同步关卡标签
                challenge_tags = ChallengeTag.where("challenge_id =? and challenge_choose_id is null", challenge.id)
                if challenge_tags.present?
                  challenge_tags.each do |challenge_tag|
                    LocalChallengeTag.create!(:local_challenge_id => new_challenge.id, :name => challenge_tag.try(:name))
                  end
                end
              end
            end
          end
        end
        render :json => {status: 0, message: "success"}
      rescue Exception => e
        logger.error("shixun_local_in ##{e.message}")
        render :json => {status: -1, message: "error,#{e.message}"}
        raise ActiveRecord::Rollback
      end

    end
  end

  def local_to_shixun
    ActiveRecord::Base.transaction do
      shixun_list = []
      LocalShixun.find_each do |local_shixun|
        identifier = generate_identifier
        shixun = Shixun.create!(name: local_shixun.name, description: local_shixun.description, user_id: User.current.id,
                                trainee: local_shixun.trainee, webssh: local_shixun.webssh, multi_webssh: local_shixun.multi_webssh,
                                can_copy: local_shixun.can_copy, identifier: identifier, reset_time: Time.now,
                                modify_time: Time.now, use_scope: local_shixun.use_scope, visits: 1, evaluate_script: local_shixun.evaluate_script)
        m = ShixunMember.new(:user_id => User.current.id, :role => 1)
        shixun.shixun_members << m

        # 同步镜像
        local_mirrors = LocalMirrorRepository.where(local_shixun_id: local_shixun.id)
        if local_mirrors.present?
          local_mirrors.each do |local_mirror|
            local_mirror_new = MirrorRepository.where(type_name: local_mirror.try(:type_name)).first
            ShixunMirrorRepository.create!(:shixun_id => shixun.id, :mirror_repository_id => local_mirror_new.id)
          end
        end

        # 同步技术标签
        local_shixun_tags = LocalShixunTagRepertoire.where(local_shixun_id: local_shixun.id)
        if local_shixun_tags.present?
          local_shixun_tags.each do |str|
            ShixunTagRepertoire.create!(:tag_repertoire_id => str.tag_repertoire_id, :shixun_id => shixun.id)
          end
        end

        # 创建版本库
        repository = Repository.new
        repository.shixun = shixun
        repository.type = 'Repository::Gitlab'
        repository.identifier = shixun.identifier.downcase
        repository.project_id = -1
        repository.save!
        s = Trustie::Gitlab::Sync.new
        s.create_shixun(shixun, repository)
        raise "版本库创建失败" if shixun.gpid.blank?   # 若和gitlab没同步成功,则抛出异常
        g = Gitlab.client
        shixun.update_column(:git_url, g.project(shixun.gpid).path_with_namespace)
        local_git_path = local_shixun.local_giturl.split('/').last if local_shixun.local_giturl.present?
        new_giturl = "http://educoder:xinhu1ji2qu3@"+g.project(shixun.gpid).http_url_to_repo.split('//').last
        # 如果有目录才执行
        if system("cd tmp/repositories/#{local_git_path}")
          system("cd tmp/repositories/#{local_git_path};git remote remove origin;git remote add origin #{new_giturl};
                  git add .;git commit -m '..';git push origin master")
        end


        #  http://Hjqreturn:xinhu1ji2qu3@bdgit.educoder.net/Hjqreturn/pgfqe6ch8.git (fetch)

        # 同步关卡信息
        local_challenges = LocalChallenge.where(local_shixun_id: local_shixun.id)
        if local_challenges.present?
          local_challenges.each do |local_challenge|
            new_challenge = Challenge.new
            new_challenge.attributes = local_challenge.attributes.dup.except("id","local_shixun_id","user_id", "test_set_score")
            new_challenge.user_id = User.current.id
            new_challenge.shixun_id = shixun.id
            new_challenge.save!

            # 同步测试集
            local_test_sets = LocalTestSet.where(local_challenge_id: local_challenge.id)
            if local_test_sets.present?
              local_test_sets.each do |local_test_set|
                new_test_set = TestSet.new
                new_test_set.attributes = local_test_set.attributes.dup.except("id","challenge_id")
                new_test_set.challenge_id = new_challenge.id
                new_test_set.save!
              end
            end

            # 同步关卡标签
            local_challenge_tags = LocalChallengeTag.where(local_challenge_id: local_challenge.id)
            if local_challenge_tags.present?
              local_challenge_tags.each do |local_challenge_tag|
                ChallengeTag.create!(:challenge_id => new_challenge.id, :name => local_challenge_tag.try(:name))
              end
            end
          end
        end
        shixun_list << shixun.identifier
      end
      render :json => {status: 0, message: "success", identifier: shixun_list}
    end
  end


  # 生成表示码
  def generate_identifier
    code = DCODES.sample(8).join
    return generate_identifier if Shixun.where(identifier: code).present?
    code
  end
 
  def index
    images = PortalImage.where(status: true).order("position asc")
    @images_url = []
    images.each do |image|
      @images_url << {path: image.link, image_url: "/images/avatars/PortalImage/#{image.id}"}
    end
    # 目录分级
    repertoires = Repertoire.includes(sub_repertoires: :tag_repertoires).order("updated_at asc")
    @rep_list = []
    repertoires.each do |rep|
      sub_rep_list = []
      rep.sub_repertoires.each do |sub_rep|
        tag_rep_list = []
        sub_rep.tag_repertoires.each do |tag_rep|
          tag_rep_list << {tag_id: tag_rep.id, tag_name: tag_rep.name}
        end
        sub_rep_list << {sub_rep_id: sub_rep.id, sub_rep_name: sub_rep.name, tag_rep_list: tag_rep_list}
      end
      @rep_list << {rep_id: rep.id, rep_name: rep.name, sub_rep_list: sub_rep_list}
    end
    @shixuns = Shixun.select([:id, :user_id, :homepage_show, :identifier, :status, :name, :challenges_count, :myshixuns_count, :use_scope,
                              :trainee, :averge_star]).where(homepage_show: 1).includes(:tag_repertoires).order("myshixuns_count desc").limit(8)
    @subjects = Subject.where(homepage_show: 1).includes(:shixuns).limit(8)
    @tea_users = User.where(homepage_teacher: 1).includes(:user_extensions).limit(10).order("experience desc")
    @stu_users = User.includes(:user_extensions).where(user_extensions: {identity: 1}).limit(10).order("experience desc")

    render :layout => 'educoder'
  end

  # 自动导入用户
  def import_users
    begin
      lists = read_xlsx_data("files/users.xlsx")
      lists.each_with_index do |list|
        logger.info("#{list[0]}---#{list[1]}")
        mail = list[1] + "@educoder.net"
        login = "edu" + list[1]
        if User.where(:login => login).blank?
          us = UsersService.new
          user = us.register phone: mail, password: 'wuhan12345678'
          @user = user
          @user.login = login
          @se = @user.extensions
          @user.lastname = list[0]
          @user.firstname = ""
          @user.show_realname = 0
          @user.nickname = list[0]

          @se.school_id = 117
          if @user.save && @se.save
            reward_grade(@user, @user.id, 'Account', 500)
            user.update_attributes!(authentication:1)
          end
          render :json => {:message => "sucess"}
        end
      end
    rescue Exception => e
      logger.error(e.message)
      render :json => {:status => 500}
    end
  end

  # 读取文件
  def read_xlsx_data(xlsx)
    doc = SimpleXlsxReader.open(xlsx)
    sheet = doc.sheets.first
    return sheet.rows
  end

  def add_user_by_name



  end

  def ccf
    render :layout => 'base_ccf'
  end

  def robots
    @projects = Project.all_public.active
    render :layout => false, :content_type => 'text/plain'
  end

  def course
    redirect_to signin_path
    return
    #
    # @course_page = FirstPage.find_by_page_type('course')
    # @school_id = params[:school_id] || User.current.user_extensions.school.try(:id) || 117
    # @logoLink ||= logolink()
  end

  def logolink()
    @course_page = FirstPage.find_by_page_type('course')
    logo = get_avatar?(@course_page)
    id = params[:school_id]
    logo_link = ""
    if id.nil? && (User.current.user_extensions.nil? || User.current.user_extensions.school.nil?)
      if logo
        logo_link = url_to_avatar(@course_page)
      else
        logo_link = '/images/transparent.png'
      end

    else
      if id == "0"
        if logo
          logo_link = url_to_avatar(@course_page)
        else
          logo_link = '/images/transparent.png'
        end
      else
        if id.nil?
          if School.find(User.current.user_extensions.school.id).logo_link.nil?
            logo_link = '/images/transparent.png'
          else
            logo_link = School.find(User.current.user_extensions.school.id).logo_link
          end
        else
          logo_link = School.find(id).logo_link

        end
      end
    end
    return logo_link
  end
  
  
  def contest
    redirect_to signin_path
    return

    # @contest_page = FirstPage.find_by_page_type('contest')
    # @contest_notifications = Contestnotification.order("created_at desc").limit(5)
  end

  def search
    @name = params[:q]
    @search_type = params[:search_type]
    page = (params[:page] || 1).to_i

    @users_count = User.search(@name).results.total
    @syllabus_count = Syllabus.search(@name).results.total
    @course_count = Course.search(@name).results.total
    @attach_count = Attachment.search(@name).results.total
    @project_count = Project.search(@name).results.total
    @memo_count = Memo.search(@name).results.total
    @total_count = Elasticsearch::Model.search({
                                                   query: {
                                                       multi_match: {
                                                           query: @name,
                                                           type:"most_fields",
                                                           operator: "or",
                                                           fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
                                                       }
                                                   },
                                                   highlight: {
                                                       pre_tags: ['<span class="c_red">'],
                                                       post_tags: ['</span>'],
                                                       fields: {
                                                           login: {},
                                                           firstname: {},
                                                           lastname: {},
                                                           title:{},
                                                           name:{},
                                                           description:{},
                                                           filename:{},
                                                           subject:{},
                                                           content:{}
                                                       }
                                                   }
                                               },[User,Syllabus,Course,Attachment,Project,Memo] ).results.total


    case params[:search_type]
      when 'all'
        if (page-1)*20 >= @total_count
          page = 1
          params[:page] = "1"
        end
        @alls = Elasticsearch::Model.search({
                                                         query: {
                                                             multi_match: {
                                                                 query: @name,
                                                                 type:"most_fields",
                                                                 operator: "or",
                                                                 fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
                                                             }
                                                         },
                                                         highlight: {
                                                             pre_tags: ['<span class="c_red">'],
                                                             post_tags: ['</span>'],
                                                             fields: {
                                                                 login: {},
                                                                 firstname: {},
                                                                 lastname: {},
                                                                 title:{},
                                                                 name:{},
                                                                 description:{},
                                                                 filename:{},
                                                                 subject:{},
                                                                 content:{}
                                                             }
                                                         }
                                                     },[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results
      when 'user'
            if (page-1)*20 >= @users_count
              page = 1
              params[:page] = "1"
            end
            @users = User.search(@name).page(page).per(20)
      when 'syllabus'
            if (page-1)*20 >= @syllabus_count
              page = 1
              params[:page] = "1"
            end
            @syllabuses = Syllabus.search(@name).page(page).per(20).results
      when 'project'
            if (page-1)*20 >= @project_count
              page = 1
            end
            @projects = Project.search(@name).page(page).per(20).results
      when 'course'
            if (page-1)*20 >= @course_count
              page = 1
              params[:page] = "1"
            end
            @courses = Course.search(@name).page(page).per(20).results
      when 'attachment'
            if (page-1)*20 >= @attach_count
              page = 1
              params[:page] = "1"
            end
            @attachments = Attachment.search(@name).page(page).per(20).results
      when 'memo'
            if (page-1)*20 >= @memo_count
              page = 1
              params[:page] = "1"
            end
            @memos = Memo.search(@name).page(page).per(20).results
      else
              if (page-1)*20 >= @total_count
                page = 1
                params[:page] = "1"
              end
              @alls = Elasticsearch::Model.search({
                                                                     query: {
                                                                         multi_match: {
                                                                             query: @name,
                                                                             type:"most_fields",
                                                                             operator: "or",
                                                                             fields: ['login', 'firstname','lastname','title','name','description^0.5','filename','subject','content^0.5']
                                                                         }
                                                                     },
                                                                     highlight: {
                                                                         pre_tags: ['<span class="c_red">'],
                                                                         post_tags: ['</span>'],
                                                                         fields: {
                                                                             login: {},
                                                                             firstname: {},
                                                                             lastname: {},
                                                                             title:{},
                                                                             name:{},
                                                                             description:{},
                                                                             filename:{},
                                                                             subject:{},
                                                                             content:{}
                                                                         }
                                                                     }
                                                                 },[User,Syllabus,Course,Attachment,Project,Memo] ).page(page).per(20).results

    end



    # search_type = params[:search_type].to_sym unless search_condition.blank?
    # search_by = params[:search_by]
    #
    # if search_type.nil? && params[:contests_search] && params[:name] != ""
    #   search_type  = :contests
    #   search_condition = params[:name]
    # end

    respond_to do |format|
      format.js
      format.html{ render :layout=>'users_base'}
    end
  end

  private
  # 判断网站的入口,是课程 course 则跳过index去渲染 course 方法
  def entry_select
    # url = request.original_url.gsub('/','')
    # if url.include?(Setting.url_course.gsub('/',''))
    #   if @first_page.show_course == 1
    #     course
    #     render :course
    #   else
    #     render_404
    #   end
    #
    #   return 0
    # elsif url.include?(Setting.url_contest.gsub('/',''))
    #   if @first_page.show_contest == 1
    #     contest
    #     render :contest
    #   else
    #     render_404
    #   end
    #
    #   return 0
    # elsif url.include?(Setting.url_user.gsub('/',''))
    #   #redirect_to(:controller => "users", :action => "index")
    # end
      
    
  end

  # def render(*args)
  #   _fake if @fake_filter
  #   super
  # end

  # private

  # def fake
  #   @fake_filter = true
  # end
  
  # # 骗子方法
  # def _fake
  #   instance_variables.map { |variable|
  #     if variable.to_s =~ /Count$/
  #       self.instance_variable_set(variable.to_sym,
  #          ("1" + (self.instance_variable_get(variable.to_sym).to_s)).to_i)
  #     end
  #   }
  # end

end