package com.casic.common.detector.gd.utils

import com.casic.common.detector.gd.base.BaseApplication
import com.casic.common.detector.gd.bean.MarkerLocalBean
import com.casic.common.detector.gd.bean.TaskLocalBean
import com.casic.common.detector.gd.bean.TaskMarkerLocalBean
import com.casic.common.detector.gd.greendao.MarkerLocalBeanDao
import com.casic.common.detector.gd.greendao.TaskLocalBeanDao
import com.casic.common.detector.gd.greendao.TaskMarkerLocalBeanDao
import com.casic.common.detector.gd.model.TaskDetailLocalModel
import com.casic.common.detector.gd.model.TaskModel

class DataBaseManager private constructor() {
    companion object {
        //Kotlin委托模式双重锁单例
        val get by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            DataBaseManager()
        }
    }

    private var taskLocalBeanDao = BaseApplication.get().getDaoSession().taskLocalBeanDao
    private var taskMarkerLocalBeanDao =
        BaseApplication.get().getDaoSession().taskMarkerLocalBeanDao

    fun saveTaskInLocale(task: TaskModel.MessageModel) {
        val bean = TaskLocalBean()
        bean.id = task.id.toLong()
        bean.taskCode = task.taskCode
        bean.description = task.description
        bean.createTime = task.deployDate
        bean.status = task.status
        bean.createUserName = task.creatorName
        if (task.beginDate == null) {
            bean.startTime = ""
        }
        if (task.endDate == null) {
            bean.endTime = ""
        }
        bean.isFreeTask = "0"
        if (!bean.isExist()) {
            taskLocalBeanDao.insert(bean)
        }
    }

    fun saveTaskInLocale(bean: TaskLocalBean) {
        if (!bean.isExist()) {
            taskLocalBeanDao.insert(bean)
        }
    }

    private fun TaskLocalBean.isExist(): Boolean {
        val result = taskLocalBeanDao.queryBuilder().where(
            TaskLocalBeanDao.Properties.Id.eq(this.id)
        ).list()
        return !result.isNullOrEmpty()
    }

    fun saveTaskMarkerInLocale(
        taskId: Int, taskCode: String, marker: TaskModel.MessageModel.TaskDetailInfosModel
    ) {
        val bean = TaskMarkerLocalBean()
        bean.id = marker.id.toLong()
        bean.taskId = taskId.toString()
        bean.taskCode = taskCode
        bean.markerId = marker.markerIdReal
        bean.lng = marker.longitude
        bean.lat = marker.latitude
        bean.isDetected = "0"
        bean.detectedTime = ""
        if (!bean.isExist()) {
            taskMarkerLocalBeanDao.insert(bean)
        }
    }

    private fun TaskMarkerLocalBean.isExist(): Boolean {
        val result = taskMarkerLocalBeanDao.queryBuilder().where(
            TaskMarkerLocalBeanDao.Properties.Id.eq(this.id)
        ).list()
        return !result.isNullOrEmpty()
    }

    fun loadLocalTask(): ArrayList<TaskDetailLocalModel> {
        val result = ArrayList<TaskDetailLocalModel>()

        val tasks = taskLocalBeanDao.loadAll()
        tasks.forEach {
            val model = TaskDetailLocalModel()
            model.taskId = it.id.toString()
            model.taskCode = it.taskCode
            model.description = it.description
            model.createTime = it.createTime
            model.status = it.status
            model.createUserName = it.createUserName
            model.isFreeTask = it.isFreeTask

            val markers = ArrayList<TaskDetailLocalModel.TaskMarkerLocalModel>()
            if (it.isFreeTask == "0") {
                //非自由巡检才有Marker
                val markerLocalBeans = taskMarkerLocalBeanDao.queryBuilder().where(
                    TaskMarkerLocalBeanDao.Properties.TaskId.eq(it.id),
                    TaskMarkerLocalBeanDao.Properties.TaskCode.eq(it.taskCode)
                ).list()
                markerLocalBeans.forEach { marker ->
                    val localModel = TaskDetailLocalModel.TaskMarkerLocalModel()
                    localModel.markerId = marker.markerId
                    localModel.lng = marker.lng
                    localModel.lat = marker.lat
                    localModel.isDetected = marker.isDetected
                    localModel.detectedTime = marker.detectedTime

                    markers.add(localModel)
                }
            }
            model.markerModels = markers
            result.add(model)
        }
        return result
    }

    fun deleteLocalTaskById(taskId: String, taskCode: String) {
        val task = taskLocalBeanDao.queryBuilder().where(
            TaskLocalBeanDao.Properties.Id.eq(taskId),
            TaskLocalBeanDao.Properties.TaskCode.eq(taskCode)
        ).list().firstOrNull() ?: return
        taskLocalBeanDao.delete(task)

        //删除此任务关联的Marker。非自由巡检才有Marker
        if (task.isFreeTask == "0") {
            val markers = taskMarkerLocalBeanDao.queryBuilder()
                .where(
                    TaskMarkerLocalBeanDao.Properties.TaskId.eq(taskId),
                    TaskMarkerLocalBeanDao.Properties.TaskCode.eq(taskCode)
                ).list()
            markers.forEach {
                taskMarkerLocalBeanDao.delete(it)
            }
        }
    }

    fun queryTaskMarkerById(
        taskId: String, taskCode: String, markerId: String, state: String
    ): TaskMarkerLocalBean? {
        return taskMarkerLocalBeanDao.queryBuilder()
            .where(
                TaskMarkerLocalBeanDao.Properties.TaskId.eq(taskId),
                TaskMarkerLocalBeanDao.Properties.TaskCode.eq(taskCode),
                TaskMarkerLocalBeanDao.Properties.MarkerId.eq(markerId),
                TaskMarkerLocalBeanDao.Properties.IsDetected.eq(state)
            ).list().firstOrNull()
    }

    fun updateLocalTaskMarkerState(marker: TaskMarkerLocalBean) {
        marker.isDetected = "1"
        taskMarkerLocalBeanDao.update(marker)
    }

    fun queryMarkerByState(state: String): List<TaskMarkerLocalBean> {
        return taskMarkerLocalBeanDao.queryBuilder()
            .where(TaskMarkerLocalBeanDao.Properties.IsDetected.eq(state))
            .list()
    }

    private var markerLocalBeanDao = BaseApplication.get().getDaoSession().markerLocalBeanDao

    fun clearMarkers() {
        markerLocalBeanDao.deleteAll()
    }

    fun saveMarkerInLocale(bean: MarkerLocalBean) {
        markerLocalBeanDao.insert(bean)
    }

    fun loadMarkers(): MutableList<MarkerLocalBean> {
        return markerLocalBeanDao.loadAll()
    }

    fun loadMarkersByCondition(selectedItem: String, value: String?): MutableList<MarkerLocalBean> {
        val property = when (selectedItem) {
            LocaleConstant.SPINNER_ARRAY[0] -> MarkerLocalBeanDao.Properties.MarkerId
            LocaleConstant.SPINNER_ARRAY[1] -> MarkerLocalBeanDao.Properties.Area
            LocaleConstant.SPINNER_ARRAY[2] -> MarkerLocalBeanDao.Properties.Line
            LocaleConstant.SPINNER_ARRAY[3] -> MarkerLocalBeanDao.Properties.Road
            LocaleConstant.SPINNER_ARRAY[4] -> MarkerLocalBeanDao.Properties.Owner
            LocaleConstant.SPINNER_ARRAY[5] -> MarkerLocalBeanDao.Properties.InstallationDept
            LocaleConstant.SPINNER_ARRAY[6] -> MarkerLocalBeanDao.Properties.UpdateTime
            else -> MarkerLocalBeanDao.Properties.Remark
        }
        return if (value == null) {
            markerLocalBeanDao.queryBuilder().where(property.isNotNull).list()
        } else {
            markerLocalBeanDao.queryBuilder().where(property.eq(value)).list()
        }
    }

    fun queryMarkerById(markerId: String): List<MarkerLocalBean> {
        return markerLocalBeanDao.queryBuilder()
            .where(MarkerLocalBeanDao.Properties.MarkerId.eq(markerId))
            .list()
    }
}