package com.persagy.server.datacenter.models.entities.tool

import com.alibaba.fastjson.annotation.JSONField
import com.alibaba.fastjson.serializer.SerializerFeature
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.google.gson.reflect.TypeToken
import com.persagy.server.datacenter.models.entities.assistant.AttPic
import com.persagy.server.datacenter.models.entities.assistant.TaskPic
import org.json.JSONObject
import org.slf4j.LoggerFactory
import java.io.Serializable

/**
 * Created by Xiaoyu on 2019/4/28
 */
open class ObjectBaseRequest : Serializable {
    companion object {
        // 日志
        private val logger = LoggerFactory.getLogger(ObjectBaseRequest::class.java)
    } // Companion object
    /** id */
    @JSONField(name = "id")
    @SerializedName("id")
    var id: String? = null
    /** 信息点 */
    @JSONField(name = "infos",serialzeFeatures = [SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty])
    @SerializedName("infos")
    var infos: HashMap<String, Any?>? = null

    //需要忽略的属性，数据平台中没有的信息点
    @JSONField(serialize=false)
    @Transient
    var ignoreKeySet = hashSetOf("LastUpdate", "CreateTime")

    //聚合在一起的字段名称，然后展开成数据平台需要的格式
    @JSONField(serialize=false)
    @Transient
    var collectKeySet = HashSet<String>()

    open fun addInfo(key: String, value: Any?) {
        addInfo(key, value, false)
    }
    /**
     * 添加信息点到infos
     * @param key   信息点
     * @param value 信息点值
     * @param ignoreNull    是否忽略value为null的情况，true value为null时不添加到infos
     */
    open fun addInfo(key: String, value: Any?, ignoreNull: Boolean) {
        if (collectKeySet.contains(key)) {
            addJSONObjectInfo(value , ignoreNull)
        } else {
            innerAddInfo(key, value, ignoreNull)
        }
    }

    /**
     * 添加信息点到infos
     * @param key   信息点
     * @param value 信息点值
     * @param ignoreNull    是否忽略value为null的情况，true value为null时不添加到infos
     */
     fun innerAddInfo(key: String, value: Any?, ignoreNull: Boolean) {
        if (ignoreKeySet.contains(key)) {
            return
        }
        if (value == null && ignoreNull) {
            return
        }
        infos = infos ?: LinkedHashMap()
        var valueArr = ArrayList<HashMap<String, Any?>>()

        val hashMap = HashMap<String, Any?>()
        if (value.toString()=="null" ){
//            valueArr[0]["value"] = null
            hashMap.put("value",null)
            valueArr.add(hashMap)
            infos!![key] = valueArr
//            logger.debug("value值0 = ${valueArr.toJson()}")
        }else{
            if (key == "Pic"||key == "InstallDrawing"||key == "InstallPic"||key == "CheckReport"||
                    key == "InsuranceFile"||key == "Nameplate" || key == "Drawing" || key == "Archive"||
                     key == "OperationManual" || key == "ProductCertification"||key == "TestReport"
                    ||key == "OriginalCertificate"||key == "AcceptanceReport"||key == "ApproachingAcceptance"
                    ||key == "SupplierContract"||key == "MaintainManual"||key == "InsuranceFile"){

//                logger.debug("Pic值001 = ${value}")
//                var list = ArrayList<AttPic>()
                if (value.toString() != "{}"){

                    try {
                        val gson = Gson()
                        val type = object : TypeToken<ArrayList<TaskPic>>() {
                        }.type
                        val attPicList = gson.fromJson<ArrayList<TaskPic>>(value.toString(),type)
//                        val attPicList = SJsonUtil.fromJson<ArrayList<TaskPic>>(value.toString())
                        if (attPicList.isNotEmpty()){
                            val listPic =ArrayList<AttPic>()
                            for (attPic in attPicList){
                                val taskPic = AttPic()
                                taskPic.key = attPic.key
                                taskPic.name = attPic.name
                                taskPic.systemId = attPic.systemId
                                taskPic.type = attPic.type
                                listPic.add(taskPic)
                            }
                            hashMap.put("value",listPic)
                            valueArr.add(hashMap)
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
//                    val attPicList = SJsonUtil.fromJson<ArrayList<AttPic>>(value.toString())


                }else{
                    hashMap.put("value",value)
                    valueArr.add(hashMap)
                }
                infos!![key] = valueArr
            }else{
                hashMap.put("value",value)
                valueArr.add(hashMap)
                infos!![key] = valueArr
            }
//            logger.debug("value值1 = ${valueArr.toJson()}")
        }
    }

    /**
     * 按信息点的一级标签，将一级标签里的信息点平铺添加
     */
    open fun addMapInfo(map: Map<String, Any?>, ignoreNull: Boolean) {
        if (map != null) {
            for (key in map.keys) {
                innerAddInfo(key, map[key], ignoreNull)
            }
        }
    }

    /**
     * 按信息点的一级标签，将一级标签里的信息点平铺添加
     */
    open fun addJSONObjectInfo(json: Any?, ignoreNull: Boolean) {
        if (json != null&&json.toString()!="null") {
            //json: JSONObject
            json as JSONObject
            val iterator = json.keys()
            while (iterator.hasNext()) {
                val key = iterator.next()
                val value = json.get(key as String)
//                innerAddInfo(key, value, ignoreNull)
                addInfo(key,value,true)
            }
        }
    }
    /**
     *
     */
    open fun removeInfo(key: String) {
        infos?.remove(key)
    }

}