class Admins::ProjectsController < Admins::BaseController
  before_action :require_business
  before_action :find_project, only: [:edit, :update, :sync_phenglei_user]

  def index
    sort_by = Project.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_on'
    sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
    search = params[:search].to_s.strip
    projects = Project.where("id = ? OR name like ? OR identifier LIKE ?", search, "%#{search}%", "%#{search}%").order("#{sort_by} #{sort_direction}")
    case params[:category]
    when 'public'
      projects = projects.where(is_public: true)
    when 'private'
      projects = projects.where(is_public: false)
    when 'fork'
      projects = projects.where.not(forked_from_project_id: nil)
    when 'original'
      projects = projects.where(forked_from_project_id: nil, project_type: 'common')
    end
    @projects = paginate projects.includes(:owner, :members, :issues, :versions, :attachments, :project_score)
  end

  def edit ;end

  def update
    respond_to do |format|
      if @project.update_attributes(project_update_params)
        format.html do 
          redirect_to admins_projects_path
          flash[:sucess] = "更新成功"
        end
        format.js {render_ok}
      else 
        format.html do 
          redirect_to admins_projects_path
          flash[:danger] = "更新失败"
        end
        format.js {render_js_error}
      end
    end
  end

  def destroy
    project = Project.find_by!(id: params[:id])
    ActiveRecord::Base.transaction do
      close_fork_pull_requests_by(project)
      Gitea::Repository::DeleteService.new(project.owner, project.identifier, current_user.gitea_token).call
      project.destroy!
      project.forked_projects.update_all(forked_from_project_id: nil)
      # 如果该项目有所属的项目分类以及为私有项目，需要更新对应数量
      project.project_category.decrement!(:private_projects_count, 1) if project.project_category.present? && !project.is_public
      # render_delete_success
      UserAction.create(action_id: project.id, action_type: "DestroyProject", user_id: current_user.id, :ip => request.remote_ip, data_bank: project.attributes.to_json)
      redirect_to admins_projects_path
      flash[:success] = "删除成功"
    end
    rescue Exception => e
      redirect_to admins_projects_path
      flash[:danger] = "删除失败"
  end

  def export
    sort_by = Project.column_names.include?(params[:sort_by]) ? params[:sort_by] : 'created_on'
    sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : 'desc'
    search = params[:search].to_s.strip
    projects = Project.where("name like ?", "%#{search}%").order("#{sort_by} #{sort_direction}")
    @projects = projects.includes(:owner, :members, :issues, :versions, :attachments, :project_score, :license)
    filename = ["项目列表", Time.zone.now.strftime('%Y%m%d%H%M%S')].join('-') << '.xlsx'
    @domain_url = EduSetting.get('host_name')
    render xlsx: 'export', filename: filename
  end

  def sync_phenglei_user
    if @project.is_secret
      SyncPhengleiUserJob.perform_later(@project.id)
      redirect_to admins_phenglei_users_path
      flash[:success] = "已开启后台同步任务"
    else
      redirect_to admins_phenglei_users_path
      flash[:danger] = "非风雷协议项目"
    end
  end

  private
  def find_project
    @project = Project.find_by_id(params[:id])
  end

  def project_update_params 
    params.require(:project).permit(:is_pinned, :recommend, :recommend_index)
  end

  def close_fork_pull_requests_by(project)
    open_pull_requests = PullRequest.where(fork_project_id: project.id)
    if open_pull_requests.present?
      open_pull_requests.each do |pull_request|
        closed = PullRequests::CloseService.call(pull_request&.project.owner, pull_request&.project.repository, pull_request, current_user)
        if closed === true
          pull_request.project_trends.create!(user: current_user, project: pull_request&.project,action_type: ProjectTrend::CLOSE)
          # 合并请求下issue处理为关闭
          pull_request.issue&.update_attributes!({status_id:5})
          SendTemplateMessageJob.perform_later('PullRequestClosed', current_user.id, pull_request.id) if Site.has_notice_menu?
        end
      end 
    end
  end
end