namespace :update_educoder_user do
  desc "update educoder user mail phone"
  task done: :environment do
    data = User.where("mail like '%***%' or phone like '%***%'")
    data = User.where(login: ENV['login']) if ENV['login'].present?
    data.each do |user|
      begin
        req_params = { "login" => "#{user.login}", "private_token" => "hriEn3UwXfJs3PmyXnqQ" }
        api_url = "https://data.educoder.net"
        client = Faraday.new(url: api_url)
        response = client.public_send("get", "/api/sources/get_user_info_by_login", req_params)
        result = JSON.parse(response.body)
        #查询
        next if result["status"].to_s != "0"

        # login 邮箱 手机号 姓名 学校/单位
        user_info = result["data"]
        Rails.logger.info("user_info====== #{user_info}")
        login = user_info["login"]
        email = user_info["mail"]
        phone = user_info["phone"]
        real_name = user_info["username"]
        department_name = user_info["school"]
        password = "12345678"

        user.update_columns(mail: "#{email}", phone: "#{phone}", lastname: real_name, nickname: real_name)

        sync_params = {
          email: email,
          login_name: user.login,
          source_id: 0
        }
        interactor = Gitea::User::UpdateInteractor.call(user.login, sync_params)
        if interactor.success?
          puts "success user: #{user.id} username:#{user.login}"
        else
          puts "error user: #{user.id} username:#{user.login}, error:#{interactor.error.to_s}"
        end

      rescue Exception => e
        puts "error user: #{user.id} username:#{user.login}, error:#{e}"
      end
    end
  end
end