package test

import com.alibaba.fastjson.{JSON, JSONArray, JSONObject}
import scala.collection.mutable.Map;
/**
  * @Author: xiaobin.yan
  * @Date: 26/07/2017
  * @Description:
  */
object ScalaTest {

  def main(args: Array[String]): Unit = {
    val json1 = "[{\"package_name\":\"com.lenovo.anyshare.gps\",\"tag\":[{\"1\":\"Tools\",\"id\":\"29\"}]}]"
    val json2 = "[{\"package_name\":\"com.lenovo.anyshare.gps\",\"tag\":[{\"1\":\"sports\",\"id\":\"30\"}]}]"
    val json = mergeJsonArray(JSON.parseArray(json1),JSON.parseArray(json2))
    println(json)
  }
    /**
      * 合并兴趣标签
      */
    def mergeJsonArray(jsonArray1: JSONArray, jsonArray2: JSONArray): _root_.scala.Predef.String = {
      val appMap: Map[String, JSONArray] = Map()
      iteratorJsonArray(jsonArray1,appMap)
      iteratorJsonArray(jsonArray2,appMap)
      val jsonArray = new JSONArray
      appMap.foreach(e=>{
        val json = new JSONObject
        json.put("package_name",e._1)
        json.put("tag",e._2)
        jsonArray.add(json)
      })
      jsonArray.toJSONString
    }

    /**
      * 设备id校验正则表达式
      */
    val DEVICE_REGEX = "[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}"

    /**
      * 迭代应用标签数组
      */
    def iteratorJsonArray(jsonArray: JSONArray, appMap: Map[String, JSONArray]): Unit = {
      for (i <- 0 until jsonArray.size()){
        val json = jsonArray.getJSONObject(i)
        val packageName = json.getString("package_name")
        val tagArray = json.getJSONArray("tag")
        appMap.get(packageName) match {
          case Some(tags) => {
            val tagMap: Map[String, JSONObject] = Map()
            iteratorTag(tagArray,tagMap)
            iteratorTag(tags,tagMap)
            val newJSONArray = new JSONArray
            tagMap.values.foreach(jsonObject=> newJSONArray.add(jsonObject))
            appMap +=(packageName -> newJSONArray)
          }
          case None => appMap +=(packageName -> tagArray)
        }
      }
    }

    /**
      * 迭代标签数组
      */
    def iteratorTag(tags: JSONArray, tagMap: Map[String, JSONObject]) = {
      for (i <- 0 until tags.size){
        val tagJson = tags.getJSONObject(i)
        val tagId = tagJson.getString("id")
        if (!tagMap.contains(tagId)){
          tagMap +=(tagId->tagJson)
        }
      }
    }


}
