class Videos::BatchPublishService < ApplicationService
  Error = Class.new(StandardError)

  attr_reader :user, :params

  def initialize(user, params)
    @user   = user
    @params = params
  end

  def call
    video_params = Array.wrap(params[:videos]).compact
    return if video_params.blank?
    Rails.logger.info("#####video_course: #{video_params}")

    video_ids = []
    ActiveRecord::Base.transaction do
      video_params.each do |param|
        video = user.videos.find_by(uuid: param[:video_id])
        Rails.logger.info("video.processing_video_apply:#{video}")
        Rails.logger.info("video.processing_video_apply:#{video.blank? || video.processing_video_apply}")
        next if video.blank? || video.processing_video_apply.present?

        raise Error, '视频还未上传完成' if video.vod_uploading?

        video.title = param[:title].to_s.strip.presence || video.title
        video.apply_publish
        if param[:course_id].present?
          video.status = "published"
        end

        #  非MP4 H264编码的都转码
        code_info = AliyunVod::Service.get_meta_code_info(video.uuid)

        result = AliyunVod::Service.get_play_info(video.uuid) rescue nil
        Rails.logger.info("code_info: #{code_info[:format]}, #{code_info[:codecnamne]}")
        if code_info[:format] == "mp4" && code_info[:codecnamne].present? && code_info[:codecnamne].start_with?('h264')
          video.transcoded = true
          if result.present? && result['PlayInfoList']['PlayInfo'].first['PlayURL']
            play_url = result['PlayInfoList']['PlayInfo'].first['PlayURL']
            video.play_url = play_url
          end
        else
          AliyunVod::Service.submit_transcode_job(video.uuid, Video::NORMAL_TRANSCODE_GROUP_ID)
        end

        if result.present?
          video.duration = result['PlayInfoList']['PlayInfo'][0]['Duration'] if result['PlayInfoList']['PlayInfo'][0]['Duration'].present?
        end

        video.save!

        if param[:course_id].present?
          video.video_applies.create!(status: "agreed")
          CourseVideoUploadedJob.perform_later(video.id) if video.transcoded
        else
          video.video_applies.create!
        end

        video_ids << video.id

        # 如果是课堂上传则创建课堂记录
        Rails.logger.info("#####param: #{ param[:course_id]}")
        if param[:course_id].present?
          course_second_category_id = param[:category_id] || 0
          video.course_videos.create!(course_id: param[:course_id], course_second_category_id: course_second_category_id)
        end
      end
    end

    BatchPublishVideoNotifyJob.perform_later(user.id, video_ids) if video_ids.present?
  end
end