class Api::V1::Users::UpdatePhoneService < ApplicationService
  include ActiveModel::Model 
  include AesCryptHelper

  attr_reader :user, :password, :phone, :code, :verify_code

  validates :password, :code, presence: true
  validates :phone, presence: true, format: { with: CustomRegexp::PHONE }

  def initialize(user, params)
    @user = user 
    @password = decrypt(params[:password]) rescue params[:password].to_s
    @phone = params[:phone]
    @code = params[:code]
    @verify_code = VerificationCode.where(phone: @phone, code_type: 4).last
  end

  def call 
    raise Error, "此用户禁止修改手机号." if @user.id.to_i === 104691
    raise Error, errors.full_messages.join(",") unless valid? 
    raise Error, "密码不正确." unless @user.check_password?(@password)
    exist_owner = Owner.find_by(phone: @phone)
    raise Error, "手机号已被使用." if exist_owner
    is_debug =  @code == "123123" && EduSetting.get("code_debug") # 万能验证码，用于测试 # TODO 万能验证码，用于测试
    raise Error, "验证码不正确." if @verify_code&.code != @code && !is_debug
    raise Error, "验证码已失效." if !@verify_code&.effective? && !is_debug

    begin
      ActiveRecord::Base.transaction do
        @user.update_attributes!({phone: @phone})
      end
      return true
    rescue
      raise Error, "服务器错误，请联系系统管理员！"
    end
  end
end