#coding=utf-8

class ProjectsService

  include ApplicationHelper
  include ApiHelper
  include ActionView::Helpers::DateHelper
  include ProjectsHelper

  #获取指定用户的项目列表
  def user_projects(user)
    projects = user.projects.not_deleted.select("projects.*,(SELECT MAX(updated_at)  FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS updated_at ").order("updated_at desc")
    projects
  end

  #显示项目
  def show_project(params,current_user)
    project = Project.find(params[:id])
    project.generate_invite_code
    project.generate_qrcode

    project
  end

  def send_wechat_create_project_notice user,project
    count = ShieldWechatMessage.where("container_type='User' and container_id=#{user.id} and shield_type='Project' and shield_id=#{project.id}").count
    Rails.logger.info "!!!!!!!!!!!!!!!!!!!!!!#{project}"
    if count == 0
      ws = WechatService.new
      title = "恭喜您创建项目成功。"
      ws.create_project_notice user.id, "create_project_notice", project.id,title, project.name, format_time(project.created_on),"点击查看项目详情。"
    end
  end


  def createNewProject params,user
    status = -1
    issue_custom_fields = IssueCustomField.sorted.all
    trackers = Tracker.sorted.all
    project = Project.new

    project[:name] = params[:name]
    project[:description] = ''
    project[:is_public] = '0'  #公开
    project[:project_type] = 0
    project[:project_new_type] = 1
    project[:identifier] = Project.next_identifier if Setting.sequential_project_identifiers?

    project.organization_id = params[:organization_id]
    project.user_id = user.id

    # if validate_parent_id && @project.save
    if project.save
      p = Project.find("#{project.id}")
      send_wechat_create_project_notice user,p
      r = Role.givable.find_by_id(Setting.new_project_user_role_id.to_i) || Role.givable.first
      m = Member.new(:user => user, :roles => [r])
      # project's score
      if ProjectScore.where("project_id=?", project.id).first.nil?
        ProjectScore.create(:project_id => project.id, :score => false)
      end
      # end
      project_info = ProjectInfo.new(:user_id => user.id, :project_id => project.id)
      user_grades =  UserGrade.create(:user_id => user.id, :project_id => project.id)
      project_status = ProjectStatus.create(:project_id => project.id, :watchers_count => 0, :changesets_count => 0, :project_type => project.project_type,:grade => 0)
      project.members << m
      project.project_infos << project_info
      status = 0
    end
    status
  end

  #修改项目成员角色
  def modify_user_project_role params
    status = -1

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

    member = project.member_principals.includes(:roles, :principal).where("user_id=?",params[:user_id]).first

    if member
      member.member_roles[0].role_id = params[:role_id]


      role = Role.find(params[:role_id])
      if role.allowed_to?(:is_manager)
        projectInfo = ProjectInfo.new(:user_id => member.user_id, :project_id => project.id)
        projectInfo.save
      else
        user_admin = ProjectInfo.where("user_id = ? and project_id = ?", member.user_id, project.id)
        if user_admin.size > 0
          user_admin.each do |user|
            user.destroy
          end
        end
      end

      if member.member_roles[0].save
        status = 0
      end
    end
    status
  end

  class JoinProjectError < Errors
    define_error [
                     0, '您已成功加入项目',
                     1, '您的邀请码不正确',
                     2, '您还未登录',
                     3, '您已经是该项目的管理人员',
                     4, '您已经是该项目的开发人员',
                     5, '您已经是该项目的报告人员',
                     6, '该项目不存在或已被删除啦',
                     7, '您的申请已提交,请等待管理员审批',
                     8, '您已经发送过申请了,请耐心等待',
                     '未知错误,请稍后再试'
                 ]
  end

  #加入项目结果
  def send_wechat_join_project_notice user,project,role_id,result
    count = ShieldWechatMessage.where("container_type='User' and container_id=#{user.id} and shield_type='Project' and shield_id=#{project.id}").count
    if count == 0
      result_name = result == 0 ? "已同意" : "已拒绝"
      if result == 0
        title = "恭喜您加入项目成功。"
        remark = "点击查看项目详情。"
        uid = 0
        type = "project"
      else
        title = "很遗憾您未能成功加入项目。"
        remark = "点击查看申请详情。"
        uid = user.id
        type = "review_project_member"
      end
      ws = WechatService.new
      ws.join_project_notice user.id, "project", project.id,title, project.name,result_name, remark,uid
    end
  end

  def join_project params,current_user
    status = -1
    project = Project.find_by_invite_code(params[:invite_code]) if params[:invite_code]

    if project
      if project[:is_delete] == 1
        status = 6
      else
        if current_user.member_of?(project) #如果已经是成员
          member = project.member_principals.includes(:roles, :principal).where("user_id=?",current_user.id).first
          status = member.member_roles[0].role_id

          #将之前的申请都改为已拒绝
          applied_messages = AppliedMessage.where(:project_id => project.id, :status => true, :applied_user_id=>current_user.id,:applied_type => "AppliedProject")
          applied_messages.update_all(:status=>5)
        else
          if params[:invite_code].present?

            if params[:role] == 5
              members = []
              user_grades = []
              project_info = []

              user_grades << UserGrade.new(:user_id => current_user.id, :project_id => project.id)
              project.user_grades << user_grades unless user_grades.first.user_id.nil?

              members << Member.new(:role_ids => ["5"], :user_id => current_user.id)
              project.members << members

              project_info << ProjectInfo.new(:user_id => current_user.id, :project_id => project.id)
              project.project_infos << project_info

              status = 0
              send_wechat_join_project_notice current_user,project,5,0

              #将之前的申请都改为已拒绝
              applied_messages = AppliedMessage.where(:project_id => project.id, :status => true, :applied_user_id=>current_user.id,:applied_type => "AppliedProject")
              applied_messages.update_all(:status=>5)
            else
              if !AppliedProject.where(:project_id => project.id, :user_id => current_user.id).first.nil?
                status = 8
              else
                AppliedProject.create(:user_id => current_user.id, :project_id => project.id, :role => params[:role])

                status = 7
              end
            end
          else
            status = 4
          end
        end
      end
    else
      status = 1
    end
    status
  end

  def get_project_review_members(project,role_id,current_user)
    review_members = []

    if role_id == 3 || role_id == 4

      #AppliedMessage.where(:applied_id => @applied_message.applied_id, :project_id => @applied_message.project_id, :status => 1,
      #:applied_type => "AppliedProject")


      apply_messages = AppliedMessage.where(:user_id => current_user.id, :project_id => project.id, :status => 1, :role=>role_id)

      apply_messages.each do |m|
        user = User.find(m.applied_user_id)

        if user
          img_url = "/images/"+url_to_avatar(user)
          gender = user.user_extensions.gender.nil? ? 0 : user.user_extensions.gender
          work_unit = get_user_work_unit user
          location = get_user_location user
          review_members << {:id => user.id, :img_url => img_url, :nickname => user.login, :gender => gender,
                        :work_unit => work_unit, :mail => user.mail, :location => location,
                        role_name: "",
                        name: user.show_name,
                        roles_id: role_id,
                        :brief_introduction => user.user_extensions.brief_introduction,:realname=>user.realname,:real_name=>user.realname}
        end
      end
    end

    review_members
  end

  def get_reviewer_info params,current_user
    status = -1
    info = nil
    project = Project.find(params[:project_id])
    if project
      # messages = AppliedProject.where(:project_id=> project.id, :user_id=>params[:user_id]).first
      #status  1未处理 5拒绝 7同意
      applied_message = AppliedMessage.where(:user_id => current_user.id, :project_id => project.id, :applied_user_id=>params[:user_id],:applied_type => "AppliedProject").last
      if applied_message
        status = applied_message.status
        user = User.find(params[:user_id])
        if user
          img_url = "/images/"+url_to_avatar(user)
          gender = user.user_extensions.gender.nil? ? 0 : user.user_extensions.gender
          work_unit = get_user_work_unit user
          location = get_user_location user
          info =  {:id => user.id, :img_url => img_url, :nickname => user.login, :gender => gender,
                   :work_unit => work_unit, :mail => user.mail, :location => location,
                   role_name: "",
                   name: user.show_name,
                   roles_id: applied_message.role,
                   :brief_introduction => user.user_extensions.brief_introduction,:realname=>user.realname}
        end
      end
    end

    {status:status,reviewer:info}
  end

  def deal_join_apply params,current_user
    status = -1
    message = ""

    project = Project.find(params[:project_id])
    user =  User.find(params[:user_id])
    if project
        applied_messages = AppliedMessage.where(:user_id => current_user.id, :project_id => project.id, :status => 1, :applied_user_id=>user.id,:applied_type => "AppliedProject")
        apply_message = applied_messages.first
        if apply_message
          if user.member_of?(project)
            message = "已经是该项目的成员了"
            u_member = project.member_principals.includes(:roles, :principal).where("user_id=?",params[:user_id]).first
            if u_member.member_roles[0].role_id == 5
              applied_messages.update_all(:status=>5)
            else
              applied_messages.update_all(:status=>7)
            end
          else
            applied_project = apply_message.applied
            ap_role = applied_project.try(:role)
            if ap_role
              rolename = ap_role == 3 ? "管理人员" : "开发人员"
              if params[:type] == 0
                #同意
                members = []
                user_grades = []
                project_info = []
                members << Member.new(:role_ids => ["#{ap_role}"], :user_id => user.id)
                user_grades << UserGrade.new(:user_id => user.id, :project_id => project.id)
                role = Role.find(ap_role)
                project_info << ProjectInfo.new(:project_id => project.id, :user_id => user.id) if role.allowed_to?(:is_manager)
                project.members << members
                project.project_infos << project_info
                project.user_grades << user_grades unless user_grades.first.user_id.nil?

                # 添加成功后所有管理员收到的消息状态都要更新
                applied_messages.update_all(:status => 7, :viewed => true)
                # 添加成功后,申请人收到消息
                AppliedMessage.create(:user_id => user.id, :applied_type => "AppliedProject", :applied_id => applied_project.id ,
                                      :status => 6, :viewed => false, :applied_user_id => current_user.id, :role => applied_project.role, :project_id => applied_project.project_id)

                message = "您已同意"+rolename+user.show_name+",加入项目"

                send_wechat_join_project_notice user,project,ap_role,0

              else
                #拒绝
                AppliedMessage.create(:user_id => user.id, :applied_type => "AppliedProject", :applied_id => applied_project.id ,:status => 4,
                                      :viewed => false, :applied_user_id => current_user.id, :role => applied_project.role, :project_id => applied_project.project_id)

                applied_messages.update_all(:status => 5, :viewed => true)
                applied_project.delete

                message = "您已拒绝"+rolename+user.show_name+",加入项目"

                send_wechat_join_project_notice user,project,ap_role,1
              end

              status = 0
            else
              message = "该申请不存在或已被处理"
            end
          end
        else
          message = "该申请不存在或已被处理"
        end
    else
      message = "该项目不存在或已被删除"
    end

    {:status => status,:message => message}
  end

  def send_wechat_project_issue_notice user,project,issue_id,issue_title,priority_id
    count = ShieldWechatMessage.where("container_type='User' and container_id=#{user.id} and shield_type='Project' and shield_id=#{project.id}").count
    if count == 0
      title = "您有新的issue需要解决。"
      remark = "点击详情查看issue。"

      case priority_id
        when "1"
          priority = "低"
        when "2"
          priority = "正常"
        when "3"
          priority = "高"
        when "4"
          priority = "紧急"
        when "5"
          priority = "立刻"
      end

      ws = WechatService.new
      ws.project_issue_notice user.id, "issues", issue_id,title, issue_title,priority, remark
    end
  end

  #删除项目成员
  def project_delete_member project,user_id,current_user
    if current_user.nil?
      state = -1
      return state
    end

    member = project.members.where("user_id=?",user_id).first

    if member != nil
      member.destroy
      # end
      user_admin = ProjectInfo.where("user_id = ? and project_id = ?", member.user_id, project.id)
      if user_admin.size > 0
        user_admin.each do |user|
          user.destroy
        end
      end
      user_grade = UserGrade.where("user_id = ? and project_id = ?", member.user_id, project.id)
      if user_grade.size > 0
        user_grade.each do |grade|
          grade.destroy
        end
      end
      # 移出的时候删除申请消息,不需要删除消息,所以不必要关联删除
      applied_projects = AppliedProject.where(:project_id => project.id, :user_id => member.user_id).first
      unless applied_projects.nil?
        applied_projects.delete
      end
      #移出项目发送消息
      ForgeMessage.create(:user_id => member.user_id, :project_id => project.id, :forge_message_type => "RemoveFromProject", :viewed => false, :forge_message_id => current_user.id)
      return 0
    else
      return 1
    end
  end

  def exit_project project,user
    if user.nil?
      state = -1
      return state
    end

    if project.user_id == user.id
      state = -2
      return state
    end

    members = Member.where(:user_id => user.id, :project_id=>project.id).first
    if members != nil
      members.destroy
      # 移出的时候删除申请消息,不需要删除消息,所以不必要关联删除
      applied_projects = AppliedProject.where(:project_id => project.id, :user_id => members.user_id).first
      unless applied_projects.nil?
        applied_projects.delete
      end
      state = 0
    else
      state = -3
    end
    return state
  end

end