# == Schema Information
#
# Table name: orders
#
#  id           :bigint           not null, primary key
#  sn           :string(255)      not null
#  client_id    :integer          not null
#  due_date     :datetime
#  confirmed_at :datetime
#  finished_at  :datetime
#  created_by   :string(255)
#  status       :integer          not null
#  remark       :text(16777215)
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#
class Order < ApplicationRecord
  has_many :order_items
  belongs_to :client

  validates :sn, presence: true, uniqueness: true
  validates :client_id, presence: true
  validates :due_date, presence: true
  validates_associated :client

  before_create :init_before_create

  serialize :remark # [{created_by: "xxx", created_at: xxx, text: ''}]

  def remark=(value)
    if value.present?
      remark_info = { created_by: User.current.true_name, created_at: Time.now, text: value }
      old_value = self.remark || []
      old_value.append(remark_info)
      write_attribute(:remark, old_value)
    end
  end

  private

  def init_before_create
    self.remark ||= []
    self.status = 0
    self.due_date = self.due_date.end_of_day if self.due_date
  end
end
