/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.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.mybatis.SMybatisDao
import com.persagy.server.Opts
import com.persagy.server.datacenter.models.entities.assistant.TaskPic
import com.persagy.server.datacenter.models.entities.objects.Equipment
import com.persagy.server.datacenter.models.entities.task.EquipScanTask
import com.persagy.server.datacenter.models.entities.task.SchemeUtils
import com.persagy.server.scanbuilding.UserLog
import com.persagy.server.services.EquipmentService

import com.persagy.server.services.base.RService
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.requests.SCreateRequest
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestBody

/**
 * 设备台账任务
 *
 * @author  邓婷婷
 */
object EquipScanTaskService : RService<EquipScanTask>(SMybatisDao(EquipScanTask::class.java))  {

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

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

    /**
     * 插入之前先过滤已经存在未验证任务的对象，返回新列表
     */
    fun createBefore(@RequestBody request: SCreateRequest<EquipScanTask>): SCreateRequest<EquipScanTask>{
        val equipList = request.content;
        var newList = arrayListOf<EquipScanTask>()
        for(equip in equipList){
            val equipTask = EquipScanTaskService.select("equipId" to equip.equipId!!,"taskState" to 1).entity()
            if(equipTask==null){//表示当前设备不存在未验证的任务
                equip.id = IdUtils.uuidCreate()
                newList.add(equip)
            }
        }

        request.content = newList
        println(newList.size)
        return request
    } // Fun createBefore

