# encoding:utf-8
class ScaleResult < ActiveRecord::Base
  has_paper_trail
  self.table_name = "scale_result"
  belongs_to :wx_user
  belongs_to :scale_user, :foreign_key => :user_id

  def wx_user_contact
    return "-" if wx_user.blank?
    user = wx_user.user
    return "-" if user.blank?
    contact = user.tel
    contact = user.email if contact.blank?
    contact.blank? ? "-" : contact
  end

  # 从测量结果中获取时间戳
  def measurement_time
    return nil if result.blank?
    begin
      data = JSON.parse(result)
      timestamp = data['timestamp']
      return nil if timestamp.blank?
      Time.parse(timestamp)
    rescue => e
      nil
    end
  end

  # 格式化数值，保留2位小数
  def fmt(val)
    return '-' if val.nil?
    val.is_a?(Numeric) ? format('%.2f', val) : val.to_s
  end

  # 格式化显示测量结果（列表简要版）
  def result_summary
    return '-' if result.blank?
    begin
      d = JSON.parse(result)
      "体重:#{fmt(d['weight_kg'])}kg BMI:#{fmt(d['bmi'])} 体脂:#{fmt(d['bodyFatPercent'])}%"
    rescue
      '-'
    end
  end

  # 格式化显示测量结果（详情完整版）
  def result_formatted
    return '-' if result.blank?
    begin
      d = JSON.parse(result)
      userdata = d['userdata'] || {}
      
      html = '<table class="table table-striped table-condensed" style="font-size:13px;">'
      
      # 用户信息
      if userdata.present?
        html += '<tr><th colspan="4" style="background:#f5f5f5;">👤 用户信息</th></tr>'
        html += "<tr><td><b>昵称</b></td><td>#{userdata['nickName']}</td>"
        html += "<td><b>性别</b></td><td>#{userdata['sex'] == 0 ? '男' : '女'}</td></tr>"
        html += "<tr><td><b>年龄</b></td><td>#{userdata['age']}岁</td>"
        html += "<td><b>身高</b></td><td>#{userdata['height']}cm</td></tr>"
      end
      
      # 基础测量
      html += '<tr><th colspan="4" style="background:#f5f5f5;">📊 基础测量</th></tr>'
      html += "<tr><td><b>体重</b></td><td>#{fmt(d['weight_kg'])} kg</td>"
      html += "<td><b>BMI</b></td><td>#{fmt(d['bmi'])}</td></tr>"
      html += "<tr><td><b>身体评分</b></td><td>#{fmt(d['bodyScore'])} 分</td>"
      html += "<td><b>身体年龄</b></td><td>#{fmt(d['physicalAge'])} 岁</td></tr>"
      
      # 体成分
      html += '<tr><th colspan="4" style="background:#f5f5f5;">🏃 体成分分析</th></tr>'
      html += "<tr><td><b>体脂率</b></td><td>#{fmt(d['bodyFatPercent'])}%</td>"
      html += "<td><b>肌肉率</b></td><td>#{fmt(d['musclePercent'])}%</td></tr>"
      html += "<tr><td><b>内脏脂肪</b></td><td>#{fmt(d['visceralFat'])}</td>"
      html += "<td><b>皮下脂肪</b></td><td>#{fmt(d['subcutaneousFatPercent'])}%</td></tr>"
      html += "<tr><td><b>水分率</b></td><td>#{fmt(d['moisturePercent'])}%</td>"
      html += "<td><b>蛋白质</b></td><td>#{fmt(d['proteinPercent'])}%</td></tr>"
      html += "<tr><td><b>骨量</b></td><td>#{fmt(d['boneMass'])} kg</td>"
      html += "<td><b>基础代谢</b></td><td>#{fmt(d['bmr'])} kcal</td></tr>"
      html += "<tr><td><b>骨骼肌率</b></td><td>#{fmt(d['smPercent'])}%</td>"
      html += "<td><b>体型</b></td><td>#{d['bodyType']}</td></tr>"
      
      # 目标建议
      html += '<tr><th colspan="4" style="background:#f5f5f5;">🎯 目标建议</th></tr>'
      html += "<tr><td><b>目标体重</b></td><td>#{fmt(d['targetWeight'])} kg</td>"
      html += "<td><b>体重控制</b></td><td>#{fmt(d['weightControl'])} kg</td></tr>"
      html += "<tr><td><b>标准体重</b></td><td>#{fmt(d['weightStandard'])} kg</td>"
      html += "<td><b>标准BMI</b></td><td>#{fmt(d['bmiStandard'])}</td></tr>"
      
      # 设备信息
      html += '<tr><th colspan="4" style="background:#f5f5f5;">📱 设备信息</th></tr>'
      html += "<tr><td><b>MAC地址</b></td><td>#{d['mac']}</td>"
      html += "<td><b>测量时间</b></td><td>#{d['timestamp']}</td></tr>"
      
      html += '</table>'
      html.html_safe
    rescue => e
      "解析错误: #{e.message}"
    end
  end

  rails_admin do
    navigation_label '测量记录'
    parent ScaleDevice
    weight 2

    list do
      filters [:wx_user]
      field :id do
        label 'ID'
      end
      field :wx_user_id do
        label '微信用户ID'
      end
      field :wx_user do
        label '微信用户'
        pretty_value do
          bindings[:object].wx_user_contact
        end
      end
      field :user_id do
        label '称用户ID'
      end
      field :scale_user do
        label '称用户名'
      end
      field :result do
        label '测量结果'
        pretty_value do
          bindings[:object].result_summary
        end
      end
      field :measurement_time do
        label '测量时间'
        pretty_value do
          time = bindings[:object].measurement_time
          time.present? ? time.strftime('%Y-%m-%d %H:%M:%S') : '-'
        end
        sortable false
      end
    end

    show do
      field :id do
        label 'ID'
      end
      field :wx_user_id do
        label '微信用户ID'
      end
      field :wx_user do
        label '微信用户'
        pretty_value do
          bindings[:object].wx_user_contact
        end
      end
      field :user_id do
        label '称用户ID'
      end
      field :scale_user do
        label '称用户名'
      end
      field :result do
        label '测量结果'
        pretty_value do
          bindings[:object].result_formatted
        end
      end
      field :measurement_time do
        label '测量时间'
        pretty_value do
          time = bindings[:object].measurement_time
          time.present? ? time.strftime('%Y-%m-%d %H:%M:%S') : '-'
        end
      end
    end

    edit do
      field :wx_user do
        label '微信用户'
      end
      field :scale_user do
        label '称用户名'
      end
      field :result do
        label '测量结果'
      end
    end
  end
end
