/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .F88X
 *        X8888Y
 *      .}888888N;
 *        i888888N;        .:!              .I$WI:
 *          R888888I      .'N88~            i8}+8Y&8"l8i$8>8W~'>W8}8]KW+8IIN"8&
 *          .R888888I    .;N8888~          .X8'  "8I.!,/8"  !%NY8`"8I8~~8>,88I
 *            +888888N;  .8888888Y                                  "&&8Y.}8,
 *            ./888888N;  .R888888Y        .'}~    .>}'.`+>  i}!    "i'  +/'  .'i~  !11,.:">,  .~]!  .i}i
 *              ~888888%:  .I888888l      .]88~`1/iY88Ii+1'.R$8$8]"888888888>  Y8$  W8E  X8E  W8888'188Il}Y88$*
 *              18888888    E8888881    .]W%8$`R8X'&8%++N8i,8N%N8+l8%`  .}8N:.R$RE%N88N%N$K$R  188,FE$8%~Y88I
 *            .E888888I  .i8888888'      .:$8I;88+`E8R:/8N,.>881.`$8E/1/]N8X.Y8N`"KF&&FK!'88*."88K./$88%RN888+~
 *            8888888I  .,N888888~        ~88i"8W,!N8*.I88.}888%F,i$88"F88"  888:E8X.>88!i88>`888*.}Fl1]*}1YKi'
 *          i888888N'      I888Y          ]88;/EX*IFKFK88X  K8R  .l8W  88Y  ~88}'88E&%8W.X8N``]88!.$8K  .:W8I
 *        .i888888N;        I8Y          .&8$  .X88!  i881.:%888>I88  ;88]  +88+.';;;;:.Y88X  18N.,88l  .+88/
 *      .:R888888I
 *      .&888888I                                          Copyright (c) 2009-2020.  博锐尚格科技股份有限公司
 *        ~8888'
 *        .!88~                                                                     All rights reserved.
 *
 * *********************************************************************************************************************
 */

package com.persagy.server.services.task

import cn.hutool.core.collection.CollUtil
import cn.sagacloud.server.scanbuilding.User
import com.alibaba.fastjson.JSONObject
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.database.SPageQueryInfo
import com.persagy.database.functions.SLength
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.Opts
import com.persagy.server.datacenter.models.entities.assistant.TaskPic
import com.persagy.server.datacenter.models.entities.dict.EquipFamilyCategory
import com.persagy.server.datacenter.models.entities.dictnew.DefClass
import com.persagy.server.datacenter.models.entities.objects.Equipment
import com.persagy.server.datacenter.models.entities.objects.Property
import com.persagy.server.datacenter.models.entities.task.EquipScanTaskQuery
import com.persagy.server.datacenter.models.entities.task.PropertyScanTask
import com.persagy.server.datacenter.models.entities.task.SchemeUtils
import com.persagy.server.scanbuilding.UserLog
import com.persagy.server.services.AdmBaseService
import com.persagy.server.services.DmpBaseService
import com.persagy.server.services.base.RService
import com.persagy.server.util.AdmEntityTransferUtil
import com.persagy.server.util.IdUtils
import com.persagy.service.SBaseService
import com.persagy.service.SObjectService
import com.persagy.service.SPageContext
import com.persagy.service.models.SCascadeQuery
import com.persagy.service.models.requests.SCreateRequest
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.responses.SQueryResponse
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.RequestBody
import java.util.*
import java.util.stream.Collectors
import kotlin.collections.ArrayList

/**
 * 资产台账任务
 *
 * @author  邓婷婷
 */
object PropertyScanTaskService : RService<PropertyScanTask>(SMybatisDao(PropertyScanTask::class.java)) {

    // 日志
    private val logger = LoggerFactory.getLogger(PropertyScanTaskService::class.java)

    /** 扫楼日志 */
    var userLogService = SObjectService(SMybatisDao(UserLog::class.java))
    /** 用户 */
    var userService = SObjectService(SMybatisDao(User::class.java))

