/*
 * *********************************************************************************************************************
 *
 *          !!
 *        .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.datacenter.services.objects

import com.persagy.base.extensions.toJson
import com.persagy.database.SFilter
import com.persagy.database.SQueryBuilder
import com.persagy.mybatis.SMybatisDao
import com.persagy.server.Opt
import com.persagy.server.datacenter.models.entities.assistant.BuildingFloorInfo
import com.persagy.server.datacenter.models.entities.dictnew.DefFuncIdProject
import com.persagy.server.datacenter.wanda.obj.Equipment
import com.persagy.server.datacenter.models.entities.rel.RSyEq
import com.persagy.server.datacenter.models.entities.rel.RSyEqList
import com.persagy.server.datacenter.models.entities.rel.RSyInBd
import com.persagy.server.datacenter.models.entities.rel.RSyInFl
import com.persagy.server.datacenter.wanda.obj.GeneralSystem
import com.persagy.server.datacenter.wanda.obj.Shaft
import com.persagy.server.datacenter.wanda.obj.ZoneSpace
import com.persagy.server.services.assistant.ObjInfoService
import com.persagy.server.services.base.Service
import com.persagy.server.services.dict.dictnew.DictDefClassService
import com.persagy.server.services.log.DataCenterLogsService
import com.persagy.server.services.rel.RSyInBdService
import com.persagy.server.services.rel.RSyInFlService
import com.persagy.server.utils.IdUtils
import com.persagy.server.utils.ShaftNameUtil
import com.persagy.service.SObjectService
import com.persagy.service.SPageContext
import com.persagy.service.models.enums.SResponseType
import com.persagy.service.models.requests.SCreateRequest
import com.persagy.service.models.requests.SQueryRequest
import com.persagy.service.models.requests.SUpdateRequest
import com.persagy.service.models.responses.SBaseResponse
import com.persagy.service.models.responses.SCreateResponse
import com.persagy.service.models.responses.SQueryResponse
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.xssf.usermodel.XSSFCell
import org.apache.poi.xssf.usermodel.XSSFRow
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.HashMap
import java.util.LinkedHashMap
import javax.servlet.http.HttpServletResponse

/**
 * 系统信息服务
 *
 * @author 张维新
 */
object GeneralSystemService : Service<GeneralSystem>(SMybatisDao(GeneralSystem::class.java)) {

    /** 项目定制化服务 */
    private val defFuncIdProjectService = SObjectService(SMybatisDao(DefFuncIdProject::class.java))

    /**
     * 创建之前的操作
     */
    override fun onCreateBefore(generalSystem: GeneralSystem): Boolean {
        val projectId = SPageContext.getHeader("projectId")
        if (generalSystem.projectId.isNullOrEmpty()) {
            generalSystem.projectId = projectId
        }
        if (generalSystem.classCode.isNullOrEmpty()) {
            return false
        }
        if (!generalSystem.id.isNullOrEmpty()){
            val isWith = generalSystem.id!!.startsWith("Sy")
            if (!isWith) {
                generalSystem.id = IdUtils.systemIdCreate(projectId!!)
            }
        }else {
            generalSystem.id = IdUtils.systemIdCreate(projectId!!)
        }

        if (generalSystem.name.isNullOrEmpty()) {
            /** TODO:待修改 */
            val dClassDef = defClassService.select(
                    SFilter.eq("projectId", Opt.projectId!!),
                    SFilter.eq("code", generalSystem.classCode!!)
            ).entity()
            if (dClassDef!=null){
                generalSystem.name = ShaftNameUtil.shaftName(dClassDef.name+"-")
            }else{
                generalSystem.name = ShaftNameUtil.shaftName("系统-")
            }
        }
        return true
    } // Function onCreateBefore()


