/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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 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.mybatis.SMybatisDao
import com.persagy.server.Opts
import com.persagy.server.datacenter.models.entities.assistant.TaskPic
import com.persagy.server.datacenter.models.entities.objects.Building
import com.persagy.server.datacenter.models.entities.objects.Equipment
import com.persagy.server.datacenter.models.entities.task.*
import com.persagy.server.datacenter.models.entities.task.base.ScanTaskBase
import com.persagy.server.mappers.StatisticsCountMapper
import com.persagy.server.services.AdmBaseService
import com.persagy.server.services.DmpBaseService
import com.persagy.server.services.StatisticsCountService
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.SPageContext
import com.persagy.service.models.SCascadeQuery
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.responses.SQueryResponse
import com.persagy.service.utils.SSpringContextUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired

/**
 * 任务父表
 *
 * @author  邓婷婷
 */
object ScanTaskBaseService : RService<ScanTaskBase>(SMybatisDao(ScanTaskBase::class.java))  {

    // 日志
    private val logger = LoggerFactory.getLogger(EquipScanTaskService::class.java)
    /** 实例化 mapper 对象 */
    val mapper by lazy {
        SSpringContextUtil.getBean(StatisticsCountMapper::class.java) as StatisticsCountMapper
    }

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

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

    @Autowired
    private val statisticsCountService: StatisticsCountService? = StatisticsCountService()

    /**
     * 查询所有设备类型或设备族
     */
    fun equipCategoryQuery(type: String): SQueryResponse<EquipCategoryDic> {
        val sQueryResponse = SQueryResponse<EquipCategoryDic>(SResponseType.success)
        var request = SQueryRequest()
        request.filters = "ProjectId = '${SPageContext.getHeader("ProjectId")}'";
        request.projection = arrayListOf("classCode")
        request.distinct = true
        val tasks = ArrayList<ScanTaskBase>()
        //查询设备，资产，模型文件现有的数据
        if(type == "equip") {
            // 如果是equip
            val response = EquipScanTaskService.pageQuery(request, null)
            tasks.addAll(response.content!!)
        } else if(type == "property") {
            // 如果是property
            val response = PropertyScanTaskService.pageQuery(request, null)
            tasks.addAll(response.content!!)
        } else if(type == "model") {
            // 如果是model
            val response = ModelScanTaskService.pageQuery(request, null)
            tasks.addAll(response.content!!)
        }
        //查询中台类型数据
        val param = JSONObject()
        val criteria = JSONObject()
         if ("equip" == type) {
             val objTypes = JSONObject()
             val objTypeList: MutableList<String> = java.util.ArrayList()
             objTypeList.add("equipment")
             objTypeList.add("component")
             objTypes["\$in"] = objTypeList
         }else if ("model" == type){
             val objTypes = JSONObject()
             val objTypeList: MutableList<String> = java.util.ArrayList()
             objTypeList.add("equipment")
             objTypeList.add("component")
             objTypeList.add("model")
             objTypes["\$in"] = objTypeList
         }else{
             criteria["objType"] = type
         }
        param["criteria"] = criteria
        val queryDictType = dmpBaseService!!.queryDictType(param)
        if(queryDictType == null || queryDictType.size<=0){
            return sQueryResponse
        }
        val queryDictMap = HashMap<String, String>()
        for (dict in queryDictType){
            dict.code?.let { dict.name?.let { it1 -> queryDictMap.put(it, it1) } }
        }

        //结果集封装
        val equipCategoryList = ArrayList<EquipCategoryDic>()
        for(task in tasks!!){
            val equipCategoryDic = EquipCategoryDic()
            equipCategoryDic.code = task.classCode
            if(queryDictMap.get(task.classCode) == null){
                continue
            }
            equipCategoryDic.name = queryDictMap.get(task.classCode)
            equipCategoryList.add(equipCategoryDic)
        }

        //历史逻辑：
        /*val pageQuery: SPageQueryInfo<EquipCategoryDic>
       return try {
            val equipCategoryDicService = SBaseService(SMybatisDao(EquipCategoryDic::class.java))
            var request = SQueryRequest()
            val queryBuilder = equipCategoryDicService.select(request.filters)

            val projectId = SPageContext.getHeader("projectId").toString()
            queryBuilder.tableName = "scantask.f_get_category('$type','$projectId')"
            pageQuery = queryBuilder.pageQuery(1, 1000)
            SQueryResponse(pageQuery)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }*/

        sQueryResponse.content = equipCategoryList
        return sQueryResponse


    }