    /** 用户 */
    //var equipFamilyCategoryService = SObjectService(SMybatisDao(EquipFamilyCategory::class.java))

    @Autowired
    private val admBaseService: AdmBaseService? = AdmBaseService()

    @Autowired
    private val dmpBaseService: DmpBaseService? = DmpBaseService()


    fun pageQuerys(request: SQueryRequest): SQueryResponse<PropertyScanTask> {
        //查询设备台账任务
        val projectId = SPageContext.getHeader("projectId").toString()
        val withFilterList = ArrayList<SFilter>()
        withFilterList.add(SFilter.eq("projectId", SPageContext.getHeader("projectId").toString()))
        //withFilterList.add(SFilter.lt(SLength("classCode"), 7))
        val pageQuery = PropertyScanTaskService.pageQuery(request, withFilterList)
        if (!pageQuery.content.isNullOrEmpty()&&pageQuery.content!!.size>0){

            //级联查询设备相关信息:建筑，楼层，空间等
            val equipScanTaskList = pageQuery.content
            var cascadeQueryAdmEquip = arrayListOf<Property>()
            if (equipScanTaskList != null) {

                val cascades = ArrayList<SCascadeQuery>()
                //级联查询建筑
                val buildCacade = SCascadeQuery()
                buildCacade.name = "building"
                cascades.add(buildCacade)
                //级联查询楼层
                val floorCacade = SCascadeQuery()
                floorCacade.name="floor"
                cascades.add(floorCacade)

                val cascade = request.cascade
                if (cascade != null) {
                    cascade.addAll(cascades)
                    request.cascade= cascade
                }else{
                    request.cascade= cascades
                }
                cascadeQueryAdmEquip = cascadeQueryAdmProperty(equipScanTaskList, request) as ArrayList<Property>
            }
            val equipMap = cascadeQueryAdmEquip?.stream()?.collect(Collectors.groupingBy { item: Property -> item.id })
            for (content in pageQuery.content!!){
                //设置级联查询结果
                val caseNodes = equipMap.get(content.equipId)
                if(CollUtil.isNotEmpty(caseNodes)){
                    val equip = caseNodes?.get(0)
                    if (equip != null) {
                        content.building = equip.building
                        content.floor = equip.floor
                        /*val component = equip.component
                        val toAdmMultiEntity = AdmEntityTransferUtil.toAdmMultiEntity(component, null, EquipScanTaskQuery::class.java)
                        content.component = toAdmMultiEntity*/
                    }
                }

                //查询组件
               /* val exec = EquipScanTaskQueryService.select(SFilter.eq("parentId", content.equipId!!), SFilter.eq("taskParentId", content.id!!)).exec()
                if (exec.size>0){
                    content.component = exec
                }*/
                //查询中台类型数据，2021.10.25日中心中台整合调整
                val param = JSONObject()
                val criteria = JSONObject()
                criteria["code"] = content.classCode!!
                param["criteria"] = criteria
                val dictTypes = dmpBaseService?.queryDictType(param)
                val entity = AdmEntityTransferUtil.toAdmMultiEntity(dictTypes, null, EquipFamilyCategory::class.java)?.get(0)
                if (entity!=null) {
                    content.equipFamily = entity
                }
            }
        }
        return pageQuery
    } // Fun