    /**
     * 创建系统
     */
    fun createBdFl(request: SCreateRequest<GeneralSystem>): SCreateResponse<GeneralSystem>{

        val contentList = request.content
        if (contentList.isNotEmpty()){

            for (generalSystem in contentList){

                try {
                    if (generalSystem.id.isNullOrEmpty()) {
                        generalSystem.id = IdUtils.systemIdCreate(Opt.projectId!!)
                    } else {
                        val startsWith = generalSystem.id!!.startsWith("Sy")
                        if (!startsWith) {
                            generalSystem.id = IdUtils.systemIdCreate(Opt.projectId!!)
                        }
                    }
                    generalSystem.projectId = Opt.projectId
                    if (generalSystem.name.isNullOrEmpty()) {
                        /** TODO:待修改 */
                        val dClassDef = defClassService.select(
                            SFilter.eq("projectId", Opt.projectId!!),
                            SFilter.eq("code", generalSystem.classCode!!)
                        ).entity()
                        if (dClassDef!=null){
                            generalSystem.name = ShaftNameUtil.shaftName(dClassDef.name+"-")
                        }else{
                            generalSystem.name = ShaftNameUtil.shaftName("系统-")
                        }
                    }

                    val insert = insert(generalSystem)
                    if (insert){
                        /** 处理建筑楼层 */
                        val buildingFloorInfoList = generalSystem.buildingFloorInfoList
                        if (!buildingFloorInfoList.isNullOrEmpty()){

                            for (buildingFloorInfo in buildingFloorInfoList){
                                try {
                                    if (!buildingFloorInfo.buildID.isNullOrEmpty()){
                                        /** 建筑  */
                                        val rSyInBd = RSyInBd()
                                        rSyInBd.buildingId = buildingFloorInfo.buildID
                                        rSyInBd.projectId = Opt.projectId
                                        rSyInBd.sysId = generalSystem.id
                                        rSyInBd.sign = 1
                                        RSyInBdService.replace(rSyInBd)
                                    }
                                    if (!buildingFloorInfo.floorID.isNullOrEmpty()){

                                        val rSyInFl = RSyInFl()
                                        rSyInFl.buildingId = buildingFloorInfo.buildID
                                        rSyInFl.floorId = buildingFloorInfo.floorID
                                        rSyInFl.sysId = generalSystem.id
                                        rSyInFl.sign = 1
                                        rSyInFl.projectId = Opt.projectId
                                        /** 楼层 */
                                        RSyInFlService.replace(rSyInFl)
                                    }
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }
                        try {
                            /** 发送消息 */
                            rabbitMqService.sendObjects(Opt.projectId!!, Opt.CREATE,generalSystem.id!!)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                        try {
                            /** 日志 */
                            DataCenterLogsService.addLogs(Opt.projectId!!,"create",generalSystem.objectType!!,
                                generalSystem.id!!,generalSystem,Opt.account,Opt.coming)
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return  SCreateResponse(SResponseType.success)
        }else{
            return  SCreateResponse(SResponseType.failure)
        }
    } // Function createBdFl()

    /**
     * 查询之前的操作
     */
    override fun onQueryBefore(queryBuilder: SQueryBuilder<GeneralSystem>) {
        return
    } // Function onQueryBefore()

    /**
     * 查询统计之前操作
     */
    override fun onCountBefore(queryBuilder: SQueryBuilder<GeneralSystem>) {
    } // Function onCountBefore()

    /**
     * 删除之前操作
     */
    override fun onDeleteBefore(entity: GeneralSystem): Boolean {
        try {
            val generalSystem = this.select(SFilter.eq("id", entity.id!!)).entity()

                /** 日志 */
                DataCenterLogsService.addLogs(Opt.projectId!!,"delete",generalSystem!!.objectType!!,
                    generalSystem.id!!,generalSystem,Opt.account,Opt.coming)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return super.onDeleteBefore(entity)
    } // Function  onDeleteBefore


    /**
     * 查询没有和当前空间绑定的系统
     *
     * @param   type        空间类型
     * @param   spaceId     空间id
     */
    fun unSpaceSys(type: String, spaceId: String, request: SQueryRequest): SQueryResponse<GeneralSystem> {
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val queryBuilder = select(request.filters)
            queryBuilder.tableName="f_unsys_in_space('$projectId','$type','$spaceId')"
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)

            SQueryResponse(pageInfo)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }

    } // Function  unSpaceSys

//    /**
//     * 查询没有和当前系统关联的设备
//     *
//     * @param   sysId        系统id
//     */
//    fun unSysEquip(sysId: String, request: SQueryRequest): SQueryResponse<Equipment>{
//        return  try {
//            val projectId = SPageContext.getHeader("projectId")
//             val equipmentService = SObjectService(SMybatisDao(Equipment::class.java))
//            val queryBuilder = equipmentService.select(request.filters)
//            queryBuilder.tableName="f_uneq_in_sy_equip('$projectId','$sysId')"
//            if (null != request.projection) {
//                queryBuilder.projection(request.projection!!)
//            }
//            if (null != request.orders) {
//                queryBuilder.order(request.orders!!)
//            }
//
//            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
//
//            SQueryResponse(pageInfo)
//        } catch (e: Exception) {
//            e.printStackTrace()
//            SQueryResponse(SResponseType.failure, "")
//        }
//    } // Fun UnSysEquip

    /**
     * 查询没有和当前系统关联的设备
     *
     * @param   sysId        系统id
     */
    fun unSysEquip(sysId: String, request: SQueryRequest): SQueryResponse<Equipment>{
        return  try {
            val projectId = SPageContext.getHeader("projectId")
            val equipmentService = SObjectService(SMybatisDao(Equipment::class.java))
            val rSyEqService = SObjectService(SMybatisDao(RSyEq::class.java))
            val rSyEqList = rSyEqService.select(SFilter.eq("sysId", sysId), SFilter.eq("projectId", projectId!!)).exec()

            val list = ArrayList<String>()
            val listf = ArrayList<SFilter>()
            for (rSyEq in rSyEqList){
                list.add(rSyEq.equipId!!)
            }

            if (list.size>0){
                listf.add(SFilter.eq("projectId", projectId))
                listf.add(SFilter.not(SFilter.inList("id", list)))
            }else{
                listf.add(SFilter.eq("projectId", projectId))
            }

            equipmentService.pageQuery(request,listf)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, "")
        }
    } // Fun UnSysEquip

    /**
     * 查询没有和当前系统关联的竖井
     *
     * @param   sysId        系统id
     */
    fun unSysShaft(sysId: String, request: SQueryRequest): SQueryResponse<Shaft>{
        return  try {
            val projectId = SPageContext.getHeader("projectId")
            val shaftservice = SObjectService(SMybatisDao(Shaft::class.java))
            val queryBuilder = shaftservice.select(request.filters)
            queryBuilder.tableName="f_uneq_in_sy_shaft('$projectId','$sysId')"
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)

            SQueryResponse(pageInfo)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, "")
        }
    } // Fun unSysShaft

    /**
     * 查询没有和当前系统关联的空间
     *
     * @param   sysId        系统id
     */
    fun unSysZoneSpaceBaseTable(sysId: String, request: SQueryRequest): SQueryResponse<ZoneSpace>{
        return  try {
            val projectId = SPageContext.getHeader("projectId")
            val zoneSpaceBaseTableservice = SObjectService(SMybatisDao(ZoneSpace::class.java))
            val queryBuilder = zoneSpaceBaseTableservice.select(request.filters)
            queryBuilder.tableName="f_uneq_in_sy_space('$projectId','$sysId')"
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }
            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)

            SQueryResponse(pageInfo)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, "")
        }
    } // Fun unSysZoneSpaceBaseTable