    /**
     * 查询所有建筑和楼层
     */
    fun buildingQuery(type: String): SQueryResponse<BuildingDic> {
        val pageQuery = SPageQueryInfo<BuildingDic>(1, 1000)
        return try {
            val projectId = SPageContext.getHeader("projectId").toString()
            var request = SQueryRequest()
            request.filters = "not buildingId isnull ; not floorId isnull";
            request.projection = arrayListOf("buildingId", "floorId")
            request.distinct = true
            val tasks = ArrayList<ScanTaskBase>()
            if(type == "equip") {
                // 如果是equip
                val response = EquipScanTaskService.pageQuery(request, null)
                tasks.addAll(response.content!!)
            } else if(type == "property") {
                // 如果是property
                val response = PropertyScanTaskService.pageQuery(request, null)
                tasks.addAll(response.content!!)
            } else if(type == "model") {
                // 如果是model
                val response = ModelScanTaskService.pageQuery(request, null)
                tasks.addAll(response.content!!)
            }
            val resultList = ArrayList<BuildingDic>()
            pageQuery.content = resultList
            if(tasks!!.isNotEmpty()) {
                // 转换为<buildId, List<floorId>>
                val builds = tasks.map { it.buildingId }
                val floors = tasks.map { it.floorId }
                var buildingRequest = SQueryRequest()

               // buildingRequest.filters = "id in (" +builds!!.joinToString(",", ",", "'").substring(1) + ")"
                buildingRequest.filters = "id in "+"(\'" + java.lang.String.join("\',\'", builds) + "\')"
                buildingRequest.pageSize = 1000
                buildingRequest.pageNumber = 1
                var cascade = SCascadeQuery()
                cascade.name = "floor"
                //cascade.filters = "id in (" +floors!!.joinToString(",", ",", "'").substring(1) + ")"
                cascade.filters = "id in "+"(\'" + java.lang.String.join("\',\'", floors) + "\')"
                buildingRequest.cascade = arrayListOf(cascade)
                //调用adm-middleware建筑查询接口
                val buildingList = admBaseService?.queryBuilding(buildingRequest) as ArrayList<Building>?
                //转换为BuildingDic
                val buildingDicList = AdmEntityTransferUtil.toAdmMultiEntity(buildingList, null, BuildingDic::class.java)
                pageQuery.content = buildingDicList as ArrayList<BuildingDic>?
            }
//            val queryBuilder = service.select(request.filters)
//            queryBuilder.tableName = "scantask.f_get_building_dic('$type','$projectId')"
//            pageQuery = queryBuilder.pageQuery(1, 1000)

            if (pageQuery.content!!.size>0){
//                for(floor in resultList!!){
//                    if(floor.floorListStr != null){
//                        val listStr = floor.floorListStr!!.replace("/\\","")
//                        val newStr = "["+listStr.substring(1,listStr.length-1)+"]"
//                        val type = object : TypeToken<ArrayList<FloorDic>>() {
//                        }.type
//                        val siInSpList = gson.fromJson<ArrayList<FloorDic>>(newStr, type)
//                        floor.floor = siInSpList
//                        floor.floorListStr = null
//                    }
//                }
                if (type == "equip"||type == "property"){
                        var taskSource: String
                    if (type == "equip"){
                        taskSource = "2"
                    }else {
                        taskSource = "3"
                    }
                    /** 处理楼层是否有未明确楼层 */
                    for(building in pageQuery.content!!){
                        if (building.floor!=null&&building.floor!!.size>0){

                                val equipScanTaskList = select(
                                    SFilter.eq("projectId", projectId), SFilter.eq("buildingId", building.id!!),
                                        SFilter.isNull("floorId"),SFilter.eq("taskSource", taskSource)).exec()
                                if (equipScanTaskList.size>0){
                                    val floorDic = FloorDic()
                                    floorDic.localName = "未明确楼层"
                                    building.floor!!.add(0,floorDic)
                                }

                        }else{
                            val equipScanTaskList = select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", building.id!!),
                                    SFilter.isNull("floorId"),SFilter.eq("taskSource", taskSource)).exec()
                            if (equipScanTaskList.size>0){
                                val list = ArrayList<FloorDic>()
                                val floorDic = FloorDic()
                                floorDic.localName = "未明确楼层"
                                list.add(floorDic)
                                building.floor= list
                            }
                        }
                    }
                    /** 未明确建筑 */
                    val equipScanTaskList = select(SFilter.eq("projectId", projectId), SFilter.isNull("buildingId"),SFilter.eq("taskSource", taskSource)).exec()
                    if (equipScanTaskList.size>0){
                        val buildingDic = BuildingDic()
                        buildingDic.localName = "未明确建筑"
                        pageQuery.content!!.add(0,buildingDic)
                    }
                }
            }else{
                if (type == "equip"||type == "property") {
                    var taskSource: String
                    if (type == "equip") {
                        taskSource = "2"
                    } else {
                        taskSource = "3"
                    }
                    val equipScanTaskList = select(SFilter.eq("projectId", projectId), SFilter.isNull("buildingId")
                            ,SFilter.eq("taskSource", taskSource)).exec()
                    if (equipScanTaskList.size > 0) {
                        val list = ArrayList<BuildingDic>()
                        val buildingDic = BuildingDic()
                        buildingDic.localName = "未明确建筑"
                        list.add(buildingDic)
                        pageQuery.content = list
                    }
                }
            }
            SQueryResponse(pageQuery)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } //  Fun modelFileQuery

