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

  require 'spreadsheet'
  require 'rubyXL'

  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? and @mq.blank?

      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(file)

    profile_data_row = ["email","sid","office_tel","sex","birthday"]
    profile_lang_data_row = ["first_name","last_name","address","autobiography"]

    @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

    workbook = RubyXL::Parser.parse(file.tempfile)
    sheet = workbook['Member'].extract_data
    sheet.each_with_index do |row,index|
      if index == 0
        @field_data = row
      end
      if index > 2

        @user_id = row[@field_data.index('user_id')]
        if !@user_id.blank?
          check_id = User.where(:user_name => @user_id).first
          @error_msg << "#{make_alpha_from_numbers(@field_data.index('user_id'))}#{index+1}欄位帳號已存在。" if !check_id.blank? 
          @error_msg << "#{make_alpha_from_numbers(@field_data.index('user_id'))}#{index+1}欄位格式不符。" if @user_id.size < 3
        end

        @password = row[@field_data.index('password')]
        if !@password.blank? and !@user_id.blank?
          @error_msg << "#{make_alpha_from_numbers(@field_data.index('password'))}#{index+1}欄位格式不符。" if @password.size < 8
        elsif @password.blank? and !@user_id.blank?
          @error_msg << "#{make_alpha_from_numbers(@field_data.index('password'))}#{index+1}欄位格式不符。" 
        end

        @error_msg << "#{make_alpha_from_numbers(@field_data.index('birthday'))}#{index+1}欄位日期格式不符。" if row[@field_data.index("birthday")].class.to_s != 'DateTime' and !row[@field_data.index('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}"
              @error_msg << "#{make_alpha_from_numbers(@field_data.index(@rowname))}#{index+1}欄位格式不符。" if !@option_list.include?("#{row[@field_data.index(@rowname)]}") and !row[@field_data.index(@rowname)].blank?

            elsif member_profile_field.markup == 'checkbox'

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

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

          end

        end


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

          role_statuses = RoleStatus.where(role_id: role.id, :disable=> false)
          if !role_statuses.blank?
            @rowname = "#{role.key}-status"
            if !@field_data.index(@rowname).blank?
              @error_msg << "#{make_alpha_from_numbers(@field_data.index(@rowname))}#{index+1}欄位格式不符。" if row[@field_data.index(@rowname)].to_s.split(',').last == row[@field_data.index(@rowname)] and !row[@field_data.index(@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}"
              if !@field_data.index(@rowname).blank?
                @error_msg << "#{make_alpha_from_numbers(@field_data.index(@rowname))}#{index+1}欄位格式不符。" if !@option_list.include?("#{row[@field_data.index(@rowname)]}") and !row[@field_data.index(@rowname)].blank?
              end

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

          end

        end

      end
    end

  end

  def import_members

    if !params[:file].blank?

      import_data_check(params[:file])

      if @error_msg.blank?

      profile_data_row = ["email","sid","office_tel","sex","birthday"]
      profile_lang_data_row = ["first_name","last_name","address","autobiography"]

      @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(params[:file].tempfile)
      sheet = workbook['Member'].extract_data
      sheet.each_with_index do |row,index|
        if index == 0
          @field_data = row
        end
        if index > 2
          if !row[0].blank? and !row[1].blank? 

            @member_profile = MemberProfile.new

            @site_in_use_locales.each_with_index do |locale, i|

              @member_profile.first_name_translations = @member_profile.first_name_translations.merge!( "#{locale}" => row[@field_data.index("first_name(#{locale})")]) if !row[@field_data.index("first_name(#{locale})")].blank? 
              @member_profile.last_name_translations = @member_profile.last_name_translations.merge!( "#{locale}" => row[@field_data.index("last_name(#{locale})")]) if !row[@field_data.index("last_name(#{locale})")].blank? 
              @member_profile.address_translations = @member_profile.address_translations.merge!( "#{locale}" => row[@field_data.index("address(#{locale})")]) if !row[@field_data.index("address(#{locale})")].blank? 
              @member_profile.autobiography_translations = @member_profile.autobiography_translations.merge!( "#{locale}" => row[@field_data.index("autobiography(#{locale})")]) if !row[@field_data.index("autobiography(#{locale})")].blank?
                     
            end
 
            @member_profile.email = row[@field_data.index("email")]
            @member_profile.sid = row[@field_data.index("sid")]
            @member_profile.office_tel = row[@field_data.index("office_tel")]
            @member_profile.sex = ( row[@field_data.index("sex")] == 'male' or row[@field_data.index("sex")] == 'female' ) ? row[@field_data.index("sex")] : 'unknown'
            @member_profile.birthday = row[@field_data.index("birthday")].class.to_s == 'DateTime' ? row[@field_data.index("birthday")] : ''

            @member_profile.save

            @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}"
                    value["val"] = row[@field_data.index(@rowname)] if !row[@field_data.index(@rowname)].blank?
                  else
                    @site_in_use_locales.each_with_index do |locale, i|
                      @rowname = "#{info.key}-#{member_profile_field.key}(#{locale})"
                      value["#{locale}"] = row[@field_data.index(@rowname)] if !row[@field_data.index(@rowname)].blank?
                    end
                  end
                elsif member_profile_field.markup == 'checkbox'
                  @rowname = "#{info.key}-#{member_profile_field.key}"
                  value["val"] = row[@field_data.index(@rowname)].to_s.split(',') if !row[@field_data.index(@rowname)].blank?
                elsif member_profile_field.markup == 'date'
                  @rowname = "#{info.key}-#{member_profile_field.key}"
                  value["val"] = row[@field_data.index(@rowname)].class.to_s == 'DateTime' ? row[@field_data.index(@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})"
                    value["#{locale}"] = row[@field_data.index(@rowname)] if !row[@field_data.index(@rowname)].blank?
                  end
                else
                  @rowname = "#{info.key}-#{member_profile_field.key}"
                  value["val"] = "#{row[@field_data.index(@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"

                if !@field_data.index(@rowname).blank?
                  if !row[@field_data.index(@rowname)].blank?
                    @status_value = row[@field_data.index(@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}"
                    if !@field_data.index(@rowname).blank?
                      if !row[@field_data.index(@rowname)].blank?
                        value["val"] = row[@field_data.index(@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})"
                      if !@field_data.index(@rowname).blank?
                        if !row[@field_data.index(@rowname)].blank?
                          value["#{locale}"] = row[@field_data.index(@rowname)] 
                          @role_add_value = @role_add_value + 1
                        end
                      end
                    end
                  end
                elsif attribute_field.markup == 'checkbox'
                  @rowname = "#{role.key}-#{attribute_field.key}"
                  if !@field_data.index(@rowname).blank?
                    if !row[@field_data.index(@rowname)].blank?
                      value["val"] = row[@field_data.index(@rowname)].to_s.split(',') 
                      @role_add_value = @role_add_value + 1
                    end
                  end
                elsif attribute_field.markup == 'date'
                  @rowname = "#{role.key}-#{attribute_field.key}"
                  if !@field_data.index(@rowname).blank?
                    value["val"] = row[@field_data.index(@rowname)].class.to_s == 'DateTime' ? row[@field_data.index(@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})"
                    if !@field_data.index(@rowname).blank?
                      if !row[@field_data.index(@rowname)].blank?
                        value["#{locale}"] = row[@field_data.index(@rowname)] 
                        @role_add_value = @role_add_value + 1
                      end
                    end
                  end
                else
                  @rowname = "#{role.key}-#{attribute_field.key}"
                  if !@field_data.index(@rowname).blank?
                    if !row[@field_data.index(@rowname)].blank?
                      value["val"] = "#{row[@field_data.index(@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

            @user = User.new(
              user_name: row[@field_data.index("user_id")],
              password: row[@field_data.index("password")],
              member_profile_id: @member_profile.id,
              approved: true
              )
            @user.save

          end

        end
        
      end

      redirect_to admin_members_path

      else

        render 'import_error_msg'

      end

    end
  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
    if has_access?
      @member = MemberProfile.new
      get_info_and_roles
      @user = User.new
      @form_index = 0
    else
      render_401
    end
  end

  def edit
     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
      if @member.update_attributes(member_profile_params) 
        if params[:edit_type]!="edit_privilege" and (params[:member_profile].nil? or params[:member_profile][:role_status_ids].nil?)
          @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
  content = params[:content]
  member = MemberProfile.find(params["member-id"]) rescue nil
  if !member.nil?
    member.autobiography = content
    member.save
  end
  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


  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)
  end

  def set_attribute
    @class = 'users'
  end

end
