module ProjectsHelper
  def menu_hash_by_name(name)
    {
      menu_name: name
    }
  end

  def render_zh_project_type(project_type)
    case project_type
    when 'common' then "开源托管项目"
    when 'sync_mirror' then "镜像托管项目"
    when 'mirror' then "开源镜像项目"
    end
  end

  def render_zip_url(owner, repository, archive)
    [base_url, archive_repositories_path(owner&.login, repository, "#{archive}.zip")].join
  end

  def render_tar_url(owner, repository, archive)
    [base_url, archive_repositories_path(owner&.login, repository, "#{archive}.tar.gz")].join
  end

  def render_download_file_url(owner, repository, filepath, ref)
    [base_url, "/api/#{owner&.login}/#{repository.identifier}/raw/#{CGI.escape(filepath)}?ref=#{CGI.escape(ref)}"].join
  end

  def render_http_url(project)
    [gitea_domain, project.owner.login, "#{project.identifier}.git"].join('/')
  end

  def gitea_domain
    GiteaService.gitea_config[:domain]
  end

  def find_user_by_login_or_mail(identifier)
    (User.find_by_login identifier) || (User.find_by_mail identifier)
  end

  def json_response(project, user)
    repo = Repository.includes(:mirror).select(:id, :is_mirror, :mirror_url, :source_clone_url).find_by(project: project)

    tmp_json = {}
    unless project.common?
      tmp_json = tmp_json.merge({
        is_mirror: repo.is_mirror ? true : false,
        mirror_status: repo.mirror_status,
        mirror_num: repo.mirror_num,
        mirror_url: repo.remote_mirror_url,
        first_sync: repo.first_sync?
      })
    end

    tmp_json = tmp_json.merge({
      identifier: render_identifier(project),
      name: project.name,
      platform: project.platform,
      id: project.id,
      repo_id: repo.id,
      open_devops: (user.blank? || user.is_a?(AnonymousUser)) ? false : project.open_devops?,
      type: project.numerical_for_project_type,
      author: render_owner(project),
      is_secret: project.is_secret,
      is_member: project.member?(user.id),
      is_need_apply: project.is_need_apply,
      user_apply_signatures: project.apply_signatures.with_user_id(user.id).collect{|s| {id: s.id, status: s.status}},
      project_category_id: project.project_category_id,
      project_language_id: project.project_language_id,
      license_id: project.license_id,
      license_name: project.license&.name,
      jianmu_devops: jianmu_devops_code(project, user),
      jianmu_devops_url: jianmu_devops_url,
      cloud_ide_saas_url: cloud_ide_saas_url(user),
      open_blockchain: Site.has_blockchain? && project.use_blockchain,
      has_dataset: project.project_dataset.present?,
      open_portrait: project.open_portrait,
      ignore_id: project.ignore_id,
      has_project_visitor: project.project_visitors.find_by(user_id: user.id).present?,
      sca_project_id: project.sca_project_id
    }).compact

    render json: tmp_json
  end

  def render_owner(project)
    if project.educoder?
      {
        login: project.project_educoder.owner,
        name: project.project_educoder.owner,
        type: 'Educoder',
        image_url: project.project_educoder.image_url
      }
    else
      {
        login: @owner.login,
        name: @owner.real_name,
        type: @owner.type,
        image_url: url_to_avatar(@owner)
      }
    end
  end

  def render_identifier(project)
    project.educoder? ? project.project_educoder&.repo_name&.split('/')[1] : project.identifier
  end

  def render_author(project)
    project.educoder? ? project.project_educoder&.repo_name&.split('/')[0] : project.owner.login
  end

  def render_educoder_avatar_url(project_educoder)
    [Rails.application.config_for(:configuration)['educoder']['cdn_url'], project_educoder&.image_url].join('/')
  end

  # 静默登录方式：
  #
  # 数据格式为JSON：
  # {
  #  "userId": "xxx", // 用户唯一标识
  #  "ref": "xxx",     // 仓库唯一标识
  #  "owner": "xxx",  // 用户登录名或组织账号
  #  "timestamp": xxx // 当前时间戳，单位：毫秒
  # }
  # 加密方式：把数据序列化成JSON字符串，用Client Secret和固定IV（5183666c72eec9e4）对称加密（模式：AES-256-CBC）
  #
  # API：
  # GET：https://ci-v3.test.jianmuhub.com/oauth2/authorize?code=${encode(密文)}
  def jianmu_devops_code(project, user)
    if user.admin? || project.member?(user.id)
      data = { userId: user.id, ref: project.identifier, owner: project.owner.login, timestamp: Time.now.to_i * 1000 }
      # uid = EduSetting.get("jianmu_oauth2_uid") || 'oedKx4v-WyAfu2oy_AsFpFQCH_-g91ms0PQKN7YcEuw'
      # app = Doorkeeper::Application.find_by(uid: uid)
      key = 'bf3c199c2470cb477d907b1e0917c17b'
      aes_encrypt(key, data.to_json)
    end
  end

  def jianmu_devops_url
    EduSetting.get("jianmu_devops_url")
  end


  def cloud_ide_saas_url(user)
    "" unless user.logged?
    token = Token.get_token_from_user(user, "autologin")
    oauth_url = "#{Rails.application.config_for(:configuration)['platform_url']}/api/users/info.json"
    saas_url = EduSetting.get("cloud_ide_saas_url") || "https://saasfactory.test.opentrs.com"
    "#{saas_url}/oauth/login?product_account_id=PA1001218&tenant_code=TI1001383&oauth_url=#{oauth_url}&token=#{token.value}"
  end

  def ai_shang_v1_url(project)
    url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn"
    case project.identifier.to_s.downcase
    when nil                   then ""
    when 'rails'               then "#{url}/v1/rails/entropy"
    when 'jittor'              then "#{url}/v1/jittor/entropy"
    when 'paddle'              then "#{url}/v1/Paddle/entropy"
    when 'vue'                 then "#{url}/v1/vue/entropy"
    when 'bootstrap'           then "#{url}/v1/bootstrap/entropy"
    when 'tensorflow'          then "#{url}/v1/tensorflow/entropy"
    when 'kernel'              then "#{url}/v1/openeuler/entropy"
    when 'opengauss-server'    then "#{url}/v1/opengauss/entropy"
    when 'mindspore'          then "#{url}/v1/mindspore/entropy"
    when 'openharmony'          then "#{url}/api/openharmony/entropy"
    when 'openeuler'          then "#{url}/api/openeuler/entropy"
    when 'xiuos'          then "#{url}/api/xiuos/entropy"
    else ''
    end
  end

  def ai_shang_v2_url(project)
    url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn"
    case project.identifier.to_s.downcase
    when nil                   then ""
    when 'rails'               then "#{url}/v2/getMediumData?repo_login=rails&repo_name=rails"
    when 'jittor'              then "#{url}/v2/getMediumData?repo_login=Jittor&repo_name=jittor"
    when 'paddle'              then "#{url}/v2/getMediumData?repo_login=PaddlePaddle&repo_name=Paddle"
    when 'vue'                 then "#{url}/v2/getMediumData?repo_login=vuejs&repo_name=vue"
    when 'bootstrap'           then "#{url}/v2/getMediumData?repo_login=twbs&repo_name=bootstrap"
    when 'tensorflow'          then "#{url}/v2/getMediumData?repo_login=tensorflow&repo_name=tensorflow"
    when 'kernel'              then "#{url}/v2/getMediumData?repo_login=openeuler&repo_name=kernel"
    when 'opengauss-server'    then "#{url}/v2/getMediumData?repo_login=opengauss&repo_name=openGauss-server"
    when 'mindspore'           then "#{url}/v2/getMediumData?repo_login=mindspore&repo_name=mindspore"
    else ''
    end
  end

  def ai_shang_v4_url(project)
    url = EduSetting.get("ai_shang_url") || "https://shang.gitlink.org.cn"
    case project.identifier.to_s.downcase
    when nil                   then ""
    when 'rails'               then "#{url}/v2/getIndexData?repo_login=rails&repo_name=rails"
    when 'jittor'              then "#{url}/v2/getIndexData?repo_login=Jittor&repo_name=jittor"
    when 'paddle'              then "#{url}/v2/getIndexData?repo_login=PaddlePaddle&repo_name=Paddle"
    when 'vue'                 then "#{url}/v2/getIndexData?repo_login=vuejs&repo_name=vue"
    when 'bootstrap'           then "#{url}/v2/getIndexData?repo_login=twbs&repo_name=bootstrap"
    when 'tensorflow'          then "#{url}/v2/getIndexData?repo_login=tensorflow&repo_name=tensorflow"
    when 'kernel'              then "#{url}/v2/getIndexData?repo_login=openeuler&repo_name=kernel"
    when 'opengauss-server'    then "#{url}/v2/getIndexData?repo_login=opengauss&repo_name=openGauss-server"
    when 'mindspore'           then "#{url}/v2/getIndexData?repo_login=mindspore&repo_name=mindspore"
    else ''
    end
  end

  def ai_shang_v3_url(project)
    url = EduSetting.get("ai_shang_v3_url") || "https://shang.gitlink.org.cn/v3"
    case project.identifier.to_s.downcase
    when nil                   then ""
    when 'rails'               then "#{url}/rails/entropy"
    when 'jittor'              then "#{url}/jittor/entropy"
    when 'paddle'              then "#{url}/paddle/entropy"
    when 'vue'                 then "#{url}/vue/entropy"
    when 'bootstrap'           then "#{url}/bootstrap/entropy"
    when 'tensorflow'          then "#{url}/tensorflow/entropy"
    when 'kernel'              then "#{url}/openeuler/entropy"
    when 'opengauss-server'    then "#{url}/opengauss/entropy"
    when 'mindspore'           then "#{url}/mindspore/entropy"
    else ''
    end
  end

  def aes_encrypt(key, des_text)
    # des_text='{"access_key_id":"STS.NTuC9RVmWfJqj3JkcMzPnDf7X","access_key_secret":"E8NxRZWGNxxMfwgt5nFLnBFgg6AzgXCZkSNCyqygLuHM","end_point":"oss-accelerate.aliyuncs.com","security_token":"CAIS8gF1q6Ft5B2yfSjIr5fACIPmu7J20YiaaBX7j2MYdt9Cq6Ocujz2IHhMenVhA+8Wv/02n2hR7PcYlq9IS55VWEqc/VXLaywQo22beIPkl5Gfz95t0e+IewW6Dxr8w7WhAYHQR8/cffGAck3NkjQJr5LxaTSlWS7OU/TL8+kFCO4aRQ6ldzFLKc5LLw950q8gOGDWKOymP2yB4AOSLjIx6lAt2T8vs/7hmZPFukSFtjCglL9J/baWC4O/csxhMK14V9qIx+FsfsLDqnUIs0YWpf0p3P0doGyf54vMWUM05A6dduPS7txkLAJwerjVl1/ADxc0/hqAASXhPeiktbmDjwvnSn4iKcSGQ+xoQB468eHXNdvf13dUlbbE1+JhRi0pZIB2UCtN9oTsLHcwIHt+EJaoMd3+hGwPVmvHSXzECDFHylZ8l/pzTwlE/aCtZyVmI5cZEvmWu2xBa3GRbULo7lLvyeX1cHTVmVWf4Nk6D09PzTU8qlAj","bucket":"edu-bigfiles1","region":"oss-cn-hangzhou","callback_url":"https://data.educoder.net/api/buckets/callback.json","bucket_host":"data.educoder.net"}'
    # des = OpenSSL::Cipher::Cipher.new('aes-256-ctr')
    des = OpenSSL::Cipher.new('AES-256-CBC')
    des.encrypt
    # des.padding =
    des.key = key
    des.iv = "5183666c72eec9e4"
    result = des.update(des_text)
    result << des.final
    Base64.strict_encode64 result
  end
end
