class Api::Pm::ActionRunsController < Api::Pm::BaseController
  before_action :require_login

  def index
    tip_exception('请输入workflows') if params[:workflows].blank?
    @owner = Owner.find_by(login: params[:owner_id].to_s) || Owner.find_by(id: params[:owner_id].to_s)
    tip_exception('组织未找到') if @owner.blank?
    action_runs = Gitea::ActionRun.where(owner_id: @owner.gitea_uid)
    group_data = action_runs.where(workflow_id: params[:workflows].to_s.split(",")).where(status: [1,2]).group(:workflow_id, :status).count
    @result = []
    params[:workflows].to_s.split(",").each do |file|
      last_action_run = action_runs.where(workflow_id: file).order(updated: :desc).first
      last_action_run_json = last_action_run.present? ? {
        id: last_action_run.id,
        schedule: last_action_run.schedule_id > 0,
        title: last_action_run.title,
        index: last_action_run.index,
        status: last_action_run.status,
        started: last_action_run.started,
        stopped: last_action_run.stopped,
        length: last_action_run.stopped - last_action_run.started,
        created: last_action_run.created,
        updated: last_action_run.updated,
      } : {}

      total = 0
      success = 0
      failure = 0
      group_data.each do |k,v|
        total += v if k[0] == file
        success += v if k[0] == file && k[1] == 1
        failure += v if k[0] == file && k[1] == 2
      end

      @result << {
        name: file,
        total: total,
        success: success,
        failure: failure
      }.merge(last_action_run_json)
    end
    render :json => {data: @result}
  end

end