package com.persagy.server.services.dict

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.datacenter.models.entities.dict.*
import com.persagy.server.datacenter.models.response.*
import com.persagy.server.services.base.Service
import com.persagy.server.utils.RecursiveQuery
import com.persagy.service.SBaseService
import com.persagy.service.SObjectService
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 org.slf4j.LoggerFactory
import java.util.concurrent.Executors

/**
 * 项目定制化字典说明
 *
 * @author 张维新
 */
object PropertyDefProjectService : Service<PropertyDefProjectInfo>(SMybatisDao(PropertyDefProjectInfo::class.java)) {

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

    /** 建筑朝向  方向代码 */
    private val dictBuildingDirectService = SBaseService(SMybatisDao(DictDirection::class.java))
    /** 建筑功能 */
    private val dictBuildingFunctionalService = SBaseService(SMybatisDao(DictBuildingFunctional::class.java))
    /** 服务 */
    private val dictRentalservice = SBaseService(SMybatisDao(DictRental::class.java))
    /** 设备族对应的设备分类服务 */
    private val equipFamilyservice = SBaseService(SMybatisDao(EquipFamily::class.java))
    /** 空间功能类型 */
    private val spaceFunctionalservice = SBaseService(SMybatisDao(DictSpaceFunctionalTypes::class.java))
    /** 省市区代码 */
    private val dictProvincialCityCodeService = SBaseService(SMybatisDao(DictProvincialCityCode::class.java))

    /** 污染等级 */
    private val dictPollutionLevelService = SObjectService(SMybatisDao(DictPollutionLevel::class.java))

    /** 污秽等级 */
    private val dictContaminationLevelService = SObjectService(SMybatisDao(DictContaminationLevel::class.java))

    /** 抗震设防烈度 */
    private val dictSeismicFortificationIntensityService = SObjectService(SMybatisDao(DictSeismicFortificationIntensity::class.java))

    /** 业务空间类型服务 */
    var dictSpaceProjectService = SObjectService(SMybatisDao(DictSpaceProject::class.java))

    var executor = Executors.newFixedThreadPool(2)

