#encoding: utf-8
# 使用请了解以下描述,不清楚请@Hjqreturn
#
# user_id: 信息接收人
# trigger_user_id: 信息的触发者,具体情况可能有所不同。eg:产生消息的用户ID;处理消息的用户ID等
# container_id:消息实体的ID。eg:issue的id
# container_type:消息实体的类型。eg:“Issue","Board"
# parent_container_id:消息实体的父实体消息的id,是为了生成url时使用,避免反复查数据库。eg:message中的board 的id
# parent_container_type:消息实体的父实体消息类型,便于分类。eg:“Message","Board"
# belong_container_id:消息实体所属的实体ID。eg:project_id,course_id,organization_id
# belong_container_type:消息实体所属的实体类型。eg:“Project”,“Course”,"Shixun"
# status:申请类消息实体的状态。eg:1:“已处理”:0:“未处理”  or 系统类消息的处理结果  1:同意  2:拒绝  3:更改(学校、部门申请结果), 4: 删除(部门被删除)
# tiding_type: 消息类型 "Apply":审核,  "HomeworkCommon":作业,  "Exercise":试卷,  "Poll":问卷, GraduationTopic:毕设选题, GraduationTask:毕设任务, "Project":项目,  "Comment":评论,  "Journal":留言,
#                     "Mentioned":@,  "Praise":赞,  "Tread":踩,   "Fan":粉丝,   "System" 系统,
# 新版:通知:System  审核:Apply   课堂提醒:HomeworkCommon、Exercise、Poll、GraduationTopic、GraduationTask  项目提醒:Project   互动提醒:Comment、Mentioned、Praise、Fan
# viewed:消息是否已读。eg:1 -> 已读; 0 -> 未读
#
class Tiding < ActiveRecord::Base
  attr_accessible :belong_container_id, :belong_container_type, :container_id, :container_type, :parent_container_id,
                  :parent_container_type, :status, :trigger_user_id, :user_id, :tiding_type, :viewed, :extra
  default_scope :order => 'created_at desc'
  belongs_to :container, :polymorphic => true
  belongs_to :user
  include ApplicationHelper

  scope :course_tiding, lambda {where(tiding_type: %W{HomeworkCommon Exercise Poll Comment})}

  # scope :sorted, lambda { order(*User.fields_for_order_statement)}
  # Tiding.order(params[:search], 1)
  # scope :order, lambda {|arg, type|
  #   if arg.blank?
  #     where(nil)
  #   else
  #     pattern = "%#{arg.to_s.strip}%"
  #     #where(" LOWER(concat(lastname, firstname)) LIKE :p ", :p => pattern)
  #     if type == "0"
  #       where(" LOWER(login) LIKE '#{pattern}' ")
  #     elsif type == "1"
  #       where(" LOWER(concat(lastname, firstname)) LIKE '#{pattern}' ")
  #     elsif type == "3"
  #       where(" LOWER(concat(lastname, firstname,login)) LIKE '#{pattern}' ")
  #     else
  #       where(" LOWER(mail) LIKE '#{pattern}' ")
  #     end
  #   end
  # }

  def user
    User.where(:id => self.trigger_user_id).first
  end

  def key_word
    case self.container_type
      when "ApplyUserAuthentication"
          user = User.where(:id => self.trigger_user_id).first unless self.trigger_user_id == 0
          ue = UserExtensions.where(:user_id => user.id).first unless self.trigger_user_id == 0
          technical_title = ue.show_identity unless self.trigger_user_id == 0
          if self.tiding_type == "Apply"
            container.auth_type == 1 ? ('申请实名认证:' + user.show_real_name + " " + user.ID_number) : ('申请职业认证:' + (ue.school.present? ? ue.school.name : '') + (ue.department_id.present? ? ( "_" + ue.department.name) : '') + " " + technical_title)
          else
            container.auth_type == 1 ? ('你提交的实名认证申请,审核' + (self.status == 1 ? '已通过' : ('未通过' + "&nbsp;&nbsp;&nbsp;&nbsp;" + '原因:' + container.try(:remarks).to_s))) : ('你提交的职业认证申请,审核' + (self.status == 1 ? '已通过' : ('未通过' + "&nbsp;&nbsp;&nbsp;&nbsp;" + '原因:' + container.try(:remarks).to_s)))
          end
      when "CancelUserAuthentication"
        user = User.where(:id => self.user_id).first
        "取消了你的实名认证:" + user.show_real_name.to_s + " " + user.ID_number.to_s
      when "CancelUserProCertification"
        user = User.where(:id => self.user_id).first
        ue = user.user_extensions
        "取消了你的职业认证:" + (ue.school.present? ? ue.school.name : '') + (ue.department_id.present? ? ( "_" + ue.department.name) : '') + " " + ue.show_identity
      when 'JoinCourse', "DealCourse", "StudentJoinCourse", "TeacherJoinCourse"
        course_name = Course.find(container_id).name
        if self.container_type == "JoinCourse"
          "申请加入课堂:" + course_name + "(" + (self.extra.to_i == 9 ? "教师" : "助教") + ")"
        elsif self.container_type == "DealCourse"
          "你提交的加入课堂申请:" + course_name + "(" + (self.extra.to_i == 9 ? "教师" : "助教") + "), 审核" + (self.status == 1 ? "已通过" : "未通过")
        elsif self.container_type == "StudentJoinCourse"
          "加入了课堂:" + course_name + "(学生)"
        elsif self.container_type == "TeacherJoinCourse"
          self.user.try(:show_real_name).to_s + "将你加入课堂:" + course_name + "(" + (self.extra.to_i == 9 ? "教师" : (self.extra.to_i == 7 ? "助教" : "学生")) + ")"
        end
      when "ApplyAddDepartment"
        if self.tiding_type == "Apply"
          "申请添加二级单位:" + container.name.to_s + "(" + School.where(:id => container.school_id).first.try(:name).to_s + ")"
        else
          case self.status
            when 1
              "你提交的添加二级单位申请:" + container.name.to_s + "(" + School.where(:id => container.school_id).first.try(:name).to_s + ")" + ",审核已通过"
            when 2
              "你提交的添加二级单位申请:" + container.name.to_s + "(" + School.where(:id => container.school_id).first.try(:name).to_s + ")" + ",审核未通过" + (self.extra.nil? ? "" : "&nbsp;&nbsp;&nbsp;&nbsp;原因:#{self.extra}")
            when 3
              "你提交的添加二级单位申请:" + container.name.to_s + "(" + School.where(:id => container.school_id).first.try(:name).to_s + ")" + ",已被更改为:" + self.extra
          end
        end
      when "ApplyAddSchools"
        if self.tiding_type == "Apply"
          ("申请添加单位:"  + container.name)
        else
          case self.status
            when 1
              "你提交的添加单位申请:" + container.name + ",审核已通过"
            when 2
              "你提交的添加单位申请:" + container.name + ",审核未通过" + (self.extra.nil? ? "" : "&nbsp;&nbsp;&nbsp;&nbsp;原因:#{self.extra}")
            when 3
              "你提交的添加单位申请:" + container.name + ",已被更改为:" + self.extra
          end
        end
      when "ApplyAction"
        case self.parent_container_type
          when "ApplyShixun"
            shixun_name = Shixun.find(self.parent_container_id).name
            self.tiding_type == "System" ? ("你提交的实训发布申请:" + shixun_name + ",审核" + (self.status == 1 ? '已通过':('未通过' + "&nbsp;&nbsp;&nbsp;&nbsp;" + '原因:' + container.try(:reason).to_s))) : ("申请发布实训:"+ shixun_name)
          when "ApplySubject"
            shixun_name = Subject.find(self.parent_container_id).name
            self.tiding_type == "System" ? ("你提交的实训课程发布申请:" + shixun_name + ",审核" + (self.status == 1 ? '已通过':('未通过' + "&nbsp;&nbsp;&nbsp;&nbsp;" + '原因:' + container.try(:reason).to_s))) : ("申请发布实训课程:"+ shixun_name)
          when "TrialAuthorization"
            self.tiding_type == "System" ? ("你提交的试用授权申请:审核" + (self.status == 1 ? '已通过':('未通过' + "&nbsp;&nbsp;&nbsp;&nbsp;" + '原因:' + container.try(:reason).to_s))) : ("提交了试用授权申请")
        end
      when "Course", "Shixun","Subject"
        name = self.container_type == "Course" ? "课堂" : (self.container_type == "Shixun" ? "实训" :"实训课程")
        "成功创建了" + name + ":" + container.name
      when "ArchiveCourse"
        course_name = Course.find(container_id).name
        "你的课堂已经归档:" + course_name
      when "JournalsForMessage"
        if self.tiding_type != "Mentioned"
          case self.parent_container_type
            when "Principal"
              if container.m_parent_id.present?
                (container.parent.try(:m_parent_id).present? ? "评论了你的回复:" : "评论了你的留言:") + message_content(container.notes)
              else
                "给你" + (container.private == 0 ? "留言:" : "私信:") + message_content(container.notes)
              end
            when "HomeworkCommon"
              (container.m_parent_id.present? ? "评论了你的回复:" : "评论了你发布的作业:") + message_content(container.notes)
            when "GraduationTopic"
              (container.m_parent_id.present? ? "评论了你的回复:" : "评论了你发布的毕设选题:") + message_content(container.notes)
            when "StudentWorksScore"
              if container.m_parent_id.present?
                "评论了你的回复:" + message_content(container.notes)
              else
                "评论了你发布的作品评语:" + message_content(container.notes)
              end
          end
        else
          "@了你:" + message_content(container.notes)
        end
      when 'Message'
        if self.tiding_type == "Mentioned"
          "@了你:" + message_content(container.content)
        else
          if container.parent.present?
            if container.parent_id == container.root_id
              "评论了你的帖子:" + message_content(container.content)
            else
              "评论了你的回复:" + message_content(container.content)
            end
          else
            "发布了帖子:" + container.subject
          end
        end
      when 'Memo'
        if container.parent.present?
          if container.parent_id == container.root_id
            "评论了你的帖子:" + message_content(container.content)
          else
            "评论了你的回复:" + message_content(container.content)
          end
        else
          "发布了帖子:" + container.subject
        end
      when 'Watcher'
        "关注了你"
      when "PraiseTread"
        try = self.parent_container_type.constantize
        object = try.find(self.parent_container_id)
        case self.parent_container_type
          when "Challenge"
            if self.container
              (self.container.praise_or_tread == 1 ? "赞" :"踩") + "了你发布的实训任务:" + object.shixun.name + ",第" + object.position.to_s + "关"
            end
          when "Memo","Message"
            "赞了你" + (object.parent_id.present? ? ("的评论:" + message_content(object.content)) : ("发布的帖子:" + object.subject))
          when "HomeworkCommon"
            "赞了你发布的作业:" + object.name
          when "JournalsForMessage"
            "赞了你" + (object.jour_type == "Principal" && !object.m_parent_id.present? ? "的留言:" : "的评论:") + message_content(object.notes)
          when "Discuss"
            "赞了你的评论:" + message_content(object.content)
          when "Issue"
            "赞了你发布的项目Issue:" + object.subject
          when "Journal"
            "赞了你的回复" + (object.notes.present? ? ":#{message_content(object.notes)}" :"")
        end
      when "Discuss"
         (self.container.parent_id.present? ?  "评论了你的回复:" : "评论了你发布的实训:" ) + message_content(container.content)
      when 'Grade'
        case self.parent_container_type
          when 'Avatar'
            "首次上传头像获得金币奖励:"
          when 'Phone'
            "首次绑定手机号码获得金币奖励:"
          when 'Attendance'
            "签到成功获得金币奖励:"
          when 'Mail'
            "首次绑定邮箱获得金币奖励:"
          when 'Account'
            "首次填写基本资料获得金币奖励:"
          when 'Answer'
            game = Game.where(:id => self.parent_container_id).first
            if game.present?
              "查看实训#{game.challenge.shixun.name}第#{game.challenge.position}关的参考答案消耗金币: "
            else
              # 之所以这样处理,是因为消息的类型是不能和实体绑定,没有关联删除
              "查看实训的参考答案消耗金币"
            end
          when 'Game'
            game = Game.where(:id => self.parent_container_id).first
            if game.present?
              "通过实训#{game.challenge.shixun.name}的第#{game.challenge.position}关获得金币奖励:"
            end
          when 'Memo'
            "发布的评论或者帖子获得平台奖励:"
          when 'Discusses'
            "发布的评论获得金币奖励:"
          when 'testSet'
            game = Game.where(:id => self.parent_container_id).first
            position = game.nil? ? "--" : game.challenge.position
            "查看实训的第#{position}关的隐藏测试集消耗的金币:"
          when 'shixunPublish'
            "发布实训#{grade_shixun_name(self.parent_container_id)}获得的奖励:"
          when 'Star'
            "给实训评分获得的随机奖励:"
          when 'Feedback'
            "反馈的问题获得平台奖励:"
          when 'Authentication'
            "用户首次完成实名认证获得的奖励:"
          when 'Professional'
            "用户首次完成职业认证获得的奖励:"
        end + container.score.to_s + "金币"
      when 'JoinProject', "DealProject", "ReporterJoinProject", "ManagerJoinProject"
        project_name = Project.find(container_id).name
        if self.container_type == "JoinProject"
          "申请加入项目:" + project_name + "(" + (self.extra.to_i == 3 ? "管理人员" : "开发人员") + ")"
        elsif self.container_type == "DealProject"
          "你提交的加入项目申请:" + project_name + "(" + (self.extra.to_i == 3 ? "管理人员" : "开发人员") + "), 审核" + (self.status == 1 ? "已通过" : "未通过")
        elsif self.container_type == "ReporterJoinProject"
          "加入了项目:" + project_name + "(报告人员)"
        elsif self.container_type == "ManagerJoinProject"
          self.user.try(:show_real_name).to_s + "将你加入项目:" + project_name + "(" + (self.extra.to_i == 3 ? "管理人员" : (self.extra.to_i == 4 ? "开发人员" : "报告人员")) + ")"
        end
      when "Journal"
        if self.tiding_type == "Mentioned"
          "@了你:" + message_content(container.notes)
        elsif self.tiding_type == "Comment"
          "评论了你" + (container.parent.present? ? "的回复:" : "发布的项目issue:") + message_content(container.notes)
        else
          "更新了Issue:#{container.issue.subject}"
        end
      when 'Issue'
        "指派了Issue给你:" + container.subject
      when 'PullRequest'
        if self.tiding_type == "Apply"
          "提交了PullRequest:" + container.try(:title).to_s
        else
          str = self.status == 2 ? "接受" : (self.status == 3 ? "重新打开" : "关闭")
          "#{str}了PullRequest:" + container.try(:title)
        end
      when 'SendMessage'
        "申请了新镜像:" + self.extra.to_s
      when 'Poll'
        case self.parent_container_type
          when 'PollPublish'
            "发布了问卷:"
          when 'NearlyEnd'
            "问卷的截止时间快到啦:"
          when 'CommitPoll'
            "提交了问卷答题:"
        end + container.polls_name
      when 'Exercise'
        case self.parent_container_type
          when 'ExercisePublish'
            "发布了试卷:"
          when 'NearlyEnd'
            "试卷的截止时间快到啦:"
          when 'CommitExercise'
            "提交了试卷答题:"
          when 'ExerciseScore'
            "评阅了你的试卷:"
        end + container.exercise_name
      when 'StudentGraduationTopic'
        "选择了毕设选题:" + container.graduation_topic.try(:name).to_s
      when 'DealStudentTopicSelect'
        topic = GraduationTopic.where(:id => parent_container_id).first
        "你提交的选题申请:#{topic.try(:name).to_s},审核#{status == 2 ? '未通过' : '已通过'}"
      when 'GraduationTask'
        case self.parent_container_type
          when 'TaskPublish'
            "发布了毕设任务:" + container.name
          when 'NearlyEnd'
            "毕设任务的提交截止时间快到啦:" + container.name
          when 'NearlyLateEnd'
            "毕设任务的补交截止时间快到啦:" + container.name
          when 'CrossComment'
            "开启了交叉评阅:" + container.name
        end
      when 'GraduationWork'
        (extra.nil? ? "提交了作品:" : "重新提交了作品,建议您重新评阅:") + container.graduation_task.try(:name).to_s
      when 'GraduationWorkScore'
        "评阅了你的作品:" + self.container.graduation_work.graduation_task.try(:name).to_s
      when 'HomeworkCommon'
        case self.parent_container_type
          when 'AnonymousComment'
            "开启了作业匿评:" + container.name
          when 'AnonymousCommentFail'
            "开启作业匿评失败:" + container.name + ",<br/>原因:#{self.extra}"
          when 'AnonymousAppeal'
            "开启了匿评申诉:" + container.name
          when 'HomeworkPublish'
            "发布了作业:" + container.name
          when'NearlyEnd'
            "作业的提交截止时间快到啦:" + container.name
          when 'AppealNearlyEnd'
            "作品的匿评申诉时间快到啦:" + container.name
          when 'EvaluationNearlyEnd'
            "作业的匿评截止时间快到啦:" + container.name
          else
            logger.error "error type: 1"
        end
      when 'StudentWork'
        (extra.nil? ? "提交了作品:" : "重新提交了作品,建议您重新评阅:") + container.homework_common.try(:name).to_s
      when 'StudentWorksScore'
        case extra
          when "1", "2"
            '评阅了你的作品:'
          when "3"
            '有人匿评了你的作品:'
        end + self.container.student_work.homework_common.try(:name).to_s
      when 'ChallengeWorkScore'
        '调整了你的作品分数:' + self.container.comment
      when 'StudentWorksScoresAppeal'
        work = StudentWork.where(:id => self.parent_container_id).first
        if work
          case self.parent_container_type
            when "UserAppealResult"
              (self.status == 1 ? "同意了你提交的匿评申诉申请:" : "拒绝了你提交的匿评申诉") + work.homework_common.try(:name)
            when "AppealResult"
              (self.status == 1 ? "同意了他人对你的匿评申诉申请:" : "拒绝了他人对你的匿评申诉") + work.homework_common.try(:name)
            when "StudentWork"
              case self.tiding_type
                when 'Apply'
                  "发起了匿评申诉申请:" + work.homework_common.try(:name)
                when 'HomeworkCommon'
                  "有人对你的匿评发起了申诉:" + work.homework_common.try(:name)
              end
          end
        end
      when "ChallengeWorkScore"
        "  "
      when 'Department'
        "你选填的二级单位:#{self.container.try(:name)}(#{self.container.try(:school).name})因不符合规范,已被系统删除.请重新选择"
      else
        logger.error "error type: 1"
    end
  end


  # status 0 待处理  # status 1 已处理
  def process
    process = []
    case self.status
      when 0
        process << "待处理"
        process << 'edu-filter-btn-red'
      else
        process << "已处理"
        process << 'edu-filter-btn-green'
    end
  end

  def title
    case tiding_type
    when "System"
      "通知"
    when "Apply"
      "审核"
    when "HomeworkCommon","Exercise","Poll"
      "课堂提醒"
    when "Project"
      "项目提醒"
    when "Comment","Mentioned","Praise","Fan"
      "互动提醒"
    end
  end

#
  def description
    case container_type
      when "Message"
        container.updated_on
      when "Journal","Issue"
        container.created_on
      else
        self.updated_at
    end
  end
end