class AccountsController < ApplicationController

  include ErrorCommon
  #skip_before_action :check_account, :only => [:logout]

  def index
    render json: session
  end

  # 用户注册
  # 注意:用户注册需要兼顾本地版,本地版是不需要验证码及激活码以及使用授权的,注册完成即可使用
  # params[:login] 邮箱或者手机号
  # params[:code]  验证码
  # code_type 1:注册手机验证码  8:邮箱注册验证码
  def register
    begin
      # 查询验证码是否正确;type只可能是1或者8
      type = phone_mail_type(params[:login].strip)
      code = params[:code].strip

      if type == 1
        uid_logger("start register by phone:  type is #{type}")
        pre = 'p'
        email = nil
        phone = params[:login]
        verifi_code = VerificationCode.where(phone: phone, code: code, code_type: 1).last
      else
        uid_logger("start register by email:  type is #{type}")
        pre = 'm'
        email = params[:login]
        phone = nil
        verifi_code = VerificationCode.where(email: email, code: code, code_type: 8).last
      end
      uid_logger("start register:  verifi_code is #{verifi_code}, code is #{code}, time is #{Time.now.to_i - verifi_code.created_at.to_i}")
      check_code = (verifi_code.try(:code) == code.strip && (Time.now.to_i - verifi_code.created_at.to_i) <= 10*60)
      unless check_code
        tip_exception("验证码无效")
      end

      code = generate_identifier User, 8
      login = pre + code
      @user = User.new(admin: false, login: login, mail: email, phone: phone)
      @user.password = params[:password]
      # 现在因为是验证码,所以在注册的时候就可以激活
      @user.activate
      # 必须要用save操作,密码的保存是在users中
      if @user.save!
        # 注册完成,手机号或邮箱想可以奖励500金币
        RewardGradeService.call(
          @user,
          container_id: @user.id,
          container_type: pre == 'p' ? 'Phone' : 'Mail',
          score: 500
        )
      end
    rescue Exception => e
      uid_logger_error(e.message)
      tip_exception(-1, e.message)
    end
  end

  # 用户登录
  def login
    @user = User.try_to_login(params[:login], params[:password])
    @user.update_column(:last_login_on, Time.now)

    successful_authentication(@user)

    session[:user_id] = @user.id
  end

  # 忘记密码
  def reset_password
    begin
      code = params[:code]
      login_type = phone_mail_type(params[:login].strip)
      # 获取验证码
      if login_type == 1
        phone = params[:login]
        verifi_code = VerificationCode.where(phone: phone, code: code, code_type: 2).last
        user = User.find_by_phone(phone)
      else
        email = params[:login]
        verifi_code = VerificationCode.where(email: email, code: code, code_type: 3).last
        user = User.find_by_mail(email)     #这里有问题,应该是为email,而不是mail  6.13-hs
      end
      check_code = (verifi_code.try(:code) == code.strip && (Time.now.to_i - verifi_code.created_at.to_i) <= 10*60)
      unless check_code
        tip_exception("验证码无效")
      end

      user.password, user.password_confirmation = params[:new_password], params[:new_password_confirmation]
      if user.save!
        sucess_status
      end
    # rescue Exception => e
    #   uid_logger_error(e.message)
    #   tip_exception("密码重置失败,请稍后再试")
    end
  end

  def successful_authentication(user)
    uid_logger("Successful authentication start: '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}")
    # Valid user
    self.logged_user = user
    # generate a key and set cookie if autologin

    set_autologin_cookie(user)
    UserAction.create(:action_id => user.try(:id), :action_type => "Login", :user_id => user.try(:id))
  end

  def set_autologin_cookie(user)
    token = Token.get_or_create_permanent_login_token(user, "autologin")
    cookie_options = {
                      :value => token.value,
                      :expires => 1.month.from_now,
                      :path => '/',
                      :secure => false,
                      :httponly => true
                     }
    if edu_setting('cookie_domain').present?
      cookie_options = cookie_options.merge(domain: edu_setting('cookie_domain'))
    end
    cookies[autologin_cookie_name] = cookie_options
    logger.info("cookies is #{cookies}")
  end

  def logout
    UserAction.create(action_id: User.current.id, action_type: "Logout", user_id: User.current.id)
    session[:user_id] = nil
    logout_user
    render :json => {status: 1, message: "退出成功!"}
  end

  # 检验邮箱是否已被注册及邮箱或者手机号是否合法
  # 参数type为事件类型 1:注册;2:忘记密码
  def valid_email_and_phone
    check_mail_and_phone_valid(params[:login], params[:type])
  end

  # 发送验证码
  # params[:login]  手机号或者邮箱号
  # params[:type]为事件通知类型 1:用户注册注册 2:忘记密码 3: 绑定手机 4: 绑定邮箱 # 如果有新的继续后面加
  # 发送验证码:send_type 1:注册手机验证码 2:找回密码手机验证码 3:找回密码邮箱验证码 4:绑定手机 5:绑定邮箱
  # 6:手机验证码登录 7:邮箱验证码登录 8:邮箱注册验证码
  def get_verification_code
    code = %W(0 1 2 3 4 5 6 7 8 9)
    value = params[:login]
    type = params[:type].strip.to_i
    login_type = phone_mail_type(value)
    send_type = verify_type(login_type, type)
    verification_code = code.sample(6).join

    # 记录验证码
    check_verification_code(verification_code, send_type, value)
    sucess_status
  end

  # 1 手机类型;0 邮箱类型
  # 注意新版的login是自动名生成的
  def phone_mail_type value
    value =~ /^1\d{10}$/ ? 1 : 0
  end

  private
  def autologin_cookie_name
    edu_setting('autologin_cookie_name') || 'autologin'
  end

  def logout_user
    if User.current.logged?
      if autologin = cookies.delete(autologin_cookie_name)
        User.current.delete_autologin_token(autologin)
      end
      User.current.delete_session_token(session[:tk])
      self.logged_user = nil
    end
    session[:user_id] = nil
  end

  # type 事件类型 1:用户注册 2:忘记密码 3: 绑定手机 4: 绑定邮箱 # 如果有新的继续后面加
  # login_type 1:手机类型 2:邮箱类型
  def verify_type login_type, type
    case type
    when 1
      login_type == 1 ? 1 : 8
    when 2
      login_type == 1 ? 2 : 3
    when 3
      login_type == 1 ? 4 : tip_exception('请填写正确的手机号')
    when 4
      login_type == 1 ? tip_exception('请填写正确的邮箱') : 5
    end
  end

end