/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.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.dict.EquipFamilyCategory
import com.persagy.server.datacenter.datacenter.models.entities.objects.Property
import com.persagy.server.datacenter.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.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
import java.util.*
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))
    /**
     * 插入之前先过滤已经存在未验证任务的对象，返回新列表
     */
    fun createBefore(@RequestBody request: SCreateRequest<PropertyScanTask>): SCreateRequest<PropertyScanTask> {
        val propertyTaskList = request.content;
        var newList = arrayListOf<PropertyScanTask>()
        for(property in propertyTaskList){
            val propertyTask = PropertyScanTaskService.select("equipId" to property.equipId!!,"taskState" to 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("equipId" to propertyScanTask.equipId!!,"taskState" to -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("id" to propertyScanTask.equipId!!).entity()
                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)
        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)
        }
    } // Fun onCreateSuccess

    /**
     * 状态修改完成之后
     */
    override fun onUpdateSuccess(list: ArrayList<PropertyScanTask>) {
        val projectId = SPageContext.getHeader("projectId")
        val comming = SPageContext.getHeader("Coming")
        val account = SPageContext.getHeader("Account")
        for (task in list) {
            val propertyService = SBaseService(SMybatisDao(Property::class.java))
            if(task.equipId == null ){
                val propertyScanTask = PropertyScanTaskService.select("id" to task.id!!).entity()
                task.equipId = propertyScanTask!!.equipId
            }
            //更改设备对象的状态
            val propertyOld = propertyService.select("id" to task.equipId!!).entity()
            if(propertyOld!!.taskState != -1) {//未找到
                val property = Property()
                property.id = task.equipId!!
                property.taskState = task.taskState
                propertyService.update(property)
            }
            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

    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()
                if (entity!=null) {
                    content.equipFamily = entity
                }
            }
        }
        super.onQuerySuccess(pageInfo)

    }



} // Class PropertyScanTaskService