    /**
     * 创建系统下的设备关系
     */
    fun createLinkEquip(rSyEqList: RSyEqList): SCreateResponse<RSyEq> {
        return try {
            val projectId = SPageContext.getHeader("projectId")
            val sysId = rSyEqList.sysId
            val service = SObjectService(SMybatisDao(RSyEq::class.java))

            /** 成功集合 */
            val successList = ArrayList<Any>()
            /** 失败集合 */
            val failureList = ArrayList<Any>()

            for (equipId in rSyEqList.equipIdList!!){
                val r = RSyEq()
                r.sysId = sysId
                r.equipId = equipId
                r.projectId = projectId

                var result = service.insert(r)

                if (result){
                    successList.add(r)
                }else{
                    failureList.add(r)
                }
            }
            if (successList.size>0){
                val sCreateResponse = SCreateResponse<RSyEq>(SResponseType.success)
                if (failureList.size>0){
                    sCreateResponse.message ="失败对象："+failureList.toJson()
                }
                sCreateResponse
            }else{
                SCreateResponse(SResponseType.failure)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            SCreateResponse(SResponseType.failure,e.message.toString())
        }
    }

    /**
     * 查询系统信息
     */
    fun pageQuerys(buildingId: String?, floorId: String?,request: SQueryRequest): SQueryResponse<GeneralSystem> {
        val projectId = SPageContext.getHeader("projectId")
        val syinFlService = SObjectService(SMybatisDao(RSyInFl::class.java))
        val syinBdService = SObjectService(SMybatisDao(RSyInBd::class.java))
        val buildingFloorInfoService = SObjectService(SMybatisDao(BuildingFloorInfo::class.java))
        val idList = ArrayList<String>()
        val notIdList = ArrayList<String>()
        var list = ArrayList<SFilter>()
        list.add(SFilter.eq("projectId",projectId!!))

        if(!floorId.isNullOrEmpty()&&!floorId.equals("1")&&(buildingId.isNullOrEmpty()||buildingId.equals("1"))){
            /** 楼层id不为空且不为1，建筑id为空 ---> 系统和楼层关系表 取系统id */
            val objList = syinFlService.select(SFilter.eq("floorId", floorId)).distinct().projection("sysId").exec()
            if(!objList.isNullOrEmpty()){
                for (obj in objList){
                    idList.add(obj.sysId!!)
                }
            }else{
                idList.add("")
            }
            list.add(SFilter.inList("id",idList))
        }else if((floorId.isNullOrEmpty()||floorId.equals("1"))&&!buildingId.isNullOrEmpty()&&!buildingId.equals("1")){
            /** 楼层id为空，建筑id不为空且不为1 ---> 系统和建筑关系表 取系统id */
            val objList = syinBdService.select(SFilter.eq("buildingId", buildingId)).distinct().projection("sysId").exec()
            if(!objList.isNullOrEmpty()) {
                for (obj in objList) {
                    idList.add(obj.sysId!!)
                }
            }else{
                idList.add("")
            }
            list.add(SFilter.inList("id", idList))
        }else if(!floorId.isNullOrEmpty()&&floorId.equals("1")&&!buildingId.isNullOrEmpty()&&buildingId.equals("1")){
            /** 楼层id为1，建筑id为1 ---> 系统id不在（系统和楼层关系表 取系统id  系统和建筑关系表 取系统id）之内*/
            val objList1 = syinFlService.selectAll().distinct().projection("sysId").exec()
            if(!objList1.isNullOrEmpty()){
                for (obj in objList1){
                    idList.add(obj.sysId!!)
                }
            }
            val objList2 = syinBdService.selectAll().distinct().projection("sysId").exec()
            if(!objList2.isNullOrEmpty()) {
                for (obj in objList2) {
                    idList.add(obj.sysId!!)
                }
            }
            list.add(SFilter.not(SFilter.inList("id", idList)))
        }else if(!floorId.isNullOrEmpty()&&!floorId.equals("1")&&!buildingId.isNullOrEmpty()&&!buildingId.equals("1")){
            /** 楼层id不为空，建筑id不为空 ---> 系统和楼层关系表 取系统id  将建筑id作为条件 */
            val objList = syinFlService.select(SFilter.eq("floorId", floorId),SFilter.eq("buildingId", buildingId)).distinct().projection("sysId").exec()
            if(!objList.isNullOrEmpty()) {
                for (obj in objList) {
                    idList.add(obj.sysId!!)
                }
            }else{
                idList.add("")
            }
            list.add(SFilter.inList("id", idList))
        }
//        else if(floorId.isNullOrEmpty()&&buildingId.isNullOrEmpty()){
//            /** 楼层id为空，建筑id为空 ---> 查询所有 */
//        }
        val pageInfo = pageQuery(request, list)

        for(system in pageInfo.content!!){
            val queryBuilder = buildingFloorInfoService.selectAll()
            queryBuilder.tableName="f_get_bd_and_fl('${system.id}','$buildingId','$floorId')"
            val bdflList = queryBuilder.exec()
            system.buildingFloorInfoList = bdflList
        }
        return pageInfo
    } // Fun pageQuerys

    /**
     * @Description: 创建成功
     */
    override fun onCreateSuccess(entityList: ArrayList<GeneralSystem>) {
        super.onCreateSuccess(entityList)
        for (generalSystem in entityList) {
            try {
                /** 发送消息 */
                rabbitMqService.sendObjects(Opt.projectId!!, Opt.CREATE,generalSystem.id!!)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            try {
                /** 日志 */
                DataCenterLogsService.addLogs(Opt.projectId!!,"create",generalSystem.objectType!!,
                    generalSystem.id!!,generalSystem,Opt.account,Opt.coming)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            ObjInfoService.createInfo(generalSystem,true,"Sy",generalSystem.classCode!!)
        }
    }

    /**
     * @Description: 更新信息点
     */
    override fun onUpdateSuccess(entityList: ArrayList<GeneralSystem>) {
        super.onUpdateSuccess(entityList)
        for (generalSystem in entityList) {
            try {
                /** 发送消息 */
                rabbitMqService.sendObjects(Opt.projectId!!, Opt.UPDATE,generalSystem.id!!)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            try {
                /** 日志 */
                DataCenterLogsService.addLogs(Opt.projectId!!,"update",generalSystem.objectType!!,
                    generalSystem.id!!,generalSystem,Opt.account,Opt.coming)
            } catch (e: Exception) {
                e.printStackTrace()
            }
            ObjInfoService.createInfo(generalSystem,false,"Sy",generalSystem.classCode!!)
        }
    }

    /**
     * @Description:删除成功之后
     */
    override fun onDeleteSuccess(entityList: ArrayList<GeneralSystem>) {
        super.onDeleteSuccess(entityList)
        try {
            val projectId = SPageContext.getHeader("projectId")
            for (generalSystem in entityList) {
                try {
                    /** 发送消息 */
                    rabbitMqService.sendObjects(Opt.projectId!!, Opt.DELETE,generalSystem.id!!)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                try {
                    /** 日志 */
                    DataCenterLogsService.addLogs(Opt.projectId!!,"delete",generalSystem.objectType!!,
                        generalSystem.id!!,generalSystem,Opt.account,Opt.coming)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                ObjInfoService.delete(SFilter.eq("projectId",projectId!!), SFilter.eq("objId",generalSystem.id!!), SFilter.eq("objType","Sy"))
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }



    fun exportExcel(response: HttpServletResponse, projectId: String, classCode: String) {
        response.contentType = "application/octet-stream"
        response.setHeader("Content-disposition", "attachment;filename=equip-$classCode.xlsx")
        response.flushBuffer()
        val defFuncIds = defFuncIdProjectService.select(SFilter.eq("projectId",projectId), SFilter.eq("classCode",classCode)).exec()

        val equipments = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.eq("classCode", classCode)).exec()
        val list = java.util.ArrayList<List<Any>>()
        val firstList = java.util.ArrayList<String>()
        val codeList = java.util.ArrayList<String>()
        codeList.add("id")
        codeList.add("bimTypeId")
        codeList.add("systemCategory")
        codeList.add("codeName")
        codeList.add("localId")
        firstList.add("设备ID-id")
        firstList.add("BIM构件编码-bimTypeId")
        firstList.add("系统分类-systemCategory")
        firstList.add("设备类型名称-codeName")
        firstList.add("本地编码-localId")
        for (defFuncId in defFuncIds) {
            codeList.add(defFuncId.code!!)
            firstList.add("${defFuncId.name}-${defFuncId.code}")
        }


        list.add(firstList)
        for (equipment in equipments) {
            val itemList = java.util.ArrayList<Any>()
            val infos = equipment.infos
            for (s in codeList) {
                if(s == "id"){
                    itemList.add(equipment.id?:"")
                } else if(s == "bimTypeId"){
                    itemList.add(equipment.bimTypeId?:"")
                }else if(s == "systemCategory"){
                    itemList.add(equipment.systemCategory?:"")
                }else if(s == "codeName"){
                    itemList.add(equipment.codeName?:"")
                }else if(s == "localId"){
                    itemList.add(equipment.localId?:"")
                }else{
                    if(infos != null && infos[s] != null){
                        itemList.add(infos[s]!!)
                    }else{
                        itemList.add("")
                    }
                }


            }
            list.add(itemList)

        }
        writeExcel(list,response.outputStream)


    } // Fun exportExcel


    /**
     * 把内容写入Excel
     * @param list 传入要写的内容，此处以一个List内容为例，先把要写的内容放到一个list中
     * @param outputStream 把输出流怼到要写入的Excel上，准备往里面写数据
     */
    fun writeExcel(list: List<List<*>>, outputStream: OutputStream){
        //创建工作簿
        var xssfWorkbook = XSSFWorkbook()

        //创建工作表
        val xssfSheet: XSSFSheet
        xssfSheet = xssfWorkbook.createSheet("系统绑点")

        //创建行
        var xssfRow: XSSFRow

        //创建列，即单元格Cell
        var xssfCell: XSSFCell

        //把List里面的数据写到excel中
        for (i in list.indices) {
            //从第一行开始写入
            xssfRow = xssfSheet.createRow(i)
            //创建每个单元格Cell，即列的数据
            val sub_list = list[i]
            for (j in sub_list.indices) {
                xssfCell = xssfRow.createCell(j) //创建单元格
                xssfCell.setCellValue(sub_list[j] as String?) //设置单元格内容
            }
        }

        //用输出流写到excel
        try {
            xssfWorkbook.write(outputStream)
            outputStream.flush()
            outputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun importExcel(file: MultipartFile, projectId: String, classCode: String) : SBaseResponse {
        try {

            val equipments = EquipmentService.select(SFilter.eq("projectId", projectId), SFilter.eq("classCode", classCode)).exec()
            val equipMap = HashMap<String,Equipment>()
            for (equipment in equipments) {
                equipMap[equipment.id!!] = equipment
            }
            val content = java.util.ArrayList<Equipment>()
            val list = readExcel(file.inputStream,"")
            for (map in list) {
                val infos = HashMap<String,Any?>()
                var equipId : String? = null
                for (key in map.keys) {
                    val code = key.substring(key.lastIndexOf("-"),key.length)
                    if(code == "id"){
                        equipId = map[key]!!
                    } else if(code == "bimTypeId"){

                    }else if(code == "systemCategory"){

                    }else if(code == "codeName"){

                    }else if(code == "localId"){

                    }else{
                        if(!map[key].isNullOrEmpty()){
                            infos[key] = map[key]
                        }
                    }
                }

                val equipment = equipMap[equipId]
                if(equipment != null){
                    content.add(equipment)
                }
            }
            val request = SUpdateRequest<Equipment>()
            request.content = content
            EquipmentService.updateList(request)


        }catch (e : Exception){
            return SBaseResponse(SResponseType.failure,"error:" + e.message)
        }
        return SBaseResponse(SResponseType.success, "")
    }

    /**
     * 读取Excel文件的内容
     * @param inputStream excel文件，以InputStream的形式传入
     * @param sheetName sheet名字
     * @return 以List返回excel中内容
     */
    fun readExcel(inputStream: InputStream?, sheetName: String): List<Map<String, String>> {

        //定义工作簿
        var xssfWorkbook: XSSFWorkbook? = null
        try {
            xssfWorkbook = XSSFWorkbook(inputStream)
        } catch (e: Exception) {
            println("Excel data file cannot be found!")
        }

        //定义工作表
        val xssfSheet: XSSFSheet
        xssfSheet = if (sheetName == "") {
            // 默认取第一个子表
            xssfWorkbook!!.getSheetAt(0)
        } else {
            xssfWorkbook!!.getSheet(sheetName)
        }
        val list = java.util.ArrayList<LinkedHashMap<String, String>>()

        //定义行
        //默认第一行为标题行，index = 0
        val titleRow = xssfSheet.getRow(0)

        //循环取每行的数据
        for (rowIndex in 1 until xssfSheet.physicalNumberOfRows) {
            val xssfRow = xssfSheet.getRow(rowIndex) ?: continue
            val map = LinkedHashMap<String, String>()
            //循环取每个单元格(cell)的数据
            for (cellIndex in 0 until xssfRow.physicalNumberOfCells) {
                val titleCell = titleRow.getCell(cellIndex)
                val xssfCell = xssfRow.getCell(cellIndex)
                map[getString(titleCell)] = getString(xssfCell)
            }
            list.add(map)
        }
        return list
    }

    /**
     * 把单元格的内容转为字符串
     * @param xssfCell 单元格
     * @return 字符串
     */
    fun getString(xssfCell: XSSFCell?): String {
        if (xssfCell == null) {
            return ""
        }
        return if (xssfCell.cellType == CellType.NUMERIC) {
            xssfCell.numericCellValue.toString()
        } else if (xssfCell.cellType == CellType.BOOLEAN) {
            xssfCell.booleanCellValue.toString()
        } else {
            xssfCell.stringCellValue
        }
    }


} // Object GeneralSystemService