#coding=utf-8

module Mobile
  module Apis
    class Projects < Grape::API

      resources :projects do
        desc "获取项目列表"
        params do
          requires :token, type: String
        end
        get do
          authenticate!

          ps = ProjectsService.new
          projects = ps.user_projects(current_user)
          present :data, projects, with: Mobile::Entities::Project,user: current_user
          present :status, 0
        end

        desc "返回单个项目"
        params do
          requires :id, type: Integer
          requires :token,type:String
        end
        route_param :id do
          get do
            # course = Course.find(params[:id])
            ps = ProjectsService.new
            project = ps.show_project(params,current_user)

            if project[:status] == 9
              {status:-1, message: '该项目不存在或已被删除啦' }
            else
              present :data, project, with: Mobile::Entities::Project,user: current_user
              present :status, 0
            end
          end
        end

        desc "获取项目动态"
        params do
          requires :id, type: Integer
          requires :token, type: String
        end
        post 'activities' do
          authenticate!

          user = current_user

          project_types = "('Message','Issue','Project')"
          activities = UserActivity.where("(container_type = 'Project' and container_id = #{params[:id]} and act_type in #{project_types})").order('updated_at desc')

          page = params[:page] ? params[:page] : 0
          all_count = activities.count
          activities = activities.limit(10).offset(page * 10)
          count = activities.count
          present :data, activities, with: Mobile::Entities::Activity,user: user
          present :all_count, all_count
          present :count, count
          present :page, page
          present :status, 0
        end

        desc "获取项目成员"
        params do
          requires :id, type: Integer
          requires :token, type: String
        end
        post 'members' do
          authenticate!

          project = Project.find("#{params[:id]}")
          members = project.member_principals

          master_members = project.member_principals.includes(:roles, :principal).where("member_roles.role_id=3").all.sort

          master_members.each do |m|
            if m.user_id == project.user_id
              master_members.delete(m)
              master_members.insert(0,m)
              break
            end
          end

          develop_members = project.member_principals.includes(:roles, :principal).where("member_roles.role_id=4").all.sort
          report_members = project.member_principals.includes(:roles, :principal).where("member_roles.role_id=5").all.sort

          review_master_members = []
          review_develop_members = []

          my_member = project.member_principals.where("users.id=#{current_user.id}").first
          if my_member && my_member.roles[0] && my_member.roles[0].id == 3
            ps = ProjectsService.new

            user = current_user
            review_master_members = ps.get_project_review_members(project,3,user)
            review_develop_members = ps.get_project_review_members(project,4,user)

          end

          present :master_members,master_members, with: Mobile::Entities::ProjectMember
          present :develop_members,develop_members, with: Mobile::Entities::ProjectMember
          present :report_members,report_members, with: Mobile::Entities::ProjectMember
          present :review_master_members,review_master_members
          present :review_develop_members,review_develop_members
          present :status, 0
        end

        desc "获取项目某成员角色信息"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :user_id, type: Integer
        end
        post 'get_member_info' do
          authenticate!

          project = Project.find("#{params[:id]}")

          my_member = project.member_principals.where("users.id=#{params[:user_id]}").first

          if my_member && my_member.roles[0]
            present :project_id,params[:id]
            present :user_id,params[:user_id]
            present :member_info,my_member, with: Mobile::Entities::ProjectMember
            present :status, 0
          else
            present :status, -1
            present :message, "该用户已不在项目中"
          end

        end

        desc "修改项目某成员角色信息"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :user_id, type: Integer
          requires :role_id, type: Integer
        end
        post 'edit_member_role' do
          authenticate!

          project = Project.find("#{params[:id]}")

          my_member = project.member_principals.where("users.id=#{current_user.id}").first

          #3管理 4开发 5报告
          if !(my_member && my_member.roles[0] && my_member.roles[0].id == 3 ) || project.user_id == params[:user_id] || !(params[:role_id] == 3 || params[:role_id] == 4 || params[:role_id] == 5)
            present :status, -1
          else
            ps = ProjectsService.new

            status = ps.modify_user_project_role params

            present :status, status
          end
        end

        desc "新建项目"
        params do
          requires :token, type: String
          requires :name, type: String, desc: '项目名称'
        end
        post 'create' do
          authenticate!

          ps = ProjectsService.new

          status = ps.createNewProject params,current_user


          present :status, 0

        end

        desc "加入项目"
        params do
          requires :token, type: String
          requires :invite_code, type: String, desc: '邀请码'
          requires :role_id, type: Integer, desc: '身份'
        end
        post "join_project" do
          authenticate!

          role_id = params[:role_id]

          if role_id != 3 && role_id != 4 && role_id != 5
            {status:-1,message:"请至少选择一个角色"}
          else
            ps = ProjectsService.new
            status = ps.join_project({role: role_id, openid: params[:openid], invite_code: params[:invite_code]}, current_user)

            {status:status, message:ProjectsService::JoinProjectError.message(status)}
          end

          # {status:-1, message: '该功能将在近日开放，敬请期待！' }
        end

        desc "项目单个未审核用户信息"
        params do
          requires :token, type: String
          requires :project_id, type: Integer, desc: "项目id"
          requires :user_id, type: Integer, desc: "用户id"
        end
        post 'review_member_info' do
          authenticate!

          ps = ProjectsService.new
          result = ps.get_reviewer_info(params,current_user)
          present :data, result[:reviewer], with: Mobile::Entities::User
          present :status, result[:status]
        end

        desc "处理管理或开发的身份申请"
        params do
          requires :token, type: String
          requires :project_id, type: Integer, desc: "项目id"
          requires :user_id, type: Integer, desc: "用户id"
          requires :type, type: Integer, desc: "同意或拒绝"
        end
        post 'deal_join_apply' do
          authenticate!

          ps = ProjectsService.new
          result = ps.deal_join_apply(params,current_user)

          present :status, result[:status]
          present :message, result[:message]
        end

        desc "发布项目帖子"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :text, type: String
        end
        post ':id/publishnote' do
          authenticate!

          project = Project.find("#{params[:id]}")

          boards = project.boards.includes(:last_message => :author).all
          if project.boards.empty?
            board = project.boards.build
            board.name = "项目讨论区"
            board.description = project.name.to_s
            board.course_id = -1
            if board.save
              boards = project.boards.includes(:last_message => :author).all
            end
          end

          board = boards.first

          message = Message.new
          message.author = current_user
          message.board = board

          tmpparams = {}
          tmpparams['subject'] = params[:title]
          tmpparams['content'] = params[:text]

          message.safe_attributes = tmpparams

          message.save!

          present :status, 0

        end

        desc "删除项目成员"
        params do
          requires :id, type: Integer
          requires :token, type: String
          requires :user_id, type: Integer
        end
        post ':id/deletemember' do
          authenticate!

          status = -1

          if(current_user.id != params[:user_id].to_i)
            #权限
            project = Project.find("#{params[:id]}")
            if project.user_id != params[:user_id].to_i

              my_member = project.member_principals.where("users.id=#{current_user.id}").first

              roles_ids = []
              my_member.roles.each do |role|
                roles_ids << role.id
              end

              if my_member && roles_ids.include?(3)
                #删除该成员
                ps = ProjectsService.new
                status = ps.project_delete_member(project,params[:user_id].to_i,current_user)
              else
                status = -2
              end
            else
              status = -3
            end
          else
            status = -4
          end

          out = {status: status}
          message = case status
                      when 0; "删除成功"
                      when 1; "该用户不在该项目中"
                      when -1; "您还未登录"
                      when -2; "您没有权限"
                      when -3; "不能删除项目创建者"
                      when -4; "不能删除自己"
                      else; "未知错误，请稍后再试"
                    end
          out.merge(message: message)
        end

        desc "退出项目"
        params do
          requires :id, type: Integer
          requires :token, type: String
        end
        post ':id/quit' do
          authenticate!

          project = Project.find("#{params[:id]}")

          ps = ProjectsService.new
          status = ps.exit_project(project,current_user)

          out = {status: status}
          message = case status
                      when 0; "退出项目成功"
                      when -3; "您不是该项目成员"
                      when -1; "您还未登录"
                      when -2; "项目创建者不能退出项目"
                      else; "未知错误，请稍后再试"
                    end
          out.merge(message: message)
        end

      end
    end
  end
end