#coding=utf-8

require 'base64'

class Sso < ActiveRecord::Base
  belongs_to :user
  attr_accessible :email, :name, :openid, :password, :school, :sex, :user, :user_id

  validates :user_id, :user, :email, :openid, :presence => true

  def self.sync_user(opt)
    sso = Sso.where(openid: opt["openid"]).first
    return sso if sso

    sso = Sso.new
    sso.name     = opt["name"]
    sso.openid   = opt["openid"]
    sso.email    = opt["email"]
    sso.password = opt["password"]
    sso.school   = opt["school"]
    sso.sex      = opt["sex"]


    # 查邮箱
    user = User.where(mail: opt["email"]).first

    unless user
      # 查用户名

      user = User.where(login: opt["name"]).first
      if user
        # 跳到修改用户名
        raise "exist user"
      end

      password = opt["password"]
      if password.size < 8
        password = random_pwd
      end
      us = UsersService.new
      user = us.register(login: opt["name"], mail: opt["email"],
                         password: password,
                         :should_confirmation_password => false)
      if user.new_record?
        raise user.errors.full_messages.first
      end
    end

    sso.user = user
    sso.save!
    return sso
  end


  private
  def self.random_pwd
    ('a'..'z').to_a.shuffle[0..7].join
  end

end
