15.2 在 Controller 中年添加对外访问接口
15.2.1 添加封装数据的 bean 类
package com.atguigu.dw.gmallpublisher.bean
import org.json4s.JValue
case class Stat(title: String, options: List[Opt])
case class Opt(name: String, value: String)
case class SaleInfo(total: Int, stats: List[Stat], detail: List[Map[String, Any]])
15.2.2 在 Controller 中添加方法
@GetMapping(Array("sale_detail"))
def saleDetail(@RequestParam("date") date: String,
@RequestParam("startpage") startPage: Int,
@RequestParam("size") pageSize: Int,
@RequestParam("keyword") keyword: String) = {
val formater = new DecimalFormat(".00")
val saleDetailMapByGender: Map[String, Any] = publisherService.getSaleDetailAndAggResultByAggField(date, keyword, startPage, pageSize, "user_gender", 2)
val total: Integer = saleDetailMapByGender("total").asInstanceOf[Integer]
val genderMap: Map[String, Long] = saleDetailMapByGender("aggMap").asInstanceOf[Map[String, Long]]
val maleCount: Long = genderMap("M")
val femalCount: Long = genderMap("F")
val genderOpts = List[Opt](
Opt("total", total.toString),
Opt("男", formater.format(maleCount.toDouble / total)),
Opt("女", formater.format(femalCount.toDouble / total))
)
val genderStat = Stat("用户性别占比", genderOpts)
val saleDetailMapByAge: Map[String, Any] = publisherService.getSaleDetailAndAggResultByAggField(date, keyword, startPage, pageSize, "user_age", 100)
val ageMap: Map[String, Long] = saleDetailMapByAge("aggMap").asInstanceOf[Map[String, Long]]
val ageOpts = ageMap.groupBy {
case (age, _) =>
val intAge = age.toInt
if (intAge < 20) "20岁以下"
else if (intAge >= 20 && intAge <= 30) "20岁到30岁"
else "30岁以上"
}.map {
case (age2age, map) =>
(age2age, (0L /: map) (_ + _._2))
}.map {
case (age2age, count) =>
(age2age, formater.format(count.toDouble / total))
}.toList.map {
case (age2age, rate) =>
Opt(age2age, rate)
}
val ageStat = Stat("用户年龄占比", ageOpts)
val detailList: List[Map[String, Any]] = saleDetailMapByAge("detail").asInstanceOf[List[Map[String, Any]]]
val saleInfo = SaleInfo(total, List(genderStat, ageStat), detailList)
import org.json4s.jackson.Serialization.write
implicit val formats = DefaultFormats
write(saleInfo)
}