class Admins::ShixunSettingsController < Admins::BaseController

  def index
    default_sort('created_at', 'desc')

    shixun_settings = Admins::ShixunSettingsQuery.call(params)
    @editing_shixuns = shixun_settings.where(status:0).size
    @processed_shixuns = shixun_settings.where(status:2, public: 0).size
    @closed_shixuns = shixun_settings.where(status:3).size
    @pending_public_shixuns = shixun_settings.where(public:1).size
    @processed_pubic_shixuns = shixun_settings.where(public:2).size

    @sort_json = {
      can_copy: params[:can_copy].present? ? params[:can_copy] : false,
      webssh: params[:webssh].present? ? params[:webssh] : "0",
      hidden: params[:hidden].present? ? params[:hidden] : false,
      homepage_show: params[:homepage_show].present? ? params[:homepage_show] : false,
      task_pass: params[:task_pass].present? ? params[:task_pass] : false,
      code_hidden: params[:code_hidden].present? ? params[:code_hidden] : false,
      vip: params[:vip].present? ? params[:vip] : false,
      no_subject: params[:no_subject].present? ? params[:no_subject] : false,
      to_be_built: params[:to_be_built].present? ? params[:to_be_created] : false
    }

    @shixuns_type_check = MirrorRepository.pluck(:type_name,:id)
    @shixun_tags = TagRepertoire.order("name asc").pluck(:name,:id)
    @params_page = params[:page] || 1
    @shixun_settings = paginate shixun_settings.preload(:user,:tag_repertoires)

    respond_to do |format|
      format.js
      format.html
      format.xls{
        filename = "实训详情_#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}.xls"
        export_url =
            if params[:base_data].present?
              shixun_base_list_xls(shixun_settings)
            else
              shixun_list_xls(shixun_settings)
            end
        send_data(export_url, :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end

  end

  def update
    @shixun = Shixun.find_by(id:params[:id])
    @page_no = params[:page_no] || "1"
    @shixun_tags = TagRepertoire.order("name asc").pluck(:name,:id)
    unless @shixun.update_attributes(setting_params)
      redirect_to admins_shixun_settings_path
      flash[:danger] = "更新失败"
    end
  end

  def update_tag_repertoires
    shixun = Shixun.find_by(id:params[:id])
    tag_repertoire_ids = params[:tag_repertoires] || []
    tag_ids = tag_repertoire_ids.reject(&:blank?).map(&:to_i)
    old_tag_ids = shixun.shixun_tag_repertoires.pluck(:tag_repertoire_id)
    new_ids = tag_ids - old_tag_ids
    delete_ids = old_tag_ids - tag_ids
    tag_params = new_ids.map{|sub| {tag_repertoire_id: sub}}
    ActiveRecord::Base.transaction do
      shixun.shixun_tag_repertoires.where(tag_repertoire_id: delete_ids).destroy_all
      shixun.shixun_tag_repertoires.create!(tag_params)
    end
  end

  private
  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.includes(:fork_shixuns, :myshixuns, :mirror_repositories, challenges: [:challenge_tags], user: [user_extension: :school]).find_each do |shixun|
      sheet1[count_row, 0] = shixun.identifier
      sheet1[count_row, 1] = shixun.name
      sheet1[count_row, 2] = shixun.mirror_repositories.select{|mr| mr.main_type == "1"}.first&.type_name

      sheet1[count_row, 3] = shixun.fork_identifier
      sheet1[count_row, 4] = shixun.challenges.select{|c| c.st == 0}.size
      sheet1[count_row, 5] = shixun.challenges.select{|c| c.st == 1}.size
      sheet1[count_row, 6] = shixun.myshixuns_count
      sheet1[count_row, 7] = shixun.myshixuns.select{|m| m.status == 1}.size
      sheet1[count_row, 8] = shixun.shixun_status
      sheet1[count_row, 9] = shixun.user&.show_real_name
      sheet1[count_row, 10] = shixun.user&.school_name
      sheet1[count_row, 11] = shixun.user&.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 shixun_base_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.includes(:mirror_repositories, :challenges, user: [user_extension: :school]).find_each do |shixun|
      sheet1[count_row, 0] = shixun.identifier
      sheet1[count_row, 1] = shixun.name
      sheet1[count_row, 2] = shixun.mirror_repositories.select{|mr| mr.main_type == "1"}.first&.type_name
      sheet1[count_row, 3] = shixun.fork_from
      sheet1[count_row, 4] = shixun.shixun_status
      sheet1[count_row, 5] = shixun.user&.show_real_name
      sheet1[count_row, 6] = shixun.user&.school_name
      sheet1[count_row, 7] = shixun.user&.identity
      challenge_count = shixun.challenges.count
      shixun.challenges.each_with_index do |challenge, index|
        sheet1[count_row, 8] = "第#{challenge.position}关"
        sheet1[count_row, 9] = challenge.subject
        if index + 1 != challenge_count
          count_row += 1
        end
      end
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end

  def setting_params
    params.permit(:use_scope,:excute_time,:close,:status,:can_copy,:webssh,:hidden,:homepage_show,:task_pass,
                  :code_hidden,:vip,:page_no,:id, :no_subject, :to_be_built, :is_wechat_support)
  end
end