    /**
     * 级联查询资产相关信息:建筑，楼层，空间等
     */
    fun cascadeQueryAdmProperty(equipScanTaskList: List<PropertyScanTask>?, request: SQueryRequest): List<Property>? {
        //级联查询设备相关信息:建筑，楼层，空间等
        if(CollUtil.isEmpty(equipScanTaskList)){
            return ArrayList<Property>()
        }
        val equipIds = equipScanTaskList?.stream()?.map(PropertyScanTask::equipId)?.collect(Collectors.toList<String>())
        var equipRequest = SQueryRequest()
        equipRequest.filters = "id in "+"(\'" + java.lang.String.join("\',\'", equipIds) + "\'）"

        val requestCascade = request.cascade
        //查询级联关系
        val cascadeList = arrayListOf<SCascadeQuery>()
        if (requestCascade != null) {
            for(cascade in requestCascade){
                if("scanScheme".equals(cascade.name)){
                    continue
                }
                cascadeList.add(cascade)
            }
            equipRequest.cascade = cascadeList;
            return admBaseService?.queryProperty(equipRequest)
        }
        return ArrayList<Property>()
    }

    /**
     * 插入之前先过滤已经存在未验证任务的对象，返回新列表
     */
    fun createBefore(@RequestBody request: SCreateRequest<PropertyScanTask>): SCreateRequest<PropertyScanTask> {
        val propertyTaskList = request.content;
        var newList = arrayListOf<PropertyScanTask>()
        for(property in propertyTaskList){
            val propertyTask = PropertyScanTaskService.select(SFilter.eq("equipId", property.equipId!!),SFilter.eq("taskState", 1)).entity()
            if(propertyTask==null){//表示当前设备已经存在未验证的任务
                newList.add(property)
            }
        }

        request.content = newList
        println(newList.size)
        return request
    }