    /**
     * 统计设备下部件的类型以及数量
     */
    fun categoryCounts(equipScanTask: EquipScanTask): SQueryResponse<CategoryStatistics>{
        try {
            val projectId = SPageContext.getHeader("projectId").toString()
            if (!equipScanTask.id.isNullOrEmpty()&&!equipScanTask.equipId.isNullOrEmpty()){
                val categoryStatistics = statisticsCountService?.categoryStatistics(projectId,equipScanTask.id!!, equipScanTask.equipId!!)
                val sQueryResponse = SQueryResponse<CategoryStatistics>()
                sQueryResponse.total = categoryStatistics?.size?.toLong()
                sQueryResponse.content = categoryStatistics
                sQueryResponse.result = SResponseType.success
                return sQueryResponse
            }else{
                val sQueryResponse = SQueryResponse<CategoryStatistics>(SResponseType.failure)
                sQueryResponse.message = "入参错误"
                return sQueryResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return SQueryResponse(SResponseType.failure,e.message.toString())
        }
    } // Fun


    /**
     * 统计设备下部件的类型以及数量
     */
    fun categoryCountsModel(type: String?,equipScanTask: ModelScanTask): SQueryResponse<CategoryStatistics>{
        try {
            val projectId = SPageContext.getHeader("projectId")
            if (!equipScanTask.id.isNullOrEmpty()&&!equipScanTask.equipId.isNullOrEmpty()){
                if (!type.isNullOrEmpty()&&type == "model"){
                    val categoryStatistics = statisticsCountService?.categoryStatisticsModel(projectId!!,equipScanTask.id!!, equipScanTask.equipId!!)
                    val sQueryResponse = SQueryResponse<CategoryStatistics>()
                    sQueryResponse.total = categoryStatistics?.size?.toLong()
                    sQueryResponse.content = categoryStatistics
                    sQueryResponse.result = SResponseType.success
                    return sQueryResponse
                }else{
                    val categoryStatistics = statisticsCountService?.categoryStatistics(projectId!!,equipScanTask.id!!, equipScanTask.equipId!!)
                    val sQueryResponse = SQueryResponse<CategoryStatistics>()
                    sQueryResponse.total = categoryStatistics?.size?.toLong()
                    sQueryResponse.content = categoryStatistics
                    sQueryResponse.result = SResponseType.success
                    return sQueryResponse
                }
            }else{
                val sQueryResponse = SQueryResponse<CategoryStatistics>(SResponseType.failure)
                sQueryResponse.message = "入参错误"
                return sQueryResponse
            }
        } catch (e: Exception) {
            e.printStackTrace()
            return SQueryResponse(SResponseType.failure,e.message.toString())
        }
    } // Fun


    /**
     * 创建之前操作
     */
    override fun onCreateBefore(equipScanTask: ScanTaskBase): Boolean  {
        try{
            val gson = Gson()
            var flag = false
            if(equipScanTask.taskState == -1){//前台传数据过来状态为-1 表示当前任务是未找到状态 重新生成任务，将之前的设备任务状态和部件任务改为已完成
                flag = true
                ScanTaskBaseService.resetTaskStatus(equipScanTask)
            }

            val projectId = SPageContext.getHeader("projectId")
            if (equipScanTask.id.isNullOrEmpty()) {
                equipScanTask.id = IdUtils.uuidCreate()
            }
            if(!projectId.isNullOrEmpty()){
                equipScanTask.projectId = projectId
            }
            equipScanTask.taskSource = 2//数据源为设备台账
            equipScanTask.taskState = 1//任务状态为待验证
            //equipScanTask.taskType = "1"

            if (!equipScanTask.equipId.isNullOrEmpty()) {//当设备id不为空时，去设备表查询对应的详细信息
                /* val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
                 val equipment = equipmentService.select(SFilter.eq("id", equipScanTask.equipId!!)).entity()*/
                //2021.10.26调整为从中间件查询设备信息
                val equipmentList = ScanTaskBaseService.admBaseService?.queryEquipById(equipScanTask.equipId!!)
                if(CollUtil.isEmpty(equipmentList)){
                    return false
                    logger.info("设备任务创建：设备不存在 id "+equipScanTask.equipId)
                }
                val equipment = equipmentList?.get(0)
                if (equipScanTask.schemeId.isNullOrEmpty()){
                    if (equipmentList != null) {
                        val equipment = equipmentList.get(0);
                        equipScanTask.schemeId = SchemeUtils.setScheme(equipment!!.classCode!!)
                    }
                }
//                equipment.ledgerParam.PhotoDoc.Pic

                if(equipment!!.infos != null){//设备图片信息
                    val photoDoc = equipment!!.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)
                        equipScanTask.taskPicList = siInSpList
                    }

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


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

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

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

                if(flag){
                    equipScanTask.equipName = equipment!!.name
                    equipScanTask.localId = equipment!!.localId
                    equipScanTask.localName = equipment!!.localName
                    equipScanTask.bimId = equipment!!.bimId
                    equipScanTask.classCode = equipment!!.classCode
                    equipScanTask.buildingId = equipment!!.buildingId
                    equipScanTask.floorId = equipment!!.floorId
                    equipScanTask.cadId = equipment!!.cadId
//                    equipScanTask.supplier = equipment!!.dpSupplierID


//                    equipScanTask.specification = equipment!!.dpManufacturerID
//                    equipScanTask.manufacturer = equipment!!.dpMaintainerID
                    //equipScanTask.bimLocation = equipment.bimLocation
//                    if (equipment.codeType!=null){
//                        equipScanTask.taskType = equipment.codeType.toString()
//                    }else{
//                        equipScanTask.taskType = "1"
//                    }


                }else {
                   // equipScanTask.bimLocation = equipment.bimLocation
                    if (equipScanTask.equipName.isNullOrEmpty()) {
                        equipScanTask.equipName = equipment!!.name
                    }
                    if (equipScanTask.localId.isNullOrEmpty()) {
                        equipScanTask.localId = equipment!!.localId
                    }
                    if (equipScanTask.localName.isNullOrEmpty()) {
                        equipScanTask.localName = equipment!!.localName
                    }
                    if (equipScanTask.bimId.isNullOrEmpty()) {
                        equipScanTask.bimId = equipment!!.bimId
                    }
                    if (equipScanTask.classCode.isNullOrEmpty()) {
                        equipScanTask.classCode = equipment!!.classCode
                    }
                    if (equipScanTask.buildingId.isNullOrEmpty()) {
                        equipScanTask.buildingId = equipment!!.buildingId
                    }
                    if (equipScanTask.floorId.isNullOrEmpty()) {
                        equipScanTask.floorId = equipment!!.floorId
                    }
                    if (equipScanTask.cadId.isNullOrEmpty()) {
                        equipScanTask.cadId = equipment!!.cadId
                    }
                    if (equipScanTask.manufacturer.isNullOrEmpty()) {
                        if (!equipment.infos.isNullOrEmpty()) {
                            val contains = equipment.infos!!.contains("manufacturer")
                            if (contains) {
                                equipScanTask.manufacturer = equipment.infos!!["manufacturer"].toString()
                            }
                        }
                    }

                    if (equipScanTask.specification.isNullOrEmpty()) {
                        if (!equipment.infos.isNullOrEmpty()) {
                            val contains = equipment.infos!!.contains("specification")
                            if (contains) {
                                equipScanTask.specification = equipment.infos!!["specification"].toString()
                            }
                        }
                    }

                    if (equipScanTask.supplier.isNullOrEmpty()) {
                        if (!equipment.infos.isNullOrEmpty()) {
                            val contains = equipment.infos!!.contains("supplier")
                            if (contains) {
                                equipScanTask.supplier = equipment.infos!!["supplier"].toString()
                            }
                        }
                    }

//                    if (equipScanTask.taskType.isNullOrEmpty()){
//                        if (equipment.codeType!=null){
//                            equipScanTask.taskType = equipment.codeType.toString()
//                        }else{
//                            equipScanTask.taskType = "1"
//                        }
//                    }

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

    /**
     * 重新生成任务时，将任务状态改为已完成
     */
    fun resetTaskStatus(task: ScanTaskBase) {
        val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
        val equipScanTaskService = SBaseService(SMybatisDao(EquipScanTask::class.java))

        //val resetTask = equipScanTaskService.select("equipId" to task.equipId!!, "taskState" to -1).entity()
        val resetTask = ScanTaskBaseService.select(SFilter.eq("equipId", task!!.equipId!!), SFilter.eq("taskState",-1)).entity()
        if (resetTask != null) {
            resetTask.taskState = 0
            ScanTaskBaseService.update(resetTask)//更改设备任务状态
            updateComponetTaskStatus(resetTask)//更改部件任务状态
        }
    }

    /**
     * 更新设备任务状态时，对应更改部件任务状态
     */
    fun updateComponetTaskStatus(task: ScanTaskBase){
        val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
        val equipScanTaskService = SBaseService(SMybatisDao(EquipScanTask::class.java))
        // val componentTaskList = equipScanTaskService.select("parentId" to task!!.equipId!!).exec()
        val componentTaskList = ScanTaskBaseService.select(SFilter.eq("projectId", task!!.equipId!!)).exec()
        for(childTask in componentTaskList){
            childTask.taskState = task.taskState
            ScanTaskBaseService.update(childTask)
        }
    } // Fun updateStatus


}  // Fun