package com.persagy.legend.services

import com.persagy.legend.models.entities.LegendPipe
import com.sybotan.database.SFilter
import com.sybotan.mybatis.SMybatisDao
import com.sybotan.service.SObjectService
import com.sybotan.service.models.enums.SResponseType
import com.sybotan.service.models.responses.SCreateResponse
import java.util.*

/**
 * @author  zy
 */
object LegendPipeService : SObjectService<LegendPipe>(SMybatisDao(LegendPipe::class.java)) {
    /**
     * 保存
     *
     * @param legend     图标图例对象
     * @return 返回结果
     */
    fun save(legend: LegendPipe): SCreateResponse<LegendPipe> {
        /** 返回对象 */
        val sCreateResponse = SCreateResponse<LegendPipe>()
        return try {
            /** id 为空赋值 */
            if (legend.id.isNullOrEmpty()) {
                legend.id = UUID.randomUUID().toString().replace("-", "")
            }

            /** 插入数据 */
            val insert = LegendPipeService.replace(legend)
            if (!insert){
                sCreateResponse.result = SResponseType.failure
                return sCreateResponse
            }

            /** 状态 */
            /** 清空图例相关的状态 */
            LegendStateService.delete(SFilter.eq("legendId", legend.id!!))
            /** 插入图例相关的状态 */
            if (!legend.stateList.isNullOrEmpty()) {
                val stateList = legend.stateList
                /** 遍历状态 */
                for (state in stateList!!){
                    /** 图例 id */
                    state!!.legendId = legend.id
                    if (state.id.isNullOrEmpty()) {
                        state.id = UUID.randomUUID().toString().replace("-", "")
                    }
                    /** 插入数据 */
                    LegendStateService.replace(state)
                }
            }
            /** 对象列表 */
            sCreateResponse.entityList = arrayListOf(legend)
            /** 标志 */
            sCreateResponse.result = SResponseType.success
            /** 对象 */
            sCreateResponse
        } catch (e: Exception) {
            e.printStackTrace()
            sCreateResponse.result = SResponseType.failure
            sCreateResponse
        }
    }
}