#coding=utf-8
module Mobile
  module Apis
    class Users < Grape::API
      resource :users do

        desc "我的资料"
        params do
          requires :token, type: String
        end

        get 'get_userinfo' do
          authenticate!
          present :data, current_user, with: Mobile::Entities::User
          present :status, 0
        end

        desc "上传头像"
        params do
          requires :token, type: String
          requires :imgdata, type: String
        end

        post 'upload_head' do
          authenticate!
          #直接生成头像
          dirPath = "public/images/avatars/User"

          fileDir = dirPath + "/"+current_user.id.to_s
          imgdata = Base64.decode64(params[:imgdata].split(",")[1])
          if imgdata.length > 1024*1024
            present :message,"上传图片不能超过1M"
            present :status, -1
          else
            begin
              File.open(fileDir,'wb'){ |f| f.write(imgdata) }
              present :status, 0
            rescue
              present :message,"上传失败"
              present :status, -1
            end
          end
        end

        desc "解除绑定"
        params do
          requires :token, type: String
        end

        post 'user_unbind' do
          authenticate!

          user = current_user
          uw = user.user_wechat

          us = UsersService.new
          us.wechat_unbind user.user_wechat

          present :status, 0
        end

        desc "查询是否已绑定"
        params do
          requires :openid, type: String, desc: 'wechat openid'
        end
        post 'isbind' do
          openid = params[:openid]
          uw = UserWechat.where(openid: openid).first
          raise "还未绑定trustie帐户" unless uw

          user = uw.user
          ::ApiKey.delete_all(user_id: user.id)
          key = ::ApiKey.create!(user_id: user.id)
          present status: 0, token: key.access_token
        end

        desc "绑定微信用户"
        params do
          requires :login, type: String, desc: 'username'
          requires :password, type: String, desc: 'password'
        end
        post 'wxbind' do
            openid = session[:wechat_openid]
            logger.debug "openid ============== #{openid}"
            raise "无法获取到openid,请在微信中打开本页面" unless openid
            uw = UserWechat.where(openid: openid).first
            raise "此微信号已绑定用户(#{uw.user.login}), 不能重复绑定" if uw && uw.real?

            user, last_login_on = User.try_to_login(params[:login], params[:password])
            raise "用户名或密码错误,请重新输入" unless user
            #补全用户信息

            raise "此用户已经绑定过公众号, 请换一个帐户试试" if user.user_wechat

            if uw && !uw.real?
              uw.migrate_user(user)
            else
              UserWechat.create!(
                openid: openid,
                user: user
              )
            end

            ws = WechatService.new
            ws.binding_succ_notice(user.id, "您已成功绑定Trustie平台。", user.show_name+"("+user.login+")", Time.now.strftime("%Y-%m-%d"))
            present status: 0, message: '您已成功绑定Trustie平台'
        end

        desc "注册用户"
        params do
          requires :login, type: String, desc: 'username'
          requires :mail, type: String, desc: 'mail'
          requires :password, type: String, desc: 'password'
        end
        post do
          openid = session[:wechat_openid]
          logger.debug "openid ============== #{openid}"
          raise "无法获取到openid,请在微信中打开本页面" unless openid

          uw = UserWechat.where(openid: openid).first
          raise "此微信号已绑定用户(#{uw.user.login}), 不能重复绑定" if uw && uw.real?
          us = UsersService.new
          user = us.register params.merge(:password_confirmation => params[:password],
                                          :should_confirmation_password => true)
          raise user.errors.full_messages.first if user.new_record?
          #自动激活
          if Setting.self_registration != '3'
            # user = automatically_register(user)
            user.activate
            user.last_login_on = Time.now
            if user.save
              UserStatus.create(:user_id => user.id, :changsets_count => 0, :watchers_count => 0)
            end
          end

          if uw && !uw.real?
            user.update_attributes(:lastname=>uw.user[:lastname])
            uw.migrate_user(user)
          else
            UserWechat.create!(
              openid: openid,
              user: user
            )
          end

          ws = WechatService.new
          ws.binding_succ_notice(user.id, "您已成功绑定Trustie平台。", user.show_name+"("+user.login+")", Time.now.strftime("%Y-%m-%d"))
          present :data, user, with: Mobile::Entities::User
          present :status, 0
        end

        desc "显示用户"
        params do
          requires :id, type: Integer
        end
        route_param :id do
          get do
            us = UsersService.new
            ue = us.show_user params
            present :data, ue,with: Mobile::Entities::User
            present :status, 0
          end
        end

        desc "修改用户"
        params do
          requires :token, type: String
          #optional :file, type: File, desc: 'avatar'
          optional :occupation, type: String
          optional :brief_introduction, type: String
          optional :province, type: String
          optional :city, type: String
          optional :gender, type: Integer
        end
        put ':id' do
          authenticate!
          us = UsersService.new
          ue = us.edit_user params.merge(id: current_user.id)
          present :data, ue,with: Mobile::Entities::User
          present :status, 0
        end

        desc '获取用户课程'
        params do
          optional :token, type: String
        end

        get ':id/courses' do
          us = UsersService.new
          ue = us.user_courses_list params,current_user.nil? ? User.find(2):current_user
          present :data, ue,with: Mobile::Entities::Course
          present :status, 0
        end


        desc '修改密码'
        params do
          requires :token, type: String
          requires :password, type:String , desc: '原密码'
          requires :new_password, type: String, desc: '新密码'
        end
        post 'password' do
          authenticate!
          us = UsersService.new
          user = us.change_password params.merge(current_user_id: current_user.id,
                                               new_password_confirmation: params[:new_password])
          present :data, user, with: Mobile::Entities::User
          present :status, 0
        end

        desc "用户搜索"
        params do
          requires :name, type: String, desc: '用户名关键字'
          requires :search_by, type: String,desc: '搜索依据：0 登录名，1 用户名，2 邮箱,3 登录名和姓名'
          optional :is_search_assitant,type:Integer,desc:'是否搜索注册用户来作为助教'
          optional :course_id,type:Integer,desc: '课程id，搜索注册用户不为该课程教师的其他用户'
          optional :user_id,type:Integer,desc:'用户id'
        end
        get 'search/search_user' do
          us = UsersService.new
          user = us.search_user params
          present :data, user, with: Mobile::Entities::User
          present :status, 0
        end

        desc "用户留言"
        params do
          requires :token, type: String
          requires :user_id, type: Integer,desc: '被留言的用户id'
          requires :page,type:Integer,desc:'请求数据的页码'
        end
        get ':user_id/messages' do
          us = UsersService.new
          jours = us.get_all_messages params
          present :data,jours,with:Mobile::Entities::Jours
          present :status,0
        end

        desc "回复用户留言"
        params do
          requires :token, type: String
          requires :user_id, type: Integer,desc: '被留言的用户id'
          requires :content,type:String,desc:'留言内容'
          requires :ref_user_id,type:Integer,desc:'被回复的用户id'
          requires :parent_id,type:Integer,desc:'留言父id'
          requires :ref_message_id,type:Integer,desc:'引用消息id'
          optional :type,type:Integer,desc:'回复类型'
          optional :course_id,type:Integer,desc:'课程id'
        end
        post ':user_id/reply_message' do
          us = UsersService.new
          jours = us.reply_user_messages params,current_user
          present :status,0
        end

        desc "给用户留言"
        params do
          requires :token, type: String
          requires :user_id, type: Integer,desc:'被留言的用户id'
          requires :content, type: String,desc:'留言内容'
        end
        post ':user_id/leave_message' do
          us = UsersService.new
          us.leave_message params,current_user
          present :data,0
        end

        desc "与我相关"
        params do
          requires :token, type: String
          requires :page,type:Integer,desc:'页码'
        end
        get ':user_id/all_my_dynamic' do
          us = UsersService.new
          my_jours = us.reply_my_messages params,current_user
          present :data,my_jours,with:Mobile::Entities::Jours
          present :status,0
        end

        desc "修改我的资料"

        params do
          requires :token, type: String
          requires :lastname, type: String
          requires :sex, type: Integer
          requires :mail, type: String
        end

        post 'edit_userinfo' do
          authenticate!
          user = current_user
          status = 0
          message = ""

          #昵称 不能超过30个字符
          if params[:lastname].length > 30 then
            message = "姓名不能超过30个字符!"
            status = -1
          end

          if params[:mail].length > 60 then
            message = "邮箱地址不能超过60个字符!"
            status = -1
          end

          if !(params[:mail].match(/\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i))
            message = "请输入正确的邮箱地址!"
            status = -1
          end

          if status == 0
            # 修改邮箱的时候同步修改到gitlab
            if user.mail != params[:mail]
              g = Gitlab.client
              begin
                g.edit_user(user.gid, :email => params[:mail])
              rescue
                Rails.logger.error "sync user's email of gitlab failed!"
              end
            end

            user.mail = params[:mail]

            user.lastname = params[:lastname]

            se = user.extensions

            se.gender = params[:sex]

            if user.save && se.save
              status = 0
            else
              message = "该邮箱地址已被使用！"
              status = -1
            end
          end

          if status == 0
            present :data, current_user, with: Mobile::Entities::User
            present :status, 0
          else
            present :status, -1
            present :message, message
          end
        end
      end
    end
  end
end


