# encoding:utf-8
#微信用户表
require 'redis'
class WxUser < ActiveRecord::Base
  has_paper_trail
  self.table_name = "wx_users"
  scope :所有会员, -> {}
  scope :代理, -> { where("rank=? and show_invite_mode=?",1,1) }
  scope :店长, -> { where("rank=? and show_invite_mode=?",2,1) }
  scope :区域代理, -> { where("rank=? and show_invite_mode=?",3,1) }


  belongs_to :user
  #has_many :channel_qrcode_results, :foreign_key => :mp_openid
  belongs_to :parent_signup_channel, :foreign_key => :channel_qrcode_id
  belongs_to :depart_record, :foreign_key => :depart

  validates_presence_of :nickname, :unionid
  #belongs_to :channel_qrcode
  attr_accessor :invite, :v_head, :intro_user
  before_save :up_wxuser_relation
  def up_wxuser_relation
    wxUser = WxUser.where("id = ?", self.id).first
    if !wxUser.blank?
      if wxUser.invite_id != self.invite_id
        #修改下属会员推荐关系
        url = "#{CONFIG_FILE["app_host"]}/v1/cron/comb_three_user"
        p url
        open(url)
      end
    end
  end
  SEX_ENUM= [["未知","0"], ["男性","1"], ["女性", "2"]]
  DEPART_ENUM= [["部门1",1], ["部门2",2], ["部门3", 3], ["部门4", 4], ["部门5", 5]]

  RANK_ENUM= [["普通会员","0"], ["群主","1"], ["店长", "2"], ["区域代理", "3"]]

  COPARTNET_STATE_ENUM = [["否",0],["是",1],["曾经是",2]]

  IMG_STORE_PATH = "wx_user"

  after_destroy :after_destroy


  def invite
    wu = WxUser.where("id = ?", invite_id).first
    if !wu.blank?
      return wu.nickname
    end
  end

  def intro_user
    wu = WxUser.where("id = ?", intro_user_id).first
    if !wu.blank?
      return wu.nickname
    end
  end

  def tel
    if self.user_id.to_i >0
      u = User.where("id=?",self.user_id).first
      return if u.blank?
      return u.tel
    end
  end

  def gzhOpenid
    if self.id.to_i >0
      u = WxUserGongzhonghao.where("wx_user_id=?",self.id).first
      return if u.blank?
      return u.gzh_open_id
    end
    return "-"
  end
  def gzhIsSub
    if self.id.to_i >0
      u = WxUserGongzhonghao.where("wx_user_id=?",self.id).first
      return false if u.blank?
      return u.subscribe
    end
    return false
  end
  def gzhSubTime
    if self.id.to_i >0
      u = WxUserGongzhonghao.where("wx_user_id=?",self.id).first
      return "-" if u.blank? || u.subscribe_time.blank? || u.subscribe_time == nil
      return Time.at(u.subscribe_time) if u.subscribe_time != nil
    end
    return "-"
  end
  def gzhUnSubTime
    if self.id.to_i >0
      u = WxUserGongzhonghao.where("wx_user_id=?",self.id).first
      return "-" if u.blank? || u.unsubscribe_time.blank? || u.unsubscribe_time == nil
      return Time.at(u.unsubscribe_time) if u.unsubscribe_time != nil
    end
    return "-"
  end
  def gzhLastConversationTime
    if self.id.to_i >0
      u = WxUserGongzhonghao.where("wx_user_id=?",self.id).first
      return "-" if u.blank? || u.last_conversation_at.blank? || u.last_conversation_at == nil
      return Time.at(u.last_conversation_at) if u.last_conversation_at != nil
    end
    return "-"
  end
  

  rails_admin do
    navigation_label '用户管理'
    # parent User
    weight -300

    list do
      scopes [nil,:代理,:店长,:区域代理]
      filters [:id,:user_id,:nickname, :city, :parent_signup_channel, :sale_group, :sale_group_sum,:active_nums,:depart]
      field :id
      field :user_id do
        filterable true
      end
      field :tel
      # field :gzhOpenid
      field :gzhIsSub, :boolean
      field :gzhSubTime     
      field :gzhUnSubTime      
      field :gzhLastConversationTime      
      field :nickname
      field :invite_id
      field :intro_user_id
      field :sex, :enum do
        enum do
          SEX_ENUM
        end
      end
      field :head do
        formatted_value do
          bindings[:view].tag(:img,{:src => bindings[:object].get_head_img,
          :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px',
          :onClick => "javascript:window.open('#{bindings[:object].get_head_img}')"})
        end
      end
      # field :openid
      # field :unionid
      # field :province
      field :city
      # field :signup_ip
      field :parent_signup_channel
      field :show_invite_mode
      field :rank, :enum do
        enum do
          RANK_ENUM
        end
      end
      field :sale_group
      field :sale_group_sum
      field :depart do
        visible false
        filterable true
      end
      field :depart_record
      field :active_nums
      # field :channel_qrcode_id
      field :created_at
    end

    show do
      field :id
      field :user
      field :user_id
      field :nickname
      field :invite
      field :invite_id
      field :intro_user
      field :intro_user_id
      field :sex, :enum do
        enum do
          SEX_ENUM
        end
      end
      field :head do
        formatted_value do
          bindings[:view].tag(:img,{:src => bindings[:object].get_head_img,
          :style => 'width: 100px;height: 100px;cursor: pointer;display: block;max-width: 100px',
          :onClick => "javascript:window.open('#{bindings[:object].get_head_img}')"})
        end
      end

      field :unionid
      field :openid
      field :gzhOpenid
      field :gzhIsSub, :boolean
      field :gzhSubTime     
      field :gzhUnSubTime      
      field :gzhLastConversationTime
      field :province
      field :city
      field :signup_ip
      # field :subscribe
      # field :subscribe_time do
      #   formatted_value do
      #     (value !=nil || value != 0) ? Time.at(value):Time.now
      #   end
      # end
      # field :unsubscribe_time do
      #   formatted_value do
      #     (value !=nil || value != 0) ? Time.at(value):Time.now
      #   end
      # end
      # field :last_conversation_at do
      #   formatted_value do
      #     (value !=nil || value != 0) ? Time.at(value):Time.now
      #   end
      # end
      # field :channel_qrcode_id
      field :invite_qrcode_url
      field :show_invite_mode
      field :rank, :enum do
        enum do
          RANK_ENUM
        end
      end
      field :parent_signup_channel
      field :sale_group
      field :sale_group_sum
      field :depart do
        visible false
        filterable true
      end
      field :depart_record
      field :active_nums
      field :tc_bl
      field :tc_area
      field :created_at
    end

    edit do
      field :user_id
      field :nickname
      # field :unionid
      field :city
      field :country
      field :province
      field :sex, :enum do
        enum do
          SEX_ENUM
        end
      end
      field :v_head, :file_upload do
        pretty_value do
          bindings[:view].tag(:img, {:src => bindings[:object].get_head_img, :class => 'preview'})
        end
      end
      # field :subscribe
      # field :unsubscribe_time, :datetime do
      #   formatted_value do
      #     (value.blank?) ? Time.at(0) : Time.at(value)
      #   end
      # end
      # field :subscribe_time, :datetime do
      #   formatted_value do
      #     (value.blank?) ? Time.at(0) : Time.at(value)
      #   end
      # end
      # field :last_conversation_at
      field :invite_id
      field :signup_ip
      field :channel_qrcode_id
      field :invite_qrcode_url
      field :show_invite_mode
      field :rank, :enum do
        enum do
          RANK_ENUM
        end
      end
      field :depart
      field :active_nums

      field :tc_bl
      field :tc_area do
        label "提成区域,多个区域请用用英文逗号分隔"
      end
    end

    export do
      include_all_fields

      field :intro_area do
        visible false
      end
      field :intro_inner_no do
        visible false
      end
      field :depth do
        visible false
      end
      field :partner_time do
        visible false
      end
      field :sale_person do
        visible false
      end
      field :sale_score do
        visible false
      end
      field :user_no do
        visible false
      end
    end

  end
  def get_head_img
    url = "http://#{Ali::Oss::CDN_URL_FOR_HOST}/#{self.head}"
    return url
  end

  def v_head=file
    unless file.blank?
      clear_head_img
      file_name = "#{UUID.new.generate[0...8].downcase}.jpg"
      file_path = "#{IMG_STORE_PATH}/#{file_name}"
      Ali::Oss.store(Ali::Oss::BUCKET_NAME_PUBLIC_READ, file_path, file.read)
      self.head = file_path
      self.save
    end
  end

  def clear_head_img
    file_path = "#{self.head}"
    Ali::Oss.delete_object(Ali::Oss::BUCKET_NAME_PUBLIC_READ, file_path)
  end

  def after_destroy
    clear_head_img
  end


end