    /**
     * 分页查询
     *
     * @param   request     查询条件
     * @return              查询结果
     */
    fun pageQuery(type:String?, request: SQueryRequest): SQueryResponse<PropertyDefProjectInfo> {
        return try {

            var dictProjectList : ArrayList<PropertyDefProjectInfo>? = null
            val projectId = SPageContext.getHeader("ProjectId")
            val queryBuilder = select(request.filters)
            var code: String?
            code = type
            if (type!=null&&code!!.length == 3){
                val equipFamily = equipFamilyservice.select("family = '$code'").entity()
                code = equipFamily!!.equipCode!!
            }

           if (!type.isNullOrEmpty()){
               dictProjectList = DataDictionaryDescriptionProjectService.select(SFilter.eq("projectId", projectId!!),
                       SFilter.eq("type", type)).exec()
               if (!dictProjectList.isNullOrEmpty()&&dictProjectList.size>0){
                   DataDictionaryDescriptionProjectService.select(SFilter.eq("projectId", projectId), SFilter.eq("type", type)).exec()
                   queryBuilder.tableName = "dict.property_def_project_info"
                   queryBuilder.filter(SFilter.eq("projectId", projectId)).filter(SFilter.eq("type", type))
               }else{
                   logger.debug("输入的类型=$type   长度是=${type.length}")
                   if (type != "Project"&&type != "Building"&&type != "Floor"&&type != "Shaft"&&type != "Tenant"&&type != "HeatingZone"
                           &&type != "CleanZone"&&type != "DomesticWaterSupplyZone"&&type != "Ispace"&&type != "NetworkZone"&&type != "TenantZone"
                           &&type != "AirConditioningZone"&&type != "FunctionZone"&&type != "FireZone"&&type != "SecurityZone"&&type != "GeneralZone"
                           &&type != "PowerSupplyZone"&&type != "LightingZone" ){
                       val dictSpaceProject = dictSpaceProjectService.select(SFilter.eq("id", type)).entity()
                       if (dictSpaceProject!=null){
//                           if (type.length == 3){
//                               queryBuilder.tableName = "\"dict\".\"f_project_def_property\"('$code')"
//                           }else{
                               queryBuilder.tableName = "\"dict\".\"f_project_def\"('${SPageContext.getHeader("ProjectId")}', 'OtherZone')"
//                           }
                       }else {
                           if (type.length == 3){
                               queryBuilder.tableName = "\"dict\".\"f_project_def_property\"('$code')"
                           }else{
                               queryBuilder.tableName = "\"dict\".\"f_project_def\"('${SPageContext.getHeader("ProjectId")}', '$code')"
                           }
                       }

                   }else{
                       if (type.length == 3){
                           queryBuilder.tableName = "\"dict\".\"f_project_def_property\"('$code')"
                       }else{
                           queryBuilder.tableName = "\"dict\".\"f_project_def\"('${SPageContext.getHeader("ProjectId")}', '$code')"
                       }
                   }
               }
           }else{
               queryBuilder.tableName = "\"dict\".\"f_project_def\"('${SPageContext.getHeader("ProjectId")}', '')"
           }
//            queryBuilder.tableName = "\"dict\".\"f_property_def\"('${SPageContext.getHeader("ProjectId")}', '$code')"

            /** 过滤 */
            if (null != request.projection) {
                queryBuilder.projection(request.projection!!)
            }
            /** 排序 */
            if (null != request.orders) {
                queryBuilder.order(request.orders!!)
            }

            /** 去重 */
            if (null != request.distinct && request.distinct!!) {
                queryBuilder.distinct()
            }

            val pageInfo = queryBuilder.pageQuery(request.pageNumber, request.pageSize)
            val contentList = pageInfo.content

            Thread {
                if (!type.isNullOrEmpty()){
                    /** 项目化定制表如果没有对应数据添加数据 */
                    if (dictProjectList.isNullOrEmpty()|| dictProjectList.size==0){
                        val contentList = pageInfo.content
                        for (content in contentList!!){
                            val propertyDefProjectInfo = PropertyDefProjectInfo()
                            propertyDefProjectInfo.dataSource = content.dataSource
                            logger.debug("数据源=${content.dataSource}")
                            propertyDefProjectInfo.dataType = content.dataType
                            propertyDefProjectInfo.unDisabled = content.unDisabled
                            propertyDefProjectInfo.editable = content.editable
                            propertyDefProjectInfo.firstName = content.firstName
                            propertyDefProjectInfo.firstTag = content.firstTag
                            propertyDefProjectInfo.flag = content.flag
                            propertyDefProjectInfo.infoPointCode = content.infoPointCode
                            propertyDefProjectInfo.infoPointName = content.infoPointName
                            propertyDefProjectInfo.inputMode = content.inputMode
                            propertyDefProjectInfo.note = content.note
                            propertyDefProjectInfo.priority = content.priority
                            propertyDefProjectInfo.projectId = projectId
                            propertyDefProjectInfo.secondName = content.secondName
                            propertyDefProjectInfo.secondTag = content.secondTag
                            propertyDefProjectInfo.sort = content.sort
                            propertyDefProjectInfo.unit = content.unit
                            propertyDefProjectInfo.visible = content.visible
                            propertyDefProjectInfo.type = type
                            DataDictionaryDescriptionProjectService.replace(propertyDefProjectInfo)
                        }
                    }
                }
            }.start()
            for (content in contentList!!) {
//                if (!"见《9租赁业态类型》".equals(content.dataSource, true)) continue
//                val service = SBaseService(SMybatisDao(DictRentalSyn::class.java))
//                content.dataSource = net.minidev.json.JSONArray.toJSONString(service.select(SFilter.notNull("id")).exec())


                if (!content.dataSource.isNullOrEmpty() && content.dataSource!!.contains("见《")||!content.dataSource.isNullOrEmpty() && content.dataSource!!.contains("参考")) {
                    // TODO: 有时间转为when表达
                    if (content.dataSource!!.contains("省市区代码")) {

                        /** 获取省一级信息 */
                        val provincialCityCodeList = DictProvincialCityCodeService.select(SFilter.isNull("parent"), SFilter.eq("specialCities", 0)).exec()
                        val contentBean = ContentBean()
                        val normalLiat = ArrayList<NormalBean>()
                        for (province in provincialCityCodeList){
                            val normalBean = NormalBean()
                            normalBean.provinceCode = province.id
                            normalBean.provinceName = province.name
                            val infoList = ArrayList<ProvinceInfoBean>()
                            val provinceInfoBean = ProvinceInfoBean()
                            provinceInfoBean.code = province.code
                            provinceInfoBean.name = province.name
                            infoList.add(provinceInfoBean)
                            normalBean.provinceInfo = infoList
                            val arrayList = ArrayList<CitiesBean>()
                            /** 城市 */
                            val cityList = DictProvincialCityCodeService.select(SFilter.eq("parent", province.code!!)).exec()
                            for (city in cityList){
                                val citiesBean = CitiesBean()
                                citiesBean.cityName = city.name
                                citiesBean.cityCode = city.id
                                citiesBean.climate = city.climateZone
                                citiesBean.developLevel = city.developmentLevel

                                val arrayListInfo = ArrayList<CityInfoBean>()

                                val cityInfoBean = CityInfoBean()
                                cityInfoBean.code = city.code
                                cityInfoBean.altitude = city.altitude
                                cityInfoBean.latitude = city.latitude
                                cityInfoBean.longitude = city.longitude
                                cityInfoBean.name = city.name
                                arrayListInfo.add(cityInfoBean)
                                citiesBean.cityInfo = arrayListInfo

                                val regionArrayList = ArrayList<DistrictBean>()
                                val regionList = DictProvincialCityCodeService.select(SFilter.eq("parent", city.code!!)).exec()
                                for (region in regionList){
                                    val districtBean = DistrictBean()
                                    districtBean.code = region.code
                                    districtBean.altitude = region.altitude
                                    districtBean.districtCode = region.id
                                    districtBean.developLevel = region.developmentLevel
                                    districtBean.districtName = region.name
                                    districtBean.latitude = region.latitude
                                    districtBean.longitude = region.longitude
                                    regionArrayList.add(districtBean)
                                }
                                citiesBean.district = regionArrayList

                                arrayList.add(citiesBean)
                            }
                            normalBean.cities = arrayList
                            normalLiat.add(normalBean)
                        }

                        contentBean.normal = normalLiat
                        /** 特殊地区代码 */
                        val specialList = DictProvincialCityCodeService.select(SFilter.isNull("parent"), SFilter.eq("specialCities", 1)).exec()

                        val specialCitiesList = ArrayList<SpecialCitiesBean>()
                        for (special in specialList){
                            val specialCitiesBean = SpecialCitiesBean()
                            specialCitiesBean.code = special.id
                            specialCitiesBean.climate = special.climateZone
                            specialCitiesBean.developLevel = special.developmentLevel
                            specialCitiesBean.name = special.name

                            val cityInfoBeanList = ArrayList<CityInfoBeanX>()
                            val cityInfoBeanX = CityInfoBeanX()
                            cityInfoBeanX.altitude = special.altitude
                            cityInfoBeanX.code = special.code
                            cityInfoBeanX.name = special.name
                            cityInfoBeanX.latitude = special.latitude
                            cityInfoBeanX.longitude = special.longitude
                            cityInfoBeanList.add(cityInfoBeanX)
                            specialCitiesBean.cityInfo = cityInfoBeanList

                            val cityCodeList = DictProvincialCityCodeService.select(SFilter.eq("parent", special.code!!)).exec()
                            val districtList = ArrayList<DistrictBeanX>()
                            for (cityCode in cityCodeList){
                                val districtBeanX = DistrictBeanX()
                                districtBeanX.code = cityCode.code
                                districtBeanX.altitude = cityCode.altitude
                                districtBeanX.cityCode = cityCode.typeCode
                                districtBeanX.districtCode = cityCode.id
                                districtBeanX.districtName = cityCode.name
                                districtBeanX.latitude = cityCode.latitude
                                districtBeanX.longitude = cityCode.longitude
                                districtBeanX.type = cityCode.type
                                districtList.add(districtBeanX)
                            }
                            specialCitiesBean.district = districtList
                            specialCitiesList.add(specialCitiesBean)
                        }
                        contentBean.specialCities = specialCitiesList
                        logger.debug("城市信息=${contentBean.toJson()}")
                        content.dataSource = contentBean.toJson()
//                        content.dataSource = null
                    } else if (content.dataSource!!.contains("气候区代码")) {
                        content.dataSource = null
                        try {
                            val dictClimateAllList = ArrayList<DictClimate>()
                            val  dictClimateList = DictClimateService.select(SFilter.isNull("parent")).exec()
                            for (dictC in dictClimateList){
                                val dic = DictClimate()
                                dic.id = dictC.id
                                dic.name = dictC.name
    //                            val tree = RecursiveQuery.treeClimate(dic.id!!, true)
                                val content = DictClimateService.select("parent" to dic.id!!).exec()
    //                            logger.debug("dexecList =$tree")
                                dic.content = content
                                dictClimateAllList.add(dic)
                            }
                            content.dataSource = dictClimateAllList.toJson()
                            logger.debug("气候区代码=${dictClimateAllList.toJson()}")
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } else if (content.dataSource!!.contains("发展水平代码")) {
                        content.dataSource = null
                    } else if (content.dataSource!!.contains("天气状态")) {
                        content.dataSource = null
                    } else if (content.dataSource!!.contains("空气风力等级")) {
                        content.dataSource = null
                    } else if (content.dataSource!!.contains("方向代码")) {
                        /** 方向代码 */
                        val directionList = dictBuildingDirectService.selectAll().exec()
                        val directionAllList = ArrayList<DictDirection>()
                        for (direction in directionList){
                            val dictDirection = DictDirection()
                            dictDirection.id = direction.id
                            dictDirection.name = direction.name
                            dictDirection.angle = direction.angle
                            dictDirection.directionCode = direction.directionCode
                            directionAllList.add(dictDirection)
                        }
                        content.dataSource = directionAllList.toJson()
                    } else if (content.dataSource!!.contains("建筑功能类型")) {
                        val buildingList = dictBuildingFunctionalService.select(SFilter.eq("parent", "")).exec() as ArrayList<DictBuildingFunctional>
                        for (b in buildingList){
                            b.parent = null
                            val treeBuildingFunctionalList = RecursiveQuery.treeBuildingFunctional(b.id!!, true)
                            b.content = treeBuildingFunctionalList
                        }
                        content.dataSource = buildingList.toJson()
                    } else if (content.dataSource!!.contains("空间功能类型")) {
                        val dictSpaceFunctionalTypesList = spaceFunctionalservice.select(SFilter.isNull("parent")).exec()
                        for (dictSpace in dictSpaceFunctionalTypesList){
                            dictSpace.parent = null
                            dictSpace.lastUpdate = null
                            dictSpace.createTime = null
                            val dictSpaceFunctionalTreeDictRental = RecursiveQuery.dictSpaceFunctionalTreeDictRental(dictSpace.id!!)
                            dictSpace.content = dictSpaceFunctionalTreeDictRental
                        }
                        content.dataSource = dictSpaceFunctionalTypesList.toJson()
                    } else if (content.dataSource!!.contains("租赁业态类型")) {
                        val oneLevelList = dictRentalservice.select(SFilter.isNull("parent")).exec()
                        for (oneLevel in oneLevelList) {
                            oneLevel.parent = null
                            oneLevel.lastUpdate = null
                            oneLevel.createTime = null
                            val treeSpaceFunctional = RecursiveQuery.treeDictRental(oneLevel.id!!)
                            oneLevel.content = treeSpaceFunctional
                        }
                        content.dataSource = oneLevelList.toJson()
                    } else if (content.dataSource!!.contains("抗震设防烈度")) {
                        try {
                            val dictSeismicFortificationIntensityList = dictSeismicFortificationIntensityService.selectAll().exec()
                            if (!dictSeismicFortificationIntensityList.isEmpty()){
                                content.dataSource = dictSeismicFortificationIntensityList.toJson()
                            }else{
                                content.dataSource = null
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                            content.dataSource = null
                        }
                    } else if (content.dataSource!!.contains("污秽等级")) {

                        val dictContaminationLevelList = dictContaminationLevelService.selectAll().exec()
                        if (!dictContaminationLevelList.isEmpty()){
                            content.dataSource = dictContaminationLevelList.toJson()
                        }else{
                            content.dataSource = null
                        }

                    } else if (content.dataSource!!.contains("污染等级")) {
                        val dictPollutionLevelList = dictPollutionLevelService.selectAll().exec()
                        content.dataSource = dictPollutionLevelList.toJson()

                    } else if (content.dataSource!!.contains("防护等级")) {
                        content.dataSource = null
                    } else if (content.dataSource!!.contains("地理分区")) {
                        content.dataSource = null
                    } else if (content.dataSource!!.contains("职业分类")) {
                        content.dataSource = null
                    }
                }
            }
            SQueryResponse(pageInfo)
        } catch (e: Exception) {
            e.printStackTrace()
            SQueryResponse(SResponseType.failure, e.message!!)
        }
    } // Function pageQuery()

    /**
     * 查询之前操作
     */
    override fun onQueryBefore(queryBuilder: SQueryBuilder<PropertyDefProjectInfo>) {
        val projectId = SPageContext.getHeader("ProjectId")
        queryBuilder.tableName = "dict.f_filter_labels('$projectId')"

        super.onQueryBefore(queryBuilder)
    } // Function onQueryBefore()

} // object PropertyDefService