package com.persagy.revit.services.endpoint

import com.persagy.revit.models.floor.FloorExpr
import com.persagy.revit.models.modelFile.FloorModelView
import com.persagy.revit.services.comparator.FloorComparator
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.regex.Pattern
import kotlin.math.absoluteValue

/**
 *
 *
 * @author jxing
 */
@Component
class FloorService {
    @Autowired
    lateinit var floorComparator: FloorComparator

    val pattern = "^((([F|B])([1-9][0-9]{0,4}))|RF)((M)([1-9]{1,4})?)?$"
    // 创建 Pattern 对象
    val regex = Pattern.compile(pattern)

    fun addMissingFloor(list: MutableList<FloorModelView>): MutableList<FloorModelView> {
        val floors = ArrayList<FloorExpr>()
        val floorNumSet = HashSet<Int>()
        list.forEach {
            val match = regex.matcher(it.floorName!!)
            if(match.find()){
                val floorExpr = FloorExpr()
                val floorBF = match.group(3)
                val floorNum = match.group(4)
                val middle = match.group(6)
                val middleNum = match.group(7)
                if(floorNum == null)
                    return@forEach
                if(floorBF == "B")
                    floorExpr.floorNum =  - floorNum.toInt()
                else
                    floorExpr.floorNum = floorNum.toInt()
                if(middle == null) {
                    floorExpr.isMiddle = false
                    floors.add(floorExpr)
                    floorNumSet.add(floorExpr.floorNum)
                    return@forEach
                }
                floorExpr.isMiddle = true
                if(middleNum == null)
                    floorExpr.middleNum = 1
                else
                    floorExpr.middleNum = middleNum.toInt()
                floors.add(floorExpr)
            }
//            if(match)
        }
        if(floors.size < 2){
            return list
        }
        val max = floors[0]
        val min = floors[floors.size - 1]
        for(i in min.floorNum..max.floorNum){
            if(i == 0)
                continue
            if(!floorNumSet.contains(i)){
                val floorModelView = FloorModelView()
                floorModelView.floorName = getFloorNameStr(i, null)
                floorModelView.note = "缺失楼层"
                list.add(floorModelView)
            }
        }
        return list.sortedWith(floorComparator).toMutableList()
    }

    /**
     * 获取楼层名的字符串
     */
    fun getFloorNameStr(floorNum : Int, middleNum : Int?) : String{
        val sb = StringBuilder()
        if(floorNum > 0)
            sb.append("F")
        else
            sb.append("B")
        sb.append(floorNum.absoluteValue)
        if(middleNum == null)
            return sb.toString()
        sb.append("M")
        sb.append(middleNum)
        return sb.toString()
    }
}