namespace :shixun do
  namespace :sync do
    desc "sync users to gitlab"
    task :myshixun => :environment do
      shixun_tomcat = Redmine::Configuration['shixun_tomcat']
      Shixun.all.each do |shixun|
        begin
          puts("shixun id is #{shixun.id}")
          tpiList =[]
          gameInfo = shixun.gameInfo
          myshixuns = shixun.myshixuns
          if myshixuns.present?
            myshixuns.each do |myshixun|
              puts("tpiID is #{myshixun.id}")
              tpiID = myshixun.id
              login = User.where(:id =>  myshixun.try(:user_id)).first.try(:login)
              rep_identify = Repository.where(:myshixun_id => myshixun.id, :type => "Repository::Gitlab").first.try(:identifier)
              gitlab_address = Redmine::Configuration['gitlab_address_ip']
              instanceGitURL = gitlab_address.to_s+"/"+login+"/"+ rep_identify + "."+"git"
              puts("instanceGitURL is #{instanceGitURL}")
              tpiList << {:tpiID => tpiID, :instanceGitURL => instanceGitURL}
              puts("###############{tpiList.to_json unless tpiList.blank?}")
              tpiList = Base64.urlsafe_encode64(tpiList.to_json) unless tpiList.blank?
              puts("************#{tpiList}")
            end
          end
          params = {:gameInfo => "#{gameInfo}", :tpiList => "#{tpiList}" }
          puts("params is #{params}")
          uri = URI("#{shixun_tomcat}/bridge/dataTransfer/transfer")
          uri = URI.parse(URI.encode("#{shixun_tomcat}/bridge/game/gameEvaluate".strip))
          puts("uri is #{uri}")
          res = Net::HTTP.post_form(uri, params).body
          res = JSON.parse(res)
          puts("=====res is #{res['code']}")
        rescue Exception => e
          puts("error ====> #{e.message}")
        end
      end
    end
  end
end