package com.cr.common

import com.cr.data.CrUtil
import com.cr.map.CaseModel
import com.cr.map.LayerConfigModel
import com.cr.map.LayerModel
import com.cr.models.*

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/4/3 10:59
 * 描述：数据操作类
 */
class DataManager {
    // todo: 2023/4/3 静态方法及属性封装
    companion object {
        private const val TABLE_AIR_LINE: String = "AIRLINE"  // define: 2023/9/19 航线表
        private const val TABLE_IMAGE_EDIT:String = "INAGEEDIT"  // define: 2023/9/28 照片编辑表
        private const val TABLE_WAY_IMAGES:String = "WAYIMAGES"  // define: 2023/9/28 照片存储表

        /**
         * 获取网络服务连接信息
         * @return IPAndComModel
         */
        fun getNetworkLinkInfo(): IPAndComModel {
            var sql: String = "SELECT * FROM ipcom where CHECKED = '1'"
            var res: List<HashMap<String, String>> = DatabaseBaseManager.getInstance().query(sql)
            var map = res[0]
            map.let {
                return IPAndComModel.initByMap(it)
            }
        }

        /**
         * 获取网络连接列表
         * @return List<IPAndComModel>
         */
        fun getNetworkLinks(): List<IPAndComModel> {
            var res = mutableListOf<IPAndComModel>()
            var sql: String = "SELECT * FROM ipcom order by id"
            var qList: List<HashMap<String, String>> = DatabaseBaseManager.getInstance().query(sql)
            for (map in qList) {
                var item = IPAndComModel.initByMap(map)
                res.add(item)
            }
            return res
        }

        /**
         * 查询指定的连接是否存在
         * @param queryItem IPAndComModel 连接信息
         * @return Boolean
         */
        fun queryNetworkLink(queryItem: IPAndComModel): Boolean {
            var sql =
                "select * from ipcom where ip='${queryItem.ip}' and com='${queryItem.com}' and server='${queryItem.serverName}'"
            var qList: List<HashMap<String, String>> = DatabaseBaseManager.getInstance().query(sql)
            return qList != null && qList.isNotEmpty()
        }

        /**
         * 更新网络连接选择状态
         * @param item IPAndComModel 网络连接
         * @param isChecked Boolean 选中状态
         * @return Boolean
         */
        fun updateNetworkChecked(item: IPAndComModel, isChecked: Boolean): Boolean {
            var where = "ip='${item.ip}' and com='${item.com}' and server='${item.serverName}'"
            var checkedValue = if (isChecked) "1" else "0"
            var values = hashMapOf("checked" to checkedValue)
            return DatabaseBaseManager.getInstance().update("ipcom", values, where)
        }

        /**
         * 插入新的网络连接
         * @param item IPAndComModel 网络连接
         * @return Boolean
         */
        fun insertNetworkLink(item: IPAndComModel): Boolean {
            var values = hashMapOf(
                "checked" to "1",
                "ip" to item.ip,
                "com" to item.com,
                "server" to item.serverName
            )
            return DatabaseBaseManager.getInstance().insert("ipcom", values)
        }

        /**
         * 取消所有连接的选中状态
         * @return Boolean
         */
        fun cancelNetworkChecked(): Boolean {
            var values = hashMapOf("checked" to "0")
            return DatabaseBaseManager.getInstance().update("ipcom", values, "")
        }

        /**
         * 存储账号和密码
         * @param userName String 账号
         * @param password String 密码
         * @return Boolean
         */
        fun saveUser(userName: String, password: String): Boolean {
            // todo: 2023/4/6 由于只保留一条数据 保存前先删除
            deleteUser()
            // todo: 2023/4/6 定义插入数据
            var userMap: HashMap<String, String> = hashMapOf()
            userMap["name"] = userName
            userMap["password"] = password
            userMap["issave"] = "1"
            return DatabaseBaseManager.getInstance().insert("user", userMap)
        }

        /**
         * 删除账号和密码
         * @return Boolean
         */
        fun deleteUser(): Boolean {
            return DatabaseBaseManager.getInstance().delete("user", "")
        }

        /**
         * 获取存储的账号信息
         * @return UserModel
         */
        fun getUser(): UserModel {
            var user = UserModel()
            var sql = "SELECT * FROM user"
            var qList: List<HashMap<String, String>> = DatabaseBaseManager.getInstance().query(sql)
            if (qList != null && qList.isNotEmpty()) {
                user.userId = qList[0]["name"]
                user.userPwd = qList[0]["password"]
            }
            return user
        }

        /**
         * 获取切片图层配置
         * @return MutableList<LayerModel>
         */
        fun getTileLayerConfig(): MutableList<LayerModel> {
            // todo: 2023/4/13 返回的图层
            var layers: MutableList<LayerModel> = mutableListOf()
            var sql = "select * from TileLayerConfig order by id"
            var qList: List<HashMap<String, String>> =
                DatabaseAppConfigManager.getInstance().query(sql)
            if (qList != null && qList.isNotEmpty()) {
                for (map in qList) {
                    var lyrName = map["lyrname"]
                    var lyrIsVisible = map["isvisible"].equals("1")
                    var lyrUrl = map["lyrurl"]?.replace("/tile/", "")
                    var model: LayerModel = LayerModel(lyrName!!, lyrIsVisible, lyrUrl!!)
                    layers.add(model)
                }
            }
            // todo: 2023/4/13 返回
            return layers
        }

        /**
         * 获取矢量数据配置
         * @return MutableList<LayerConfigModel>
         */
        fun getVectorLayerConfig(): MutableList<LayerConfigModel> {
            // todo: 2023/4/13 定义数据集
            var layerList: MutableList<LayerConfigModel> = mutableListOf()
            var sql = "SELECT * FROM BaseLayerConfig"
            var qList: List<HashMap<String, String>> =
                DatabaseAppConfigManager.getInstance().query(sql)
            if (qList != null && qList.isNotEmpty()) {
                for (map in qList) {
                    var model = LayerConfigModel(
                        map["name"]!!,
                        map["lyrname"]!!,
                        map["idx"]!!.toInt(),
                        map["isvisible"].equals("1")
                    )
                    layerList.add(model)
                }
            }
            // todo: 2023/4/13 返回数据集合
            return layerList
        }

        /**
         * 添加案件点照片
         * @param model CaseModel 案件点模型
         * @param callback iCompletion? 完成回调
         */
        fun appAppendImages(model: CaseModel, callback: ICompletion<String>?) {
            // todo: 2023/6/19 先查询是否已经存在
            var SQL = String.format(
                "select * from WAYIMAGES where wayid='%s' and imgname='%s'",
                model.name,
                model.imgName
            )
            var queryList = DatabaseAppUAVManager.getInstance().query(SQL)
            if (queryList.isNotEmpty()) {
                if (callback != null) callback?.onCompletion(CompletionModel(false, "该照片已经存储！"))
            } else {
                var values = HashMap<String, String>()
                values["wayid"] = model!!.name!!
                values["imgname"] = model!!.imgName!!
                values["lat"] = model!!.latitude!!.toString()
                values["lng"] = model!!.longitude!!.toString()
                values["alt"] = model!!.altitude!!.toString()
                values["ang"] = model!!.angle!!.toString()
                values["isdown"] = "0"
                values["date"] = model!!.date!!.toString()
                var res = DatabaseAppUAVManager.getInstance().insert("WAYIMAGES", values)
                if (res) {
                    if (callback != null) callback?.onCompletion(CompletionModel(true, ""))
                } else {
                    if (callback != null) callback?.onCompletion(CompletionModel(false, "该照片已经存储！"))
                }
            }
        }

        /**
         * 替换照片名称
         * @param caseId String 案件Id
         * @param oldName String 旧名称
         * @param newName String 新名称
         * @param callback ICompletion<String> 回调
         */
        fun replaceImageName(caseId:String, oldName:String, newName: String, callback: ICompletion<String>){
            CrUtil.print("caseId = $caseId 名称=$oldName")
            // todo: 2023/9/28 先查询是否存在
            val strWhere = String.format("wayid = '%s' and (imgname = '%s' or imgname='%s')",caseId,oldName,newName)
            val sql = String.format("select * from %s where %s", TABLE_WAY_IMAGES,strWhere)
            val qList = DatabaseAppUAVManager.getInstance().query(sql)
            if(qList.isNotEmpty()){
                // todo: 2023/9/28 更新
                var valueMap = HashMap<String,String>()
                valueMap["imgname"] = newName
                val isOk = DatabaseAppUAVManager.getInstance().update(TABLE_WAY_IMAGES,valueMap,strWhere)
                if(isOk){
                    callback.onCompletion(CompletionModel(true,"","更新成功！"))
                }else{
                    callback.onCompletion(CompletionModel(false,"","更新失败！"))
                }
            }else{
                callback.onCompletion(CompletionModel(false,"","照片未曾编辑过！"))
            }
        }

        /**
         * 根据案件Id查询案件照片的详细信息
         * @param caseId String 案件Id
         * @param callback iCompletion<List<String>> 回调
         */
        fun appQueryImages(caseId: String, callback: ICompletion<List<String>>) {
            var querySQL = String.format("select * from WAYIMAGES where wayid='%s'", caseId)
            var queryList = DatabaseAppUAVManager.getInstance().query(querySQL)
            if (queryList.isNotEmpty()) {
                var resList = mutableListOf<String>()
                for (map in queryList) {
                    resList.add(map["imgname"].toString())
                }
                if (callback != null) callback.onCompletion(CompletionModel(true, resList))
            } else {
                if (callback != null) callback.onCompletion(
                    CompletionModel(
                        false,
                        mutableListOf("未查询到任何信息！")
                    )
                )
            }
        }

        /**
         * 存储案件提报快捷描述信息
         * @param dataList List<SelModel> 快捷信息列表
         * @return Boolean 存储是否成功
         */
        fun saveCaseSubmitDescription(dataList: List<SelModel>): Boolean {
            var isReturn = true;
            DatabaseAppUAVManager.getInstance().delete("CASEKjInput", "")
            for (model in dataList) {
                var value: HashMap<String, String> = hashMapOf()
                value["kjid"] = model.code!!
                value["kjnr"] = model.name!!
                isReturn =
                    isReturn && DatabaseAppUAVManager.getInstance().insert("CASEKjInput", value)
            }
            return isReturn
        }

        /**
         * 获取案件提报快捷描述信息
         * @return List<SelModel> 快捷描述信息列表
         */
        fun getCaseSubmitDescription(): List<SelModel> {
            var resList = mutableListOf<SelModel>()
            var SQL = "select * from CASEKjInput order by kjid;"
            var qList = DatabaseAppUAVManager.getInstance().query(SQL)
            for (map in qList) {
                resList.add(SelModel(map["kjid"]!!, map["kjnr"]!!))
            }
            return resList
        }

        /**
         * 案件类型本地化
         * @param dataList List<SelModel> 案件类型列表
         * @return Boolean
         */
        fun saveCaseType(dataList: List<SelModel>): Boolean {
            var isReturn = true;
            DatabaseAppUAVManager.getInstance().delete("CASEType", "")
            for (model in dataList) {
                var value: HashMap<String, String> = hashMapOf()
                value["lxid"] = model.code!!
                value["lxname"] = model.name!!
                isReturn = isReturn && DatabaseAppUAVManager.getInstance().insert("CASEType", value)
            }
            return isReturn
        }

        /**
         * 获取案件类型快捷描述信息
         * @return List<SelModel> 类型信息列表
         */
        fun getCaseType(): List<SelModel> {
            var resList = mutableListOf<SelModel>()
            var SQL = "select * from CASEType order by lxid;"
            var qList = DatabaseAppUAVManager.getInstance().query(SQL)
            for (map in qList) {
                resList.add(SelModel(map["lxid"]!!, map["lxname"]!!))
            }
            return resList
        }

        /**
         * 保存航线点
         * @param model CrAircraftLineModel 航线点模型
         * @return Int 返回-1表示失败 其他表示保存的Id标识
         */
        fun saveAircraftLine(model: AircraftWaypointModel): Int {
            var resInt: Int = -1
            var values: HashMap<String, String> = hashMapOf()
            values["date"] = model.createDate
            values["lng"] = model.longitude
            values["lat"] = model.latitude
            values["alt"] = model.altitude
            values["angle"] = model.angle
            values["type"] = model.type
            values["flag"] = model.userId
            var isInsert = DatabaseAppUAVManager.getInstance().insert(TABLE_AIR_LINE, values)
            if (isInsert) {
                var sql = String.format(
                    "SELECT max(ID) maxid FROM %s where FLAG='%s'",
                    TABLE_AIR_LINE, model.userId
                );
                var qList = DatabaseAppUAVManager.getInstance().query(sql)
                resInt = qList[0]["maxid"]!!.toInt()
            }
            return resInt
        }

        /**
         * 查询指定用户的航线统计信息
         * @param userId String 用户Id
         * @return AircraftLineCountModel 统计信息
         */
        fun queryAircraftStatisticsInfo(userId: String): AircraftLineCountModel {
            var resModel = AircraftLineCountModel()
            // todo: 2023/9/19 查询航点总数
            var sql = String.format(
                "select count(*) count from %s where flag='%s'",
                TABLE_AIR_LINE,
                userId
            )
            var qList = DatabaseAppUAVManager.getInstance().query(sql)
            resModel.waypointAllCount = qList[0]["count"]!!.toInt()
            // todo: 2023/9/19 查询待传航点数
            sql = String.format(
                "select count(*) count from %s where flag='%s' and type='0'",
                TABLE_AIR_LINE, userId
            )
            qList = DatabaseAppUAVManager.getInstance().query(sql)
            resModel.waitUploadWaypointCount = qList[0]["count"]!!.toInt()
            // todo: 2023/9/19 查询已上传航点数
            sql = String.format(
                "select count(*) count from %s where flag='%s' and type='1'",
                TABLE_AIR_LINE, userId
            )
            qList = DatabaseAppUAVManager.getInstance().query(sql)
            resModel.yesUploadWaypointCount = qList[0]["count"]!!.toInt()
            // todo: 2023/9/19 查询统计信息
            sql = String.format(
                "SELECT date,COUNT(*) count from (select date(date) date from %s WHERE FLAG = '%s' and TYPE = '0') GROUP BY date",
                TABLE_AIR_LINE, userId
            )
            qList = DatabaseAppUAVManager.getInstance().query(sql)
            for (data in qList) {
                resModel.appendWaypointDetailInfo(data["date"]!!, data["count"]!!.toInt())
            }
            return resModel
        }

        /**
         * 查询所有待上传航点数据
         * @param userId String 用户Id
         * @return List<AircraftWaypointModel>
         */
        fun queryAllWaitUploadWaypoint(userId:String):List<AircraftWaypointModel>{
            val sql = String.format("select * from %s where flag='%s' and type='0'", TABLE_AIR_LINE,userId)
            val qList = DatabaseAppUAVManager.getInstance().query(sql)
            var resModel = mutableListOf<AircraftWaypointModel>()
            for (map in qList){
                var model = AircraftWaypointModel(userId)
                model.ptId = map["id"]!!
                model.longitude = map["lng"]!!
                model.latitude = map["lat"]!!
                model.altitude = map["alt"]!!
                model.angle = map["angle"]!!
                resModel.add(model)
            }
            return resModel
        }

        /**
         * 更新指定航点状态
         * @param userId String 用户Id
         * @param ptList List<AircraftWaypointModel> 航点集合
         * @return Boolean
         */
        fun updateWaypointState(userId: String,ptList:List<AircraftWaypointModel>):Boolean{
            // todo: 2023/9/20 更新的Id集合
            var arrayInt = mutableListOf<Int>()
            for (pt in ptList){
                arrayInt.add(pt.ptId.toInt())
            }
            // todo: 2023/9/20 组合条件
            val strWhere = "flag = '${userId}' and id in (${arrayInt.joinToString(",")})"
            // todo: 2023/9/20 更新内容
            var valueMap = HashMap<String,String>()
            valueMap["type"] = "1"
            // todo: 2023/9/20 更新
            return DatabaseAppUAVManager.getInstance().update(TABLE_AIR_LINE,valueMap,strWhere)
        }

        /**
         * 删除航点信息
         * @param userId String 用户Id
         * @return Boolean 删除是否成功
         */
        fun deleteAircraftPoint(userId: String): Boolean {
            val sqlWhere = String.format("flag='%s'", userId)
            return DatabaseAppUAVManager.getInstance().delete(TABLE_AIR_LINE,sqlWhere)
        }

        /**
         * 插入编辑照片数据
         * @param oldName String 原照片
         * @param newName String 新照片
         * @return Boolean 是否成功
         */
        fun appendEditImage(oldName:String,newName:String):Boolean{
            // todo: 2023/9/28 先查询是否存在
            val strWhere = String.format("oldimage = '%s'",oldName)
            val sql = String.format("select * from %s where %s", TABLE_IMAGE_EDIT,strWhere)
            val qlist = DatabaseAppUAVManager.getInstance().query(sql)
            return if(qlist.isNotEmpty()){
                // todo: 2023/9/28 需要更新
                var valueMap = HashMap<String,String>()
                valueMap["newimage"] = newName
                DatabaseAppUAVManager.getInstance().update(TABLE_IMAGE_EDIT,valueMap,strWhere)
            }else{
                var valueMap = HashMap<String,String>()
                valueMap["newimage"] = newName
                valueMap["oldimage"] = oldName
                DatabaseAppUAVManager.getInstance().insert(TABLE_IMAGE_EDIT,valueMap)
            }
        }

        /**
         * 查询编辑后照片对应的源照片
         * @param newName String 源照片
         * @return String? 编辑后的照片名字
         */
        fun queryEditImage(newName: String):String?{
            // todo: 2023/9/28 先查询是否存在
            val strWhere = String.format("newimage = '%s'",newName)
            val sql = String.format("select * from %s where %s", TABLE_IMAGE_EDIT,strWhere)
            val qlist = DatabaseAppUAVManager.getInstance().query(sql)
            if(qlist.isNotEmpty()){
                return qlist[0]["oldimage"]
            }
            return null
        }
    }
}