    /**
     * 创建之前操作
     */
    override fun onCreateBefore(propertyScanTask: PropertyScanTask): Boolean {
        try {
            val gson = Gson()
            var flag = false
            if(propertyScanTask.taskState == -1){//表示当前任务是未找到状态，重新生成任务
                flag = true

                val propertyScanTaskService = SBaseService(SMybatisDao(PropertyScanTask::class.java))
               val resetTask = propertyScanTaskService.select(SFilter.eq("equipId", propertyScanTask.equipId!!),SFilter.eq("taskState", -1)
               ).entity()

                if( resetTask!=null ){
                    resetTask.taskState = 0
                    propertyScanTaskService.update(resetTask)
                }
            }
            val projectId = SPageContext.getHeader("projectId")
//            if (propertyScanTask.id.isNullOrEmpty()) {
                propertyScanTask.id = UUID.randomUUID().toString()
//            }
            if(!projectId.isNullOrEmpty()){
                propertyScanTask.projectId = projectId
            }
            propertyScanTask.taskSource = 3//数据源为资产
            propertyScanTask.taskState = 1//任务状态为待验证
            propertyScanTask.taskType = "1"
            if (!propertyScanTask.equipId.isNullOrEmpty()) {//当设备id不为空时，去设备表查询对应的详细信息
               // val propertyService = SBaseService(SMybatisDao(Property::class.java))
               // val property = propertyService.select(SFilter.eq("id", propertyScanTask.equipId!!)
                //).entity()
                val property = admBaseService?.queryPropertyById(propertyScanTask.equipId!!)?.get(0)
                if (propertyScanTask.schemeId.isNullOrEmpty()){
                    propertyScanTask.schemeId = SchemeUtils.setScheme(property!!.family!!)
                }
//                property.ledgerParam.PhotoDoc.Pic
                if(property!!.infos != null){//设备图片信息
                    val photoDoc = property!!.infos!!.get("PhotoDoc")
                    if( photoDoc != null){
                        val obj = JSONObject.parseObject(photoDoc!!.toJson())
                        val pic = obj.getString("Pic")

                        val type = object : TypeToken<ArrayList<TaskPic>>() {
                        }.type
                        val siInSpList = gson.fromJson<ArrayList<TaskPic>>(pic, type)
                        propertyScanTask.taskPicList = siInSpList
                    }

                    val containsKey = property.infos!!.containsKey(Opts.INSTALLLOCATION)
                    if (containsKey){
                        propertyScanTask.installLocation = property.infos!![Opts.INSTALLLOCATION].toString()
                    }
                }

                try {
                    if (!property.infos.isNullOrEmpty()){

                        val containsKey = property.infos!!.containsKey(Opts.MANUFACTURER)
                        if (containsKey){
                            propertyScanTask.manufacturer = property.infos!![Opts.MANUFACTURER].toString()
                        }
                        val containsKey2 = property.infos!!.containsKey(Opts.SPECIFICATION)
                        if(containsKey2) {
                            propertyScanTask.specification = property.infos!![Opts.SPECIFICATION].toString()
                        }

                        val containsKeys = property.infos!!.containsKey(Opts.SUPPLIER)
                        if (containsKeys){
                            propertyScanTask.supplier =  property.infos!![Opts.SUPPLIER].toString()
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }


                if(flag){
                    propertyScanTask.equipName = property!!.name
                    propertyScanTask.localId = property!!.localId
                    propertyScanTask.localName = property!!.localName
                    propertyScanTask.bimId = property!!.bimId
                    propertyScanTask.classCode = property!!.family
                    propertyScanTask.buildingId = property!!.buildingId
                    propertyScanTask.floorId = property!!.floorId
                    propertyScanTask.cadId = property!!.cadId
//                    propertyScanTask.supplier = property!!.dpSupplierID
//                    propertyScanTask.specification = property!!.dpManufacturerID
//                    propertyScanTask.manufacturer = property!!.dpMaintainerID
                    propertyScanTask.bimLocation = property.bimLocation
                    if (property.codeType!=null){
                        propertyScanTask.taskType = property.codeType.toString()
                    }else{
                        propertyScanTask.taskType = "1"
                    }
                }else{
                    if (propertyScanTask.equipName.isNullOrEmpty()) {
                        propertyScanTask.equipName = property!!.name
                    }
                    if (propertyScanTask.localId.isNullOrEmpty()) {
                        propertyScanTask.localId = property!!.localId
                    }
                    if (propertyScanTask.localName.isNullOrEmpty()) {
                        propertyScanTask.localName = property!!.localName
                    }
                    if (propertyScanTask.bimId.isNullOrEmpty()) {
                        propertyScanTask.bimId = property!!.bimId
                    }
                    if (propertyScanTask.classCode.isNullOrEmpty()) {
                        propertyScanTask.classCode = property!!.family
                    }
                    if (propertyScanTask.buildingId.isNullOrEmpty()) {
                        propertyScanTask.buildingId = property!!.buildingId
                    }
                    if (propertyScanTask.floorId.isNullOrEmpty()) {
                        propertyScanTask.floorId = property!!.floorId
                    }
                    if (propertyScanTask.cadId.isNullOrEmpty()) {
                        propertyScanTask.cadId = property!!.cadId
                    }
//                    if (propertyScanTask.supplier.isNullOrEmpty()) {
//                        propertyScanTask.supplier = property!!.dpSupplierID
//                    }
//                    if (propertyScanTask.specification.isNullOrEmpty()) {
//                        propertyScanTask.specification = property!!.dpManufacturerID
//                    }
//                    if (propertyScanTask.manufacturer.isNullOrEmpty()) {
//                        propertyScanTask.manufacturer = property!!.dpMaintainerID
//                    }
                    if (propertyScanTask.bimLocation.isNullOrEmpty()){
                        propertyScanTask.bimLocation = property.bimLocation
                    }

                    if (propertyScanTask.taskType.isNullOrEmpty()){
                        if (property.codeType!=null){
                            propertyScanTask.taskType = property.codeType.toString()
                        }else{
                            propertyScanTask.taskType = "1"
                        }
                    }

                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return true
    } // Function onCreateBefore()


    override fun onDeleteBefore(entity: PropertyScanTask): Boolean {
        /*  val entity1 = select(SFilter.eq("id", entity.id!!)).entity()
         val propertyService = SBaseService(SMybatisDao(Property::class.java))
         val property = propertyService.select(SFilter.eq("id", entity1!!.equipId!!)).entity()

          val list = ArrayList<String>()
          list.add("TaskState")
          property!!.taskState = null
          propertyService.update(property,list)*/

        val property = admBaseService?.queryPropertyById(entity!!.equipId!!)?.get(0)
        val infos = HashMap<String, Any?>()
        infos.put("taskState",null)
        if (property != null) {
            property.infos = infos
        }

        val list = ArrayList<Property>()
        if (property != null) {
            list.add(property)
        }
        admBaseService?.updateProperty(list)

        return super.onDeleteBefore(entity)
    }


    /**
     * 创建成功之后
     */
    override fun onCreateSuccess(propertyScanTaskList: ArrayList<PropertyScanTask>) {
        for(task in propertyScanTaskList){
            /*val property = Property()
            val propertyService = SBaseService(SMybatisDao(Property::class.java))
            property.id = task.equipId!!
            property.taskState = 1
            propertyService.update(property)*/

            val property = Property()
            property.id = task.equipId!!
            val infos = HashMap<String, Any?>()
            infos.put("taskState",1)
            if (property != null) {
                property.infos = infos
            }
            admBaseService?.updateProperty(arrayListOf(property))

        }
    } // Fun onCreateSuccess

    /**
     * 状态修改完成之后
     */
    override fun onUpdateSuccess(list: ArrayList<PropertyScanTask>) {
        val projectId = SPageContext.getHeader("projectId")
        for (task in list) {
           // val propertyService = SBaseService(SMybatisDao(Property::class.java))
            if(task.equipId == null ){
                val propertyScanTask = PropertyScanTaskService.select(SFilter.eq("id", task.id!!)).entity()
                task.equipId = propertyScanTask!!.equipId
            }
            //更改设备对象的状态
            //val propertyOld = propertyService.select(SFilter.eq("id", task.equipId!!)).entity()
            val propertyOld = admBaseService?.queryPropertyById(task!!.equipId!!)?.get(0)
            if(propertyOld!!.taskState != -1) {//未找到
              /*  val property = Property()
                property.id = task.equipId!!
                property.taskState = task.taskState
                propertyService.update(property)*/

                val property = Property()
                property.id = task.equipId!!
                val infos = HashMap<String, Any?>()
                infos.put("taskState",task.taskState!!)
                if (property != null) {
                    property.infos = infos
                }
                admBaseService?.updateProperty(arrayListOf(property))
            }
            try {
                if (!Opts.coming.isNullOrEmpty()&&Opts.coming == "app"){
                        val entity = userService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("phone", Opts.account!!)).entity()
                        val userLog = UserLog()
                        userLog.comming = "app"
                        userLog.action = "修改资产任务"
                        userLog.id = IdUtils.uuidCreate()
                        userLog.note = "确认资产任务"
                        userLog.phone = entity?.phone
                        userLog.projectId = projectId
                        userLog.userId = entity!!.id
                        userLog.name = entity.name
                        userLog.objectId = task.id
                        userLogService.insert(userLog)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    } // Fun onUpdateSuccess

    override fun onQuerySuccess(pageInfo: SPageQueryInfo<PropertyScanTask>) {
       /* if (!pageInfo.content.isNullOrEmpty()){
            for (content in pageInfo.content!!){
              //  val entity = equipFamilyCategoryService.select(SFilter.eq("family", content.classCode!!)).entity()
                //查询中台类型数据，2021.10.25日中心中台整合调整
                val param = JSONObject()
                val criteria = JSONObject()
                criteria["code"] = content.classCode!!
                param["criteria"] = criteria
                val dictTypes = dmpBaseService?.queryDictType(param)
                val entity = AdmEntityTransferUtil.toAdmMultiEntity(dictTypes, null, EquipFamilyCategory::class.java)?.get(0)
                if (entity!=null) {
                    content.equipFamily = entity
                }else {

                }
            }
        }*/
        super.onQuerySuccess(pageInfo)
    }



} // Class PropertyScanTaskService