class Admin::MembersController < OrbitMemberController
  before_action :show_member_profile, only: [:show, :edit, :update, :edit_passwd, :edit_privilege]
  before_action :check_password_reset

  helper MemberHelper
  helper OrbitBackendHelper
  Rack::Utils.key_space_limit = 5000000
  require 'spreadsheet'
  require 'rubyXL'
  require 'fileutils'
  load File.expand_path(__dir__)+'/zipgenerator.rb'
  def sort_role_attr_field
    Role.all.map{|v| v}.each do |role|
      role.attribute_fields.asc(:id).each_with_index do |attribute_field,index1|
        key = attribute_field.key
        if key.to_i.to_s != key.to_s
          attr_f = attribute_field
          attr_f.key = index1 + 1
          attr_f.save
        end 
      end
    end
    MemberInfo.all.each do |member_info|
      member_info.member_profile_fields.each_with_index do |attribute_field,index1|
        key = attribute_field.key
        if key.to_i.to_s != key.to_s
          attr_f = attribute_field
          attr_f.key = index1 + 1
          attr_f.save
        end 
      end
    end
  end
  def index
    @roles = Role.excludes(disabled: true)
    @member_tags = MemberTag.all
    page_num = params[:page] || 1
    param_temp = request.fullpath.split("?")
    @edit_params = (param_temp.count > 1 ? "?" + param_temp.last : "") rescue ""

  	@filter = params[:filter]
    @mq = params[:mq]
    @new_filter = params[:new_filter]

    if @filter && params[:clear]
      @filter.delete(params[:type])
    elsif @filter && @new_filter
      if @filter.has_key?(@new_filter[:type]) && @filter[@new_filter[:type]].include?(@new_filter[:id].to_s)
        @filter[@new_filter[:type]].delete(@new_filter[:id].to_s)
      elsif @filter.has_key?(@new_filter[:type])
        @filter[@new_filter[:type]] << @new_filter[:id].to_s
      else
        @filter.merge!({@new_filter[:type] => [@new_filter[:id].to_s]})
      end
    elsif @new_filter
      @filter = {@new_filter[:type] => [@new_filter[:id].to_s]}
    end

    render_401 and return if current_user.nil? || !current_user.is_approved?

    if @filter.blank? and @mq.blank?

      render case params[:at]
        when 'summary'
          @members = MemberProfile.all.page(page_num).per(12).desc("_id")
          "index_summary"
        when 'thumbnail'
          @members = MemberProfile.all.page(page_num).per(36).desc("_id")
          "index_thumbnail"
        else
          @members = MemberProfile.all.page(page_num).per(10).desc("_id")
          "index"
      end

    elsif @filter.blank? and !@mq.blank?

      render case params[:at]
        when 'summary'
          @members=MemberProfile.all.any_of({:user_id => /#{@mq}/i}, {:first_name => /#{@mq}/i}, {:last_name => /#{@mq}/i}, {:email => /#{@mq}/i}, {:office_tel => /#{@mq}/i}).desc("_id")
          "index_summary"
        when 'thumbnail'
          @members=MemberProfile.all.any_of({:user_id => /#{@mq}/i}, {:first_name => /#{@mq}/i}, {:last_name => /#{@mq}/i}, {:email => /#{@mq}/i}, {:office_tel => /#{@mq}/i}).desc("_id")
          "index_thumbnail"
        else
          @members=MemberProfile.all.any_of({:user_id => /#{@mq}/i}, {:first_name => /#{@mq}/i}, {:last_name => /#{@mq}/i}, {:email => /#{@mq}/i}, {:office_tel => /#{@mq}/i}).desc("_id")
          "index"
      end

    elsif !@filter.blank? && @mq.blank?
	  @filter_role = @filter['role'].flat_map{|role_id| (role_id == 'no_role') ? [[],nil] : role_id} if !@filter['role'].nil?
	  @filter_tag = @filter['tag'].flat_map{|tag_id| (tag_id == 'no_tag') ? [[],nil] : tag_id} if !@filter['tag'].nil?
      render case params[:at]
        when 'summary'
          case (@new_filter["type"] rescue @filter.keys.first)
          when "role"
            @members=MemberProfile.all.any_in(:role_ids=>@filter_role).page(page_num).per(12).desc("_id")
            "index_summary"
          when "tag"
            @members=MemberProfile.all.any_in(:member_tag_ids=>@filter_tag).page(page_num).per(12).desc("_id")
            "index_summary"
          end
        when 'thumbnail'
          case (@new_filter["type"] rescue @filter.keys.first)
          when "role"
            @members=MemberProfile.all.any_in(:role_ids=>@filter_role).page(page_num).per(36).desc("_id")
            "index_thumbnail"
          when "tag"
            @members=MemberProfile.all.any_in(:member_tag_ids=>@filter_tag).page(page_num).per(36).desc("_id")
            "index_thumbnail"
          end
        else
          case (@new_filter["type"] rescue @filter.keys.first)
          when "role"
            @members=MemberProfile.all.any_in(:role_ids=>@filter_role).page(page_num).per(10).desc("_id")
            "index"
          when "tag"
            @members=MemberProfile.all.any_in(:member_tag_ids=>@filter_tag).page(page_num).per(10).desc("_id")
            "index"
          end
      end

    end

  end

  def show
    @custom_fields = @member.member_profile_field_values rescue []
    if current_site.personal_plugins_sort.blank?
      @plugins = OrbitApp::Plugin::Registration.all rescue nil
    else
      plugin_list = OrbitApp::Plugin::Registration.all.collect{|p| p.module_app_name}
      plugin_list = current_site.personal_plugins_sort | plugin_list
      @plugins = OrbitApp::Plugin::Registration.sort_by_array(plugin_list) rescue nil
    end
    # @ppname = Array.new
    # @plugins.each do |aa|
    #   @ppname << [aa.sort_number.to_i, [aa.name, aa.app_name, aa.intro_app_name, aa.front_partial_path]]
    # end
    @plugin_shows = @plugins.collect {|v| {"name"=>v.name,"app_name"=>v.app_name,"intro_app_name"=>v.intro_app_name,"front_partial_path"=>v.front_partial_path, "count" =>  (v.app_name.classify.constantize.where(:member_profile_id => @member.id).count rescue 0)} }
    if(!params[:show_plugin_profile].nil?)
      @right_partial = OrbitApp::Plugin::Registration.find_by_app_name(params[:show_plugin_profile]).profile_partial_path rescue 'plugin_summary'
      @plugin_app_name = OrbitApp::Plugin::Registration.find_by_app_name(params[:show_plugin_profile]).name rescue nil
    else
      @right_partial = "new_profile_partial"
      @plugin_app_name = ''
    end

    get_info_and_roles
    render_401 and return if current_user.nil? || (@member.id.to_s != current_user.member_profile.id.to_s && !current_user.is_approved?)
  end


  def make_alpha_from_numbers(number)

    @numeric = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if number < @numeric.size
      @a = @numeric[number]
    else
      @dev_by = (number/@numeric.size).floor
      @a = "#{make_alpha_from_numbers(@dev_by-1)}#{make_alpha_from_numbers(number-(@dev_by*@numeric.size))}";
    end
  end


  def import_data_check(tempfile,filename)
    profile_data_row = ["user_id","password","email","sid","office_tel","sex","birthday","avatar"]
	profile_lang_data_row = ["first_name","last_name","address","autobiography","fax","mobile_no"]
    @field_type = {'text_field' => 'typeA', 'select' => 'typeB', 'date' => 'typeC', 'text_area' => 'typeD', 'radio_button' => 'typeE', 'checkbox' => 'typeE', 'address' => ''}
    @date_type = {'format1' => '%Y/%m/%d %H:%M', 'format2' => '%Y/%m/%d', 'format3' => '%Y/%m', 'format4' => '%Y'}
    @error_msg = Array.new
	@filename = filename.nil? ? tempfile.path : filename
	begin
		workbook = RubyXL::Parser.parse(tempfile)
	rescue 
		@error_msg << filename+'格式錯誤'
		return @error_msg
	end
    sheet = workbook['Member'].sheet_data.rows
    sheet.each_with_index do |raw_row,index|
	  begin
		row = raw_row.cells.map{ |cell| cell.value rescue nil}
	  rescue
		(@error_msg << filename+'格式錯誤')
		return @error_msg
	  end
      if index == 0
        @field_data = row
      end
	  if index == 1
		@row_index_hash = {}
		profile_data_row.each do |row_key|
			@row_index_hash[row_key] = @field_data.index(row_key)
		end
		profile_lang_data_row.each do |lang_row_key|
			current_site.in_use_locales.each do |locale_name|
				@row_index_hash[lang_row_key+"(#{locale_name})"] = @field_data.index(lang_row_key+"(#{locale_name})")
			end
		end
	  end
      if index > 2
		@user_id = row[@row_index_hash['user_id']]
		@name_lang = current_site.in_use_locales.map{|locale| ['first_name','last_name'].map{|name| row[@row_index_hash["#{name}(#{locale})"]].strip rescue ''}.select{|field| !field.blank? && !field.nil?}}
		#@error_msg << current_site.in_use_locales.map{|locale| ['first_name','last_name'].map{|name| row[@row_index_hash["#{name}(#{locale})"]].strip rescue ''}.select{|field| !field.blank? && !field.nil?}}
		if !@user_id.blank?
			if !@name_lang.select{|field| !field.empty?}.empty?
				check_id = User.where(:user_name => @user_id).first
				 # @error_msg << @filename+"中#{make_alpha_from_numbers(@field_data.index('user_id'))}#{index+1}欄位帳號已存在。" if !check_id.blank?
				@error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash['user_id'])}#{index+1}欄位格式不符(長度不足，請超過3個字)。" if @user_id.size < 3
				@password = row[@row_index_hash['password']]
				if !@password.blank?
				  @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash['password'])}#{index+1}欄位格式不符(長度不足，請至少8碼以上)。" if @password.to_s.size < 8
				elsif @password.blank? && User.where(:user_name => @user_id).first.nil?
				  @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash['password'])}#{index+1}欄位格式不符，請填入使用者密碼，以建立該位於#{make_alpha_from_numbers(@row_index_hash['user_id'])}#{index+1}欄位的使用者。"
				end
			else
				@empty_locales = []
				@name_lang.each_with_index{|empty_locale,i| (empty_locale.empty?) ? (@empty_locales << current_site.in_use_locales[i]) : nil}
				@empty_locales.each do |empty_locale|
					@name_fields_position = ['first_name','last_name'].map{|name| make_alpha_from_numbers(@row_index_hash["#{name}(#{empty_locale.to_s})"])}
					@error_msg << @filename+"中#{@name_fields_position.join((index+1).to_s+'或')}#{index+1}欄位(#{I18n.t(empty_locale)}#{I18n.t('users.name')}})格式不符，該橫列(#{index+1}列)中有會員名(user_id欄位有值)，故該橫列(#{index+1}列)之名稱不可為空。"
				end
			end
		end
        @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash['birthday'])}#{index+1}欄位日期格式不符。" if row[@row_index_hash["birthday"]].class.to_s != 'DateTime' and !row[@row_index_hash['birthday']].blank?



        @infos = MemberInfo.all
        @infos.each do |info|
          info.member_profile_fields.each do |member_profile_field|



            if member_profile_field.markup == 'select' or member_profile_field.markup == 'radio_button'

              @option_list = member_profile_field[@field_type[member_profile_field.markup]]['option_list'].collect{|p| p[0]}

              @rowname = "#{info.key}-#{member_profile_field.key}"
			  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
              @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash[@rowname])}#{index+1}欄位格式不符。" if !@option_list.include?("#{row[@row_index_hash[@rowname]]}") && !row[@row_index_hash[@rowname]].blank?

            elsif member_profile_field.markup == 'checkbox'

              @rowname = "#{info.key}-#{member_profile_field.key}"
			  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
              @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash[@rowname])}#{index+1}欄位格式不符。" if row[@row_index_hash[@rowname]].to_s.split(',').last != row[@row_index_hash[@rowname]] && !row[@row_index_hash[@rowname]].blank?

            elsif member_profile_field.markup == 'date'
              @rowname = "#{info.key}-#{member_profile_field.key}"
			  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
              @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash[@rowname])}#{index+1}欄位日期格式不符。" if row[@row_index_hash[@rowname]].class.to_s != 'DateTime' && !row[@row_index_hash[@rowname]].blank?
            end

          end

        end


        @roles = Role.all
        @roles.each do |role|

          role_statuses = RoleStatus.where(role_id: role.id, :disable=> false)
		  role_name = role.key
          if !role_statuses.blank?
            @rowname = "#{role.key}-status"
			@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
            if !@row_index_hash[@rowname].blank?
              @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash[@rowname])}#{index+1}欄位格式不符。" if row[@row_index_hash[@rowname]].to_s.split(',').last != row[@row_index_hash[@rowname]] && !row[@row_index_hash[@rowname]].blank?
            end
          end

          role.attribute_fields.asc(:created_at).each do |attribute_field|


            if attribute_field.markup == 'select' or attribute_field.markup == 'radio_button'

              @option_list = attribute_field[@field_type[attribute_field.markup]]['option_list'].collect{|p| p[0]}

              @rowname = "#{role.key}-#{attribute_field.key}"
			  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
              if !@field_data.index(@rowname).blank?
                @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash[@rowname])}#{index+1}欄位格式不符。" if !@option_list.include?("#{row[@row_index_hash[@rowname]]}") && !row[@row_index_hash[@rowname]].blank?
              end

            elsif attribute_field.markup == 'checkbox'
              @rowname = "#{role.key}-#{attribute_field.key}"
			  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
              if !@row_index_hash[@rowname].blank?
                @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash[@rowname])}#{index+1}欄位格式不符。" if row[@row_index_hash[@rowname]].to_s.split(',').last != row[@row_index_hash[@rowname]] && !row[@row_index_hash[@rowname]].blank?
              end
            elsif attribute_field.markup == 'date'
              @rowname = "#{role.key}-#{attribute_field.key}"
			  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
              if !@row_index_hash[@rowname].blank?
                @error_msg << @filename+"中#{make_alpha_from_numbers(@row_index_hash[@rowname])}#{index+1}欄位日期格式不符。" if row[@row_index_hash[@rowname]].class.to_s != 'DateTime' && !row[@row_index_hash[@rowname]].blank?
              end
            end

          end

        end

      end
    end
	 return @error_msg
  end
  def export_members
  end
  def read_xlsx_temp_file_and_import_members(tempfile,unzip_path = nil,filename = nil)
	@text = ''
	if !tempfile.blank?
		@error_msg = import_data_check(tempfile,filename)
		if @error_msg.blank?
			@members_list_tmp = []
			profile_data_row = ["user_id","password","email","sid","office_tel","sex","birthday","avatar"]
		    profile_lang_data_row = ["first_name","last_name","address","autobiography","fax","mobile_no"]
			@field_type = {'text_field' => 'typeA', 'select' => 'typeB', 'date' => 'typeC', 'text_area' => 'typeD', 'radio_button' => 'typeE', 'checkbox' => 'typeE', 'address' => ''}
			@date_type = {'format1' => '%Y/%m/%d %H:%M', 'format2' => '%Y/%m/%d', 'format3' => '%Y/%m', 'format4' => '%Y'}
			workbook = RubyXL::Parser.parse(tempfile)
			sheet = workbook['Member'].sheet_data.rows
			sheet.each_with_index do |raw_row,index|
				row = raw_row.cells.map{ |cell| cell.value rescue nil}
				if index == 0
				  @field_data = row
				end
				if index == 1
					@row_index_hash = {}
					profile_data_row.each do |row_key|
						@row_index_hash[row_key] = @field_data.index(row_key)
					end
					profile_lang_data_row.each do |lang_row_key|
						current_site.in_use_locales.each do |locale_name|
							@row_index_hash[lang_row_key+"(#{locale_name})"] = @field_data.index(lang_row_key+"(#{locale_name})")
						end
					end
				end
				if index > 2
					@member_profile = MemberProfile.new
					@site_in_use_locales.each_with_index do |locale, i|
					 # profile_lang_data_row.each do |profile_lang|
						  #(@member_profile.send(profile_lang+'_translations'+'=' , @member_profile.send(profile_lang+'_translations').merge("#{locale}" => row[@field_data.index("#{profile_lang}(#{locale})")]))) if !row[@field_data.index("#{profile_lang}(#{locale})")].blank?
						  @member_profile.first_name_translations = @member_profile.first_name_translations.merge!( "#{locale}" => row[@row_index_hash["first_name(#{locale})"]]) if !row[@row_index_hash["first_name(#{locale})"]].blank?
						  @member_profile.last_name_translations = @member_profile.last_name_translations.merge!( "#{locale}" => row[@row_index_hash["last_name(#{locale})"]]) if !row[@row_index_hash["last_name(#{locale})"]].blank?
						  @member_profile.address_translations = @member_profile.address_translations.merge!( "#{locale}" => row[@row_index_hash["address(#{locale})"]]) if !row[@row_index_hash["address(#{locale})"]].blank?
						  @member_profile.autobiography_translations = @member_profile.autobiography_translations.merge!( "#{locale}" => row[@row_index_hash["autobiography(#{locale})"]]) if !row[@row_index_hash["autobiography(#{locale})"]].blank?
					 # end
					end
					@member_profile.email = row[@row_index_hash["email"]]
					@member_profile.sid = row[@row_index_hash["sid"]]
					@member_profile.office_tel = row[@row_index_hash["office_tel"]]
					@member_profile.sex = ( row[@row_index_hash["sex"]] == 'male' or row[@row_index_hash["sex"]] == 'female' ) ? row[@row_index_hash["sex"]] : 'unknown'
					@member_profile.birthday = row[@row_index_hash["birthday"]].class.to_s == 'DateTime' ? row[@row_index_hash["birthday"]] : ''
					@avatar = row[@row_index_hash["avatar"]] rescue ''
					if @avatar != '' && !@avatar.nil?
						@cache_dir = @member_profile.avatar.cache_dir
						FileUtils.cp @avatar,@cache_dir
						Dir.chdir(@cache_dir) do
							@member_profile.avatar = File.open(@avatar)
						end
					end
					@member = @members_list.select{|member| member.name == @member_profile.name}.first
					if !@member.nil?
						@member_profile = @member
					else
						@member_profile.save
						@members_list_tmp << @member_profile
					end
					@infos = MemberInfo.all
					@infos.each do |info|
					  info.member_profile_fields.each do |member_profile_field|
						value = member_profile_field.member_profile_field_values.build
						value.member_profile_id = @member_profile.id
						if member_profile_field.markup == 'text_field' or member_profile_field.markup == 'text_area'
						  if member_profile_field[@field_type[member_profile_field.markup]]['cross_lang'] == 'true'
							@rowname = "#{info.key}-#{member_profile_field.key}"
							@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
							value["val"] = row[@row_index_hash[@rowname]] if !row[@row_index_hash[@rowname]].blank?
						  else
							@site_in_use_locales.each_with_index do |locale, i|
							  @rowname = "#{info.key}-#{member_profile_field.key}(#{locale})"
							  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
							  value["#{locale}"] = row[@row_index_hash[@rowname]] if !row[@row_index_hash[@rowname]].blank?
							end
						  end
						elsif member_profile_field.markup == 'checkbox'
						  @rowname = "#{info.key}-#{member_profile_field.key}"
						  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
						  value["val"] = row[@row_index_hash[@rowname]].to_s.split(',') if !row[@row_index_hash[@rowname]].blank?
						elsif member_profile_field.markup == 'date'
						  @rowname = "#{info.key}-#{member_profile_field.key}"
						  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
						  value["val"] = row[@row_index_hash[@rowname]].class.to_s == 'DateTime' ? row[@row_index_hash[@rowname]].to_datetime.strftime(@date_type[member_profile_field['typeC']['format']]) : ''
						elsif member_profile_field.markup == 'address'
						  @site_in_use_locales.each_with_index do |locale, i|
							@rowname = "#{info.key}-#{member_profile_field.key}(#{locale})"
							@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
							value["#{locale}"] = row[@row_index_hash[@rowname]] if !row[@row_index_hash[@rowname]].blank?
						  end
						else
						  @rowname = "#{info.key}-#{member_profile_field.key}"
						  @row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
						  value["val"] = "#{row[@row_index_hash[@rowname]]}"
						end
						value.save
					  end
					end
					@role_status_data = []
					@roles = Role.all
					@roles.each do |role|
						role_statuses = RoleStatus.where(role_id: role.id, :disable=> false).asc(:_id)
						if !role_statuses.blank?
							@rowname = "#{role.key}-status"
							@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
							if !@row_index_hash[@rowname].blank?
								if !row[@row_index_hash[@rowname]].blank?
									@status_value = row[@row_index_hash[@rowname]].to_s.split(',')
									role_statuses.each do |role_status|
										if @status_value.include?(role_status.key)
											@role_status_data << role_status.id
										end
									end
								end
							end
						end
						@role_add_value = 0
						role.attribute_fields.asc(:created_at).each do |attribute_field|
							value = attribute_field.attribute_values.build
							value.member_profile_id = @member_profile.id
							if attribute_field.markup == 'text_field' or attribute_field.markup == 'text_area'
								if attribute_field[@field_type[attribute_field.markup]]['cross_lang'] == 'true'
									@rowname = "#{role.key}-#{attribute_field.key}"
									@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
									if !@row_index_hash[@rowname].blank?
										if !row[@row_index_hash[@rowname]].blank?
											value["val"] = row[@row_index_hash[@rowname]]
											@role_add_value = @role_add_value + 1
										end
									end
								else
									@site_in_use_locales.each_with_index do |locale, i|
										@rowname = "#{role.key}-#{attribute_field.key}(#{locale})"
										@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
										if !@row_index_hash[@rowname].blank?
											if !row[@row_index_hash[@rowname]].blank?
												value["#{locale}"] = row[@row_index_hash[@rowname]]
												@role_add_value = @role_add_value + 1
											end
										end
									end
								end
							elsif attribute_field.markup == 'checkbox'
								@rowname = "#{role.key}-#{attribute_field.key}"
								@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
								if !@row_index_hash[@rowname].blank?
									if !row[@row_index_hash[@rowname]].blank?
									  value["val"] = row[@row_index_hash[@rowname]].to_s.split(',')
									  @role_add_value = @role_add_value + 1
									end
								end
							elsif attribute_field.markup == 'date'
								@rowname = "#{role.key}-#{attribute_field.key}"
								@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
								if !@row_index_hash[@rowname].blank?
									value["val"] = row[@row_index_hash[@rowname]].class.to_s == 'DateTime' ? row[@row_index_hash[@rowname]].to_datetime.strftime(@date_type[attribute_field['typeC']['format']]) : ''
								end
							elsif attribute_field.markup == 'address'
								@site_in_use_locales.each_with_index do |locale, i|
									@rowname = "#{role.key}-#{attribute_field.key}(#{locale})"
									@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
									if !@row_index_hash[@rowname].blank?
									  if !row[@row_index_hash[@rowname]].blank?
										value["#{locale}"] = row[@row_index_hash[@rowname]]
										@role_add_value = @role_add_value + 1
									  end
									end
								end
							else
								@rowname = "#{role.key}-#{attribute_field.key}"
								@row_index_hash[@rowname] = @field_data.index(@rowname) if index == 3
								if !@row_index_hash[@rowname].blank?
									if !row[@row_index_hash[@rowname]].blank?
									  value["val"] = "#{row[@row_index_hash[@rowname]]}"
									  @role_add_value = @role_add_value + 1
									end
								end
							end
							value.save
						end
						if @role_add_value > 0
							role.member_profiles << @member_profile
							role.save
						end
					end
					if !@role_status_data.blank?
					  @member_profile.role_status_ids = @role_status_data
					  @member_profile.save
					end
					if !row[@row_index_hash["password"]].to_s.blank? && !row[@row_index_hash["user_id"]].to_s.blank?
						if !User.where(:user_name=> row[@row_index_hash["user_id"]]).first.nil?
							@user = User.where(:user_name=> row[@row_index_hash["user_id"]]).first
							@user.update_password(row[@row_index_hash["password"]].to_s, row[@row_index_hash["password"]].to_s)
							@user = User.where(:user_name=> row[@row_index_hash["user_id"]]).first
							@user.member_profile = @member_profile
							@user.approved = true
							@user.save
						else
							@user = User.new(
							  user_name: row[@row_index_hash["user_id"]],
							  password: row[@row_index_hash["password"]],
							  member_profile: @member_profile,
							  approved: true
							)
							@user.save
						end
					elsif row[@row_index_hash["password"]].to_s.blank? && !row[@row_index_hash["user_id"]].to_s.blank?
						@user = User.where(:user_name=> row[@row_index_hash["user_id"]]).first
						if !@user.nil?
							@user.member_profile = @member_profile
							@user.save
						end
					end
				  end
			end
			@members_list.concat(@members_list_tmp)
			return true
			#redirect_to admin_members_path
		else
			return false
			#render 'import_error_msg'
		end
    end
  end
  def import_members
	if !params[:file].blank?
		#render :html => get_image_extension(params[:file].tempfile.path) and return
		@members_list = []
		if( params[:file].original_filename.to_s.reverse.index('.xlsx'.reverse) == 0 rescue false)
			flag = read_xlsx_temp_file_and_import_members(params[:file].tempfile,nil,params[:file].original_filename)
			if flag == true
				redirect_to admin_members_path
			else
				render 'import_error_msg'
			end
		elsif( params[:file].original_filename.to_s.reverse.index('.zip'.reverse) == 0 rescue false)
			unzip_path = 'tmp/unzip/'
			FileUtils.rm_r(unzip_path,:force=>true) if Dir.exist? unzip_path
			FileUtils.mkdir_p unzip_path
			ZipFileGenerator.new(params[:file].tempfile.path,unzip_path).extract_zip
			flag = true
			Dir.chdir(unzip_path) do
				@filenames = `ls`.split
				@filenames.each do |filename|
					if filename.reverse.index('.xlsx'.reverse) == 0
						@file = File.open(filename,'r')
						flag = read_xlsx_temp_file_and_import_members(@file,unzip_path,filename)
						@file.close
					end
					break if flag == false
				end
			end
			#return
			#zip_data = read_zip(params[:file].tempfile)
			# zip_data.each do |data|
				# temp_file = Tempfile.new(['temp','.xlsx'], encoding: 'ascii-8bit')
				# temp_file << data
				# #if get_image_extension(temp_file.path) == 'jpg' || get_image_extension(temp_file.path) == 'png' || get_image_extension(temp_file.path) == 'gif'
					# #File.open(||
					# #next
				# #end
				# #temp_file.close
				# #render :html => temp_file.path and return
				# flag = read_xlsx_temp_file_and_import_members(temp_file.open)
				# temp_file.close
			# end
			
			if flag == true
				redirect_to admin_members_path
			else
				render 'import_error_msg'
			end
		end
	end
  end
   def get_image_extension(local_file_path)
	png = Regexp.new("\x89PNG".force_encoding("binary"))
	jpg = Regexp.new("\xff\xd8\xff\xe0\x00\x10JFIF".force_encoding("binary"))
	jpg2 = Regexp.new("\xff\xd8\xff\xe1(.*){2}Exif".force_encoding("binary"))
	case IO.read(local_file_path, 10)
	  when /^GIF8/
		'gif'
	  when /^#{png}/
		'png'
	  when /^#{jpg}/
		'jpg'
	  when /^#{jpg2}/
		'jpg'
	else
		mime_type = `file #{local_file_path} --mime-type`.gsub("\n", '') # Works on linux and mac
		raise UnprocessableEntity, "unknown file type" if !mime_type
		mime_type.split(':')[1].split('/')[1].gsub('x-', '').gsub(/jpeg/, 'jpg').gsub(/text/, 'txt').gsub(/x-/, '')
	end  
  end
  def export_members_data
    @users = User.all
    @member_role = params[:member_role].blank? ? Role.all.asc(:_id) : params[:member_role]
    @member_roles = @member_role.collect{|a| a[0]}
	zip_path = 'tmp/member_tmp/'
	tmp_filename = ''
	FileUtils.rm_r(zip_path, :force => true) if Dir.exist?(zip_path)
	FileUtils.mkdir zip_path #create dir for storing tmp_file
	if params[:member_role].nil?
		write_zip = true
		roles = Role.all.take_while{true}
		index = 0
		role_hash_arr = []
		roles.each do |role|
			member_info_hash_arr = []
			if !role.member_profile_ids.nil?
				role.member_profile_ids.each do |profile_id|
					member_info_hash =  {}
					member_profile = MemberProfile.find(profile_id) rescue next
					next if member_profile.nil?
					if !member_profile.user.nil?
						member_info_hash['user_id'] = member_profile.user.user_name
					end
					attr_field = ['first_name','last_name','email','sid','office_tel','sex','birthday','address','autobiography']
					attr_field.each do |attr|
						member_info_hash[attr] = member_profile[attr]
					end
					member_info_hash['member_info'] = []
					if MemberInfo.all.length != 0
						MemberInfo.all.take_while{true}.each do |info|
							info.member_profile_fields.each do |member_profile_fields|
								@member_profile_field_value = member_profile_fields.to_a.map{|member_profile_field| MemberProfileField.find(member_profile_field.id).member_profile_field_values.to_a rescue next}.map{|member_profile_field_value| member_profile_field_value.select{|field_value| field_value.member_profile_id == profile_id}}
								temp_info = {}
								if @member_profile_field_value.length != 0
									current_site.in_use_locales.each do |locale|
										temp_info[locale] = @member_profile_field_value.first.first[locale] rescue ''
									end
								else
									current_site.in_use_locales.each do |locale|
										temp_info[locale] = ''
									end
								end
								member_info_hash['member_info'].push(temp_info)
							end
						end
					end
					member_profile.role_status_ids.each do |role_status_id|
						role_status = RoleStatus.find(role_status_id) rescue nil
						next if role_status.nil?
						member_info_hash.merge!( {"status"=>role_status.key}) if role_status.role_id == role.id
					end
					role_keys = member_profile.roles.select{|r| r==role}[0].attribute_fields.where(:disabled=>false).asc(:_id).map{|rf| rf.title} rescue nil
					role_keys.map{|role_key| member_info_hash[role_key] = {}}
					current_site.in_use_locales.each do |locale|
						role_values = member_profile.roles.select{|r| r==role}[0].attribute_fields.where(:disabled=>false).asc(:_id).map{|rf| (member_profile.get_attribute_value(rf,"role").get_value_by_locale(locale.to_s) rescue '')}
						role_keys.each_with_index do |role_key,i|
							member_info_hash[role_key][locale] = role_values[i]
						end
					end		
					locale_name = current_site.in_use_locales.first
					role_select_names = role.attribute_fields.map{|field| field.option_list.map{|key,value| value[locale_name]}}
					role_select_names.each_with_index do |select_name_arr,i|
						next if select_name_arr.empty?
						member_info_hash[role_keys[i]] = select_name_arr.index(member_info_hash[role_keys[i]][locale_name]).to_s
					end
					member_info_hash['role_keys'] = role_keys
					if member_profile.avatar.file.nil?
						member_info_hash['avatar'] = ''
					else
						if member_profile.avatar.file.exists?
							write_zip = true
							@original_filename = member_profile.avatar.file.filename
							@picture_name = zip_path+ member_profile.name.delete(' ') + @original_filename[@original_filename.rindex('.')..-1]
							member_info_hash['avatar'] = member_profile.name.delete(' ') + @original_filename[(@original_filename.rindex('.'))..-1]
							File.open(@picture_name, 'w:ascii-8bit') do |f|
								f.write(member_profile.avatar.file.read)
							end
						end
					end
					member_info_hash_arr.push member_info_hash			
				end
			end
			next if member_info_hash_arr == []
			
			role_hash_arr.push member_info_hash_arr
			if role.key.to_s == ''
				role_name = role.title
			else
				role_name = role.key.to_s
			end
			@filename = zip_path+'member_export_'+role_name+'.xlsx'
			@member_roles = {'key'=>role.key,'title'=>role.title}
			if File.exist?(@filename)
				i = 0
				while File.exist?(@filename[0..-6]+i.to_s+'.xlsx')
					i += 1
				end
				@filename = @filename[0..-6]+i.to_s+'.xlsx'
			end
			File.open(@filename, 'w') do |f|
				f.write render_to_string( handlers: [:axlsx], formats: [:xlsx] ,partial: 'export_members_data.xlsx',locals: {:@member_roles=>@member_roles,:@member_data_list=>member_info_hash_arr,:@site_in_use_locales=>@site_in_use_locales} )
			end
		end
		no_role_members = []
		MemberProfile.all.any_in(:role_ids=>[nil,[]]).each do |member_profile|
			member_info_hash = {}
			if !member_profile.user.nil?
				member_info_hash['user_id'] = member_profile.user.user_name
			end
			attr_field = ['first_name','last_name','email','sid','office_tel','sex','birthday','address','autobiography']
			attr_field.each do |attr|
				member_info_hash[attr] = member_profile[attr]
			end
			member_info_hash['member_info'] = []
			if MemberInfo.all.length != 0
				MemberInfo.all.take_while{true}.each do |info|
					info.member_profile_fields.each do |member_profile_fields|
						@member_profile_field_value = member_profile_fields.to_a.map{|member_profile_field| MemberProfileField.find(member_profile_field.id).member_profile_field_values.to_a rescue next}.map{|member_profile_field_value| member_profile_field_value.select{|field_value| field_value.member_profile_id == member_profile.id}}
						temp_info = {}
						if @member_profile_field_value.length != 0
							current_site.in_use_locales.each do |locale|
								temp_info[locale] = @member_profile_field_value.first.first[locale] rescue ''
							end
						else
							current_site.in_use_locales.each do |locale|
								temp_info[locale] = ''
							end
						end
						member_info_hash['member_info'].push(temp_info)
					end
				end
			end
			if member_profile.avatar.file.nil?
				member_info_hash['avatar'] = ''
			else
				if member_profile.avatar.file.exists?
					write_zip = true
					@original_filename = member_profile.avatar.file.filename
					@picture_name = zip_path+ member_profile.name.delete(' ') + @original_filename[@original_filename.rindex('.')..-1]
					member_info_hash['avatar'] = member_profile.name.delete(' ') + @original_filename[(@original_filename.rindex('.'))..-1]
					File.open(@picture_name, 'w:ascii-8bit') do |f|
						f.write(member_profile.avatar.file.read)
					end
				end
			end
			member_info_hash['role_keys'] = []
			no_role_members.push member_info_hash
		end
		@filename = zip_path+'member_export_no_role_members.xlsx'
		if File.exist?(@filename)
			i = 0
			while File.exist?(@filename[0..-6]+i.to_s+'.xlsx')
				i += 1
			end
			@filename = @filename[0..-6]+i.to_s+'.xlsx'
		end
		File.open(@filename, 'w') do |f|
			f.write render_to_string( handlers: [:axlsx], formats: [:xlsx] ,partial: 'export_members_data.xlsx',locals: {:@member_roles=>nil,:@member_data_list=>no_role_members,:@site_in_use_locales=>@site_in_use_locales} )
		end
		#create zip from dir start
		zip_file= ZipFileGenerator.new(zip_path,Pathname.new(zip_path).parent.to_s+'/member_export_data.zip')
		begin
			zip_file.write
		rescue
			File.delete(Pathname.new(zip_path).parent.to_s+'/member_export_data.zip')
			zip_file.write
		end
		#create zip from dir end
	else
		write_zip = false
		write_zip = (true if params[:member_role].keys.length > 1 rescue false)
		params[:member_role].keys.each do |role_key|
			if role_key == 'no_role'
				no_role_members = []
				MemberProfile.all.any_in(:role_ids=>[nil,[]]).each do |member_profile|
					member_info_hash = {}
					if !member_profile.user.nil?
						member_info_hash['user_id'] = member_profile.user.user_name
					end
					attr_field = ['first_name','last_name','email','sid','office_tel','sex','birthday','address','autobiography']
					attr_field.each do |attr|
						member_info_hash[attr] = member_profile[attr]
					end
					member_info_hash['member_info'] = []
					if MemberInfo.all.length != 0
						MemberInfo.all.take_while{true}.each do |info|
							info.member_profile_fields.each do |member_profile_fields|
								@member_profile_field_value = member_profile_fields.to_a.map{|member_profile_field| MemberProfileField.find(member_profile_field.id).member_profile_field_values.to_a rescue next}.map{|member_profile_field_value| member_profile_field_value.select{|field_value| field_value.member_profile_id == member_profile.id}}
								temp_info = {}
								if @member_profile_field_value.length != 0
									current_site.in_use_locales.each do |locale|
										temp_info[locale] = @member_profile_field_value.first.first[locale] rescue ''
									end
								else
									current_site.in_use_locales.each do |locale|
										temp_info[locale] = ''
									end
								end
								member_info_hash['member_info'].push(temp_info)
							end
						end
					end
					if member_profile.avatar.file.nil?
						member_info_hash['avatar'] = ''
					else
						if member_profile.avatar.file.exists?
							write_zip = true
							@original_filename = member_profile.avatar.file.filename
							@picture_name = zip_path+ member_profile.name.delete(' ') + @original_filename[@original_filename.rindex('.')..-1]
							member_info_hash['avatar'] = member_profile.name.delete(' ') + @original_filename[(@original_filename.rindex('.'))..-1]
							File.open(@picture_name, 'w:ascii-8bit') do |f|
								f.write(member_profile.avatar.file.read)
							end
						end
					end
					member_info_hash['role_keys'] = []
					no_role_members.push member_info_hash
				end
				@filename = zip_path+'member_export_no_role_members.xlsx'
				if File.exist?(@filename)
					i = 0
					while File.exist?(@filename[0..-6]+i.to_s+'.xlsx')
						i += 1
					end
					@filename = @filename[0..-6]+i.to_s+'.xlsx'
				end
				File.open(@filename, 'w') do |f|
					f.write render_to_string( handlers: [:axlsx], formats: [:xlsx] ,partial: 'export_members_data.xlsx',locals: {:@member_roles=>nil,:@member_data_list=>no_role_members,:@site_in_use_locales=>@site_in_use_locales} )
				end
			else
				begin
					role = Role.where(:key=>role_key).first
					role = Role.where(:title=>role_key).first if role.nil?
				rescue
					next
				end
				member_info_hash_arr = []
				if !role.member_profile_ids.nil?
					role.member_profile_ids.each do |profile_id|
						member_info_hash =  {}
						member_profile = MemberProfile.find(profile_id) rescue next
						next if member_profile.nil?
						if !member_profile.user.nil?
							member_info_hash['user_id'] = member_profile.user.user_name
						end
						attr_field = ['first_name','last_name','email','sid','office_tel','sex','birthday','address','autobiography','fax','office_tel','mobile_no']
						attr_field.each do |attr|
							member_info_hash[attr] = member_profile[attr]
						end
						member_info_hash['member_info'] = []
						if MemberInfo.all.length != 0
							MemberInfo.all.take_while{true}.each do |info|
								info.member_profile_fields.each do |member_profile_fields|
									@member_profile_field_value = member_profile_fields.to_a.map{|member_profile_field| MemberProfileField.find(member_profile_field.id).member_profile_field_values.to_a rescue next}.map{|member_profile_field_value| member_profile_field_value.select{|field_value| field_value.member_profile_id == profile_id}}
									temp_info = {}
									if @member_profile_field_value.length != 0
										current_site.in_use_locales.each do |locale|
											temp_info[locale] = @member_profile_field_value.first.first[locale] rescue ''
										end
									else
										current_site.in_use_locales.each do |locale|
											temp_info[locale] = ''
										end
									end
									member_info_hash['member_info'].push(temp_info)
								end
							end
						end
						member_profile.role_status_ids.each do |role_status_id|
							role_status = RoleStatus.find(role_status_id) rescue nil
							next if role_status.nil?
							member_info_hash.merge!( {"status"=>role_status.key}) if role_status.role_id == role.id
						end
						role_keys = member_profile.roles.select{|r| r==role}[0].attribute_fields.where(:disabled=>false).asc(:_id).map{|rf| rf.title} rescue nil
						role_keys.map{|role_key| member_info_hash[role_key] = {}}
						current_site.in_use_locales.each do |locale|
							role_values = member_profile.roles.select{|r| r==role}[0].attribute_fields.where(:disabled=>false).asc(:_id).map{|rf| (member_profile.get_attribute_value(rf,"role").get_value_by_locale(locale)) rescue ''}
							role_keys.each_with_index do |role_key,i|
								member_info_hash[role_key][locale] = role_values[i]
							end
						end
						locale_name = current_site.in_use_locales.first
						role_select_names = role.attribute_fields.map{|field| field.option_list.map{|key,value| value[locale_name]}}
						role_select_names.each_with_index do |select_name_arr,i|
							next if select_name_arr.empty?
							member_info_hash[role_keys[i]] = select_name_arr.index(member_info_hash[role_keys[i]][locale_name]).to_s
						end
						member_info_hash['role_keys'] = role_keys
						if member_profile.avatar.file.nil?
							member_info_hash['avatar'] = ''
						else
							if member_profile.avatar.file.exists?
								write_zip = true
								@original_filename = member_profile.avatar.file.filename
								@picture_name = zip_path+ member_profile.name.delete(' ') + @original_filename[(@original_filename.rindex('.'))..-1]
								member_info_hash['avatar'] = member_profile.name.delete(' ') + @original_filename[(@original_filename.rindex('.'))..-1]
								File.open(@picture_name, 'w:ascii-8bit') do |f|
									f.write(member_profile.avatar.file.read)
								end
							end
						end
						member_info_hash_arr.push member_info_hash
					end	
				end
				next if member_info_hash_arr == []
				if write_zip == false
					tmp_filename = 'member_export_'+role_key+'.xlsx'		
				end
				@filename = zip_path+'/member_export_'+role_key+'.xlsx'
				@member_roles = {'key'=>role.key,'title'=>role.title}
				if File.exist?(@filename)
					i = 0
					while File.exist?(@filename[0..-6]+i.to_s+'.xlsx')
						i += 1
					end
					@filename = @filename[0..-6]+i.to_s+'.xlsx'
				end
				File.open(@filename, 'w') do |f|
					f.write render_to_string( :handlers=> [:axlsx], :formats=> [:xlsx] ,:partial=> 'export_members_data.xlsx',:locals=> {:@member_roles=>@member_roles,:@member_data_list=>member_info_hash_arr,:@site_in_use_locales=>@site_in_use_locales} )
				end
			end
		end
		if write_zip == true
			#create zip from dir start
			zip_file= ZipFileGenerator.new(zip_path,Pathname.new(zip_path).parent.to_s+'/member_export_data.zip')
			begin
				zip_file.write
			rescue
				File.delete(Pathname.new(zip_path).parent.to_s+'/member_export_data.zip')
				zip_file.write
			end
			#create zip from dir end
		end
	end
	Dir.chdir zip_path do
		if `ls`.split().length == 1
			write_zip = false
			tmp_filename = `ls`.split()[0]
		end
	end
	if write_zip == true
		zip_data = File.read(Pathname.new(zip_path).parent.to_s+'/member_export_data.zip')
		send_data(zip_data, type: 'application/zip', disposition: 'attachment', filename: "member_export_data.zip")
	else
		if tmp_filename != ""
			tmp_filename_data = File.read(zip_path +tmp_filename)
			send_data(tmp_filename_data, type: 'application/xlsx', disposition: 'attachment', filename: tmp_filename)
		else
			redirect_to admin_members_export_members_path+'?error=true'
		end
	end

  end

  def read_zip(zip_path)
	zip_data = []
	Zip::File.open(zip_path) do |zipfile|
		zipfile.each do |entry|
		  # Read into memory
		  content = entry.get_input_stream.read
		  zip_data.push content
	    end
	end
	return zip_data #it's ascii-8bit data
  end
  def download_export

    @users = User.all
    @member_role = params[:member_role].blank? ? Role.all.asc(:_id) : params[:member_role]
    @member_roles = @member_role.collect{|a| a[0]}
    respond_to do |format|
      format.xlsx {
        response.headers['Content-Disposition'] = 'attachment; filename="member_import_data.xlsx"'
      }
    end

  end

  def new
    sort_role_attr_field
    if has_access?
      @member = MemberProfile.new
      get_info_and_roles
      @user = User.new
      @form_index = 0
    else
      render_401
    end
  end

  def edit
    sort_role_attr_field
    param_temp = request.fullpath.split("?")
    @edit_params = (param_temp.count > 1 ? "?" + param_temp.last : "") rescue ""
    if has_access?
      @form_index = 0
      get_info_and_roles
      if @member.user.present?
        @user = @member.user
      else
        @user = User.new(member_profile_id: @member.id)
      end
    else
      render_401
    end
  end

  def create
    @member = MemberProfile.new(member_profile_params)
    if @member.save
      if user_params["user_name"] != ""
        @user = User.new(user_params) rescue nil
        @user.member_profile = @member
        if !@user.save
          @member.destroy
          get_info_and_roles
		  @form_index = 0
          render 'new' and return
        end
      end
      mpfv_params = member_profile_field_values_params
      if !mpfv_params.nil?
        mpfv_params.each_with_index do |m,i|
          @custom_field_value = @member.member_profile_field_values.build(value: m.second["value"], member_profile_field_id: m.second["member_profile_field_id"])
          @custom_field_value.save
        end
      end
      rfv_params = role_field_values_params
      if !rfv_params.nil?
        rfv_params.each_with_index do |r,i|
          field_value = r.last[:id].present?
          @custom_field_value = AttributeValue.put_field_values(@member, r.last, r.last[:attribute_field_id], field_value)
        end
      end

      redirect_to admin_members_path
    else
      render 'new'
    end
  end

  def update
    param_temp = request.fullpath.split("?")
    @edit_params = (param_temp.count > 1 ? "?" + param_temp.last : "") rescue ""
    respond_to do |format|
      if @member.user.present?
        @user = @member.user
        @user.update(user_params)
      else
        if user_params["user_name"] != ""
          @user = User.new(user_params) rescue nil
          @user.member_profile = @member
          @user.save
        else
		  @user = User.new(user_params) rescue nil
        end
      end

      # quick fix for preventing user delete their own role_status_ids
      # NOTE: new_member_profile_params will overwrite member_profile_params
      new_member_profile_params = member_profile_params
      if request_from_regular_user?(current_user, @user)
        new_member_profile_params[:role_status_ids] = @user.member_profile.role_status_ids
      end

      if @member.update_attributes(new_member_profile_params)
        if params[:edit_type]!="edit_privilege" and (member_profile_params.nil? or member_profile_params[:role_status_ids].nil?)
          # condition member_profile_params[:role_status_ids].nil? become useless when current_user is not admin,
          # wait for git commit #e94ee506748 issue showing up again
          @member.update_attributes(role_status_ids: [])
        end
        mpfv_params = member_profile_field_values_params
        if !mpfv_params.nil?
          mpfv_params.each_with_index do |m,i|
            field_value = m.last[:id].present?
            @custom_field_value = MemberProfileFieldValue.put_field_values(@member, m.last, m.last[:id], field_value)
          end
        # elsif !params[:member_profile_field_value].nil?
        #   params[:member_profile_field_value].each_with_index do |m,i|
        #     field_value = m.last[:id].present?
        #     @custom_field_value = MemberProfileFieldValue.put_field_values(@member, m.last, nil, field_value)
        #   end
        end
        rfv_params = role_field_values_params
        if !rfv_params.nil?
          rfv_params.each_with_index do |r,i|
            field_value = r.last[:id].present?
            @custom_field_value = AttributeValue.put_field_values(@member, r.last, r.last[:id], field_value)
          end
        end
        if params[:edit_type]=="edit_privilege"
           @member.user.update_attributes(workgroup_id: params[:workgroup_id])
        end


        format.html { redirect_to admin_members_path() + @edit_params, notice: 'Successfully Updated the User' }
        format.json { head :no_content }
      else
        get_info_and_roles
		@form_index = 0
        format.html { render action: "edit_passwd"} if params[:edit_type] == "edit_passwd"
        format.html { render action: 'edit' }
        format.json { render json: @member.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    if params[:id].eql?(current_user.id.to_s)
      flash[:error] = t(:cant_delete_self)
    else
      @member_profile = MemberProfile.find(params[:id])
      @member_profile.user.delete if @member_profile.user.present?
      @member_profile.destroy
      @member_profile.roles.clear
      @member_profile.role_statuses.clear
    end

    respond_to do |format|
      format.js
    end
  end

  def unapproved_members
    @member_query = Sanitize.clean(params[:member_query])
    page_num = params[:page] || 1
    if !@member_query.blank?
      members = MemberProfile.all.any_of({:user_id => /#{@member_query}/i}, {:first_name => /#{@member_query}/i}, {:last_name => /#{@member_query}/i}, {:email => /#{@member_query}/i})
      @members = members.collect do |member|
        if !member.user.approved
          member.user
        end
      end
    else
      @members = User.unapproved.page(page_num).per(12)
    end
  end

  def accept_member
    user = User.find(params[:member_id])
    user.approved = true
    user.save
    redirect_to admin_members_unapproved_members_path
  end

  def edit_passwd
    if has_access?
      @user = @member.user
    else
      render_401
    end
  end

  def edit_privilege
    @edit_params = "?" + request.fullpath.split("?").last  rescue ""
    if current_user.is_admin?
      @user = @member.user
      @workgroup = Workgroup.find_by(key: 'admin')
    else
      render_401
    end
  end

  def edit_order_card
    @members = MemberProfile.order('created_at DESC')
    @type = 'card'
    render 'edit_order'
  end

  def edit_order_list
    @members = MemberProfile.order(:position=>'asc',:created_at=>'desc')
    @type = 'list'
    render 'edit_order'
  end

  def update_order_card
    @error = false
    if params[:users].present?
      to_go = params[:users][:position].to_i
      member_at_position = MemberProfile.find_by(position: to_go + 1)
      member = MemberProfile.find(params[:users][:id])
      if member_at_position
        if member.position > member_at_position.position
          member.move_above(member_at_position)
        else
          member.move_below(member_at_position)
        end
      end
    end
    render nothing: true, status: 200
  end

  def update_order_list
    if params[:position].present?
      params[:position].each do |id, position|
        profile = MemberProfile.find(id)
        profile.position = position.to_i
        profile.save(:validate => false)
      end
    end
    # @error = []
    # if params[:users].present?
    #   params[:users].values.sort.each do |pair|
    #     to_go = pair[0].to_i

    #     if to_go > 0
    #       member_at_position = MemberProfile.where(position: to_go).first
    #       member = MemberProfile.find(pair[1])
    #       if member_at_position && !(member_at_position == member)
    #         if member.position > member_at_position.position
    #           member.move_above(member_at_position)
    #         else
    #           member.move_below(member_at_position)
    #         end
    #       elsif to_go > MemberProfile.count
    #         member.move_to_bottom
    #       end
    #     end
    #   end
    # end
    # @members = MemberProfile.asc(:position)
    render :nothing=>true
 end

 def save_autobiography
  member = MemberProfile.find(params["member-id"]) rescue nil
  now_locale = I18n.locale
  if !member.nil?
    params[:content].each do |content_key,content_value|
      locale = content_key.split('bio_text_')[1]
      I18n.locale = locale
      member.autobiography = content_value
      member.save
      puts ['key',content_key.inspect,'value',content_value.inspect]
    end
  end
  I18n.locale = now_locale
  render :json => {"success" => true}.to_json
 end

 def new_tag
  membertag = MemberTag.new(member_tag_params)
  membertag.created_by = current_user.id
  membertag.save
  render :json => {"success" => true, "title" => membertag.title, "id" => membertag.id.to_s}.to_json
 end

  def setting_account
    if params[:member_id].blank?
      redirect_to action: :index
    else
      @user = MemberProfile.find(params[:member_id])
      if current_user.id != @user.id
        redirect_to action: :index
      end
    end
  end

  def get_role_fields
    role = Role.find(params[:id])
    statuses = role.role_statuses.map{|status| {'key'=>status.key, 'title'=>status.title}}.select{|s| s['key']='part_time'}
    render :json=>{"statuses"=>statuses}
  end

  def set_privacy
    id = params[:id]
    status = params[:status]
    if current_user.is_admin?
      member = MemberProfile.find(params[:memberid])
    else
      member = current_user.member_profile
    end
    old = member.get_privacy_type_for_field(id)
    case status
    when "locked"
      member.locked_privacy << id
    when "logged_in"
      member.logged_in_privacy << id
    when "public"
      member.public_privacy << id
    end
    case old
    when "locked"
      member.locked_privacy.delete(id)
    when "logged_in"
      member.logged_in_privacy.delete(id)
    when "public"
      member.public_privacy.delete(id)
    end
    member.save
    render :json => {"success" => true}.to_json
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_member_profile
    @member = MemberProfile.find(params[:id])
  end

  def show_member_profile
    path = request.path.split('/')
    if path.last.include? '-'
      uid = path[-1].split("-").last
      uid = uid.split("?").first
    else
      uid = path[-2].split("-").last
      uid = uid.split("?").first
    end
    @member = MemberProfile.find_by(uid: uid)
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def member_profile_params
    params.require(:member_profile).permit! rescue nil
  end

  def role_field_values_params
    params.require(:role_field_values).permit! rescue nil
  end

  def member_profile_field_values_params
    params.require(:member_profile_field_values).permit! rescue nil
  end

  def user_params
    params.require(:user).permit! rescue nil
  end

  def member_tag_params
    params.require(:member_tag).permit!
  end

  def request_from_regular_user?(current_user, user_for_update)
    (!current_user.is_admin? &&
     !user_for_update.member_profile.role_status_ids.nil? &&
     !user_for_update.member_profile.role_status_ids.empty? &&
     params[:member_profile][:role_status_ids].nil?)
  end

  protected

  def get_info_and_roles
    if current_user.is_admin?
      @roles = Role.excludes(disabled: true).asc(:key)
    else
      @roles = current_user.member_profile.roles
    end
    @infos = MemberProfileField.excludes(disabled: true).sort_by{|v| v.key.to_i}
  end

  def set_attribute
    @class = 'users'
  end

end
