/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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 com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.persagy.database.SFilter
import com.persagy.database.SPageQueryInfo
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.datacenter.datacenter.models.entities.task.EquipScanTask
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.base.RService
import com.persagy.service.SBaseService
import com.persagy.service.SPageContext
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

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

    /** 实例化 mapper 对象 */
    val mapper by lazy {
        SSpringContextUtil.getBean(StatisticsCountMapper::class.java) as StatisticsCountMapper
    }

    /**
     * 查询所有设备类型或设备族
     */
    fun equipCategoryQuery(type: String): SQueryResponse<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!!)
        }
    } //  Fun equipCategoryQuery

    /**
     * 查询所有建筑和楼层
     */
    fun buildingQuery(type: String): SQueryResponse<BuildingDic> {
        val pageQuery: SPageQueryInfo<BuildingDic>
        val gson = Gson()
        return try {
            val projectId = SPageContext.getHeader("projectId").toString()
            var request = SQueryRequest()
            val service = SBaseService(SMybatisDao(BuildingDic::class.java))
            val queryBuilder = service.select(request.filters)
            queryBuilder.tableName = "scantask.f_get_building_dic('$type','$projectId')"
            pageQuery = queryBuilder.pageQuery(1, 1000)

            if (pageQuery.content!=null&&pageQuery.content!!.size>0){
                for(floor in pageQuery.content!!){
                    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.floorList = 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.floorList!=null&&building.floorList!!.size>0){

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

                        }else{
                            val equipScanTaskList = select(SFilter.eq("projectId", projectId), SFilter.eq("buildingId", building.buildingId!!),
                                    SFilter.isNull("floorId"),SFilter.eq("taskSource", taskSource)).exec()
                            if (equipScanTaskList.size>0){
                                val list = ArrayList<FloorDic>()
                                val floorDic = FloorDic()
                                floorDic.floorName = "未明确楼层"
                                list.add(floorDic)
                                building.floorList= list
                            }
                        }
                    }
                    /** 未明确建筑 */
                    val equipScanTaskList = select(SFilter.eq("projectId", projectId), SFilter.isNull("buildingId"),SFilter.eq("taskSource", taskSource)).exec()
                    if (equipScanTaskList.size>0){
                        val buildingDic = BuildingDic()
                        buildingDic.buildingName = "未明确建筑"
                        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.buildingName = "未明确建筑"
                        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 = mapper.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 = ModelScanTaskService.mapper.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 = mapper.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