class Api::V1::Projects::Actions::ActionsController < Api::V1::Projects::Actions::BaseController

  def new_index 
    @files = $gitea_client.get_repos_contents_by_owner_repo_filepath(@project&.owner&.login, @project&.identifier, ".gitea/workflows") rescue []
    @workflows = params[:workflows].split(",") if params[:workflows].present?
    @action_runs = Gitea::ActionRun.where(repo_id: @project.gpid)
    disabled_config = Gitea::RepoUnit.where(repo_id: @project.gpid, type: 10)&.first&.config
    disabled_workflows = disabled_config.present? ? JSON.parse(disabled_config)["DisabledWorkflows"] : []
    @action_runs = @action_runs.where(id: params[:ids].split(",")) if params[:ids].present?
    @action_runs = @action_runs.where(workflow_id: @workflows) if params[:workflows].present?
    group_data = @action_runs.where(status: [1,2]).group(:workflow_id, :status).count
    @result = []
    @files.map{|i|i['name']}.each do |file| 
      if @workflows.present?
        next if !@workflows.include?(file)
      end
      last_action_run = @action_runs.where(workflow_id: file).order(updated: :desc).first
      last_action_run_json = last_action_run.present? ? {
        pipeline_id: Action::Pipeline.find_by(pipeline_name: file, project_id: @project.id),
        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

      pipeline_type = 1
      begin
        content = Gitea::Repository::Entries::GetService.call(@project&.owner, @project&.identifier, URI.escape(file), ref: last_action_run.present? ? last_action_run.ref.gsub("refs/heads/","") : @project.default_branch)['content']
        yaml_string = Base64.decode64(content).force_encoding("GBK").encode("UTF-8") unless Base64.decode64(content).force_encoding('UTF-8').valid_encoding?
        yaml_string = Base64.decode64(content).force_encoding('UTF-8')
        yml = YAML.safe_load(yaml_string)
        pipeline_type = yml.name == file.to_s.gsub(".yml","").gsub(".yaml","") ? 2 : 1
      rescue
        Rails.logger.info("#{file}不能识别流水线类型")
      end
      @result << {
        filename: file,
        disabled: disabled_workflows.include?(file.to_s),
        name: file.to_s.gsub(".yml","").gsub(".yaml","") ,
        branch: last_action_run.present? ? last_action_run.ref.gsub("refs/heads/","") : @project.default_branch,
        pipeline_type: pipeline_type,
        total: total,
        success: success,
        failure: failure
      }.merge(last_action_run_json)
    end
    render :json => {data: @result}
  end

  def index 
    begin 
      gitea_result = $gitea_hat_client.get_repos_actions_by_owner_repo(@project&.owner&.login, @project&.identifier)
      @data = gitea_result[:data]["Workflows"]
    rescue 
      @data = []
    end
  end

  def disable 
    return render_error("请输入正确的流水线文件！") if params[:workflow].blank?
    gitea_result = $gitea_hat_client.post_repos_actions_disable(@project&.owner&.login, @project&.identifier, {query: {workflow: params[:workflow]}}) rescue nil
    if gitea_result 
      render_ok 
    else 
      render_error("禁用流水线失败")
    end
  end 

  def enable 
    return render_error("请输入正确的流水线文件！") if params[:workflow].blank?
    gitea_result = $gitea_hat_client.post_repos_actions_enable(@project&.owner&.login, @project&.identifier, {query: {workflow: params[:workflow]}}) rescue nil
    if gitea_result 
      render_ok 
    else 
      render_error("取消禁用流水线失败")
    end
  end
end