    /**
     * 创建之前操作
     */
    override fun onCreateBefore(equipScanTask: EquipScanTask): Boolean  {
        try{
            val gson = Gson()
            var flag = false
            if(equipScanTask.taskState == -1){//前台传数据过来状态为-1 表示当前任务是未找到状态 重新生成任务，将之前的设备任务状态和部件任务改为已完成
                flag = true
                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("id" to equipScanTask.equipId!!).entity()
                if (equipScanTask.schemeId.isNullOrEmpty()){
                    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 {
                    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.supplier.isNullOrEmpty()) {
//                        equipScanTask.supplier = equipment!!.dpSupplierID
//                    }
//                    if (equipScanTask.specification.isNullOrEmpty()) {
//                        equipScanTask.specification = equipment!!.dpManufacturerID
//                    }
//                    if (equipScanTask.manufacturer.isNullOrEmpty()) {
//                        equipScanTask.manufacturer = equipment!!.dpMaintainerID
//                    }
                    if (equipScanTask.bimLocation.isNullOrEmpty()){
                        equipScanTask.bimLocation = equipment.bimLocation
                    }

//                    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()

    /**
     * 设备级联部件，所有部件也增加任务
     */
    override fun onCreateSuccess(equipScanTaskList: ArrayList<EquipScanTask>) {
        val projectId = SPageContext.getHeader("projectId")

        for(task in equipScanTaskList){
            val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
            val componentList = equipmentService.select("parentId" to task.equipId!!).exec()

            for(equipment in componentList){
                val equipScanTask = EquipScanTask()
                equipScanTask.id = IdUtils.uuidCreate()
                if(!task.projectId.isNullOrEmpty()){
                    equipScanTask.projectId = task.projectId
                }else{
                    equipScanTask.projectId = projectId
                }
                equipScanTask.taskSource = 4//数据源为设备台账
                equipScanTask.taskState = 1//任务状态为待验证
                equipScanTask.parentId = task.equipId
                equipScanTask.equipId = equipment!!.id
                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
                equipScanTask.taskParentId = task.id
                if (equipment.codeType!=null){
                    equipScanTask.taskType = equipment.codeType.toString()
                }else {
                    equipScanTask.taskType = "1"
                }

                EquipScanTaskService.insert(equipScanTask)
            }
            resetObjStatus(task)
        }

    } // Fun onCreateSuccess

    /**
     * 状态修改完成之后，若修改为  已完成状态  则级联部件任务状态全部修改为  已完成
     */
    override fun onUpdateSuccess(list: ArrayList<EquipScanTask>) {
        val projectId = SPageContext.getHeader("projectId")
        val comming = SPageContext.getHeader("Coming")
        val account = SPageContext.getHeader("Account")
        for (task in list) {
            val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
            if(task.equipId == null ){
                val equipScanTaskScanTask = EquipScanTaskService.select("id" to task.id!!).entity()
                task.equipId = equipScanTaskScanTask!!.equipId
            }
            if (!task.confirmingPersonId.isNullOrEmpty()&&task.taskState == 0){
                task.taskState = -1
                //更改部件对象状态
                updateComponetObjStatus(task)
                //更改部件任务状态
                updateComponetTaskStatus(task)
            }else if(task.confirmingPersonId.isNullOrEmpty()&&task.taskState == 0) {
                task.taskState = 0
                //更改部件对象状态
                updateComponetObjStatus(task)
                //更改部件任务状态
                updateComponetTaskStatus(task)
            }
            //更改设备对象的状态
            val equipmentOld = equipmentService.select("id" to task.equipId!!).entity()
            if(equipmentOld!!.taskState != -1){//未找到
                val equip = Equipment()
                equip.id = task.equipId!!
                equip.taskState = task.taskState
                equipmentService.update(equip)
            }

            try {
                if (!comming.isNullOrEmpty()){
                    if (comming == "app"){
                        val entity = userService.select(SFilter.eq("projectId", projectId!!), SFilter.eq("phone", account!!)).entity()
                        val userLog = UserLog()
                        userLog.comming = "app"
                        userLog.action = "修改任务"
                        userLog.id = IdUtils.uuidCreate()
                        userLog.note = "项目ID: "+projectId+" 用户ID："+entity!!.id+" 手机号："+ account+" 请求来源："+comming+ " "+task.toJson()
                        userLog.phone = account
                        userLog.projectId = projectId
                        userLog.userId = entity!!.id
                        userLog.name = entity.name
                        userLog.objectId = task.equipId
                        userLogService.insert(userLog)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    } // Fun onUpdateSuccess

    /**
     * 更新设备对象状态时，对应更改部件对象状态，当为未找到状态时，特殊处理
     */
    fun updateComponetObjStatus(task: EquipScanTask){
        val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
        val componentList = equipmentService.select("parentId" to task!!.equipId!!).exec()

        if(task.taskState == 1 || task.taskState == -1){ // 待验证和未找到
            for(component in componentList){
                component.taskState = task.taskState
                equipmentService.update(component)
            }
        }else if(task.taskState == 0){ // 已完成
            for(component in componentList){
                if(component.taskState != -1){//如果部件状态为未找到，则不改变状态
                    component.taskState = task.taskState
                    equipmentService.update(component)
                }
            }
        }
    }

    /**
     * 更新设备任务状态时，对应更改部件任务状态
     */
    fun updateComponetTaskStatus(task: EquipScanTask){
        val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
        val equipScanTaskService = SBaseService(SMybatisDao(EquipScanTask::class.java))

        val componentTaskList = equipScanTaskService.select("parentId" to task!!.equipId!!).exec()

        for(childTask in componentTaskList){
            childTask.taskState = task.taskState
            EquipScanTaskService.update(childTask)
        }
    } // Fun updateStatus

    /**
     * 更新设备对象状态时，对应更改部件对象状态
     */
    fun resetComponetObjStatus(task: EquipScanTask){
        val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))
        val componentList = equipmentService.select("parentId" to task!!.equipId!!).exec()
        for(component in componentList){
            component.taskState = task.taskState
            equipmentService.update(component)
        }
    }

    /**
     * 重新生成任务时，将任务状态改为已完成
     */
    fun resetTaskStatus(task: EquipScanTask) {
        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()
        if (resetTask != null) {
            resetTask.taskState = 0
            equipScanTaskService.update(resetTask)//更改设备任务状态
            updateComponetTaskStatus(resetTask)//更改部件任务状态
        }
    }
        /**
         * 重新生成任务时，将设备和部件状态改变为待验证
         */
     fun resetObjStatus(task: EquipScanTask){
        val equipmentService = SBaseService(SMybatisDao(Equipment::class.java))

        //更改设备对象状态
        val equip = Equipment()
        equip.id = task.equipId!!
        equip.taskState = task.taskState
        equipmentService.update(equip)
        //更改部件对象状态
        resetComponetObjStatus(task)
    }

    override fun onDeleteBefore(entity: EquipScanTask): Boolean {
        try {
            val entity2 = select(SFilter.eq("id", entity.id!!)).entity()
            val entity1 = EquipmentService.select(SFilter.eq("id", entity2!!.equipId!!)).entity()
            if (entity1!=null){
                if (entity1.taskState == 1){
                    entity1.taskState = null
                    EquipmentService.update(entity1, arrayListOf("TaskState"))
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.onDeleteBefore(entity)
    }


} // Class EquipScanTaskService