package com.cr.common

import android.os.Handler
import android.os.Looper
import com.cr.cruav.CrApplication
import com.cr.data.CrUtil
import com.cr.dialog.DialogNormal
import com.cr.models.AircraftWaypointModel
import com.cr.models.CompletionModel
import com.cr.models.ICompletion
import com.cr.models.UserModel
import com.cr.network.NetManager
import com.cr.network.TCPDataTask
import org.json.JSONArray

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/9/20 09:04
 * 描述：接口管理（所有与服务器的交互均放置该管理类中，统一管理）
 */
class CrInterfaceManager {
    private var mainHandler = Handler(Looper.getMainLooper())

    /**
     * 单例必备
     */
    object InstanceHelper {
        var self = CrInterfaceManager()
    }

    /**
     * 初始化
     */
    init {
        this.mainHandler = Handler(Looper.getMainLooper())
    }

    /**
     * 静态方法集合
     */
    companion object {
        /**
         * 获取实例
         * @return CrInterfaceManager
         */
        fun getInstance() = InstanceHelper.self
    }

    /**
     * 获取API接口访问的URL地址
     * @param subUrl String 子URL地址
     * @return String 完整的URL地址
     */
    private fun getNetworkUrl(subUrl: String): String {
        return NetManager.getServerUrl(subUrl)
    }

    /**
     * 显示错误信息
     * @param error String 错误消息
     */
    private fun showError(error: String) {
        mainHandler.post {
            DialogNormal(CrApplication.getContext(), "错误", error).show()
        }
    }

    /**
     * 用户登录认证
     * @param user UserModel 登录账号
     * @param callback ICompletion<UserModel>? 回调
     */
    fun userLogin(user: UserModel, callback: ICompletion<UserModel>?) {
        TCPDataTask.getInstance().sendJSON(
            getNetworkUrl("appQueryUser"),
            user,
            object : TCPDataTask.IChangeCallback {
                // todo: 2023/4/10 成功
                override fun onSuccess(jsonArray: JSONArray) {
                    var resUser = UserModel.toModel(jsonArray.optString(0))
                    callback?.let { it.onCompletion(CompletionModel(true, resUser)) }
                }

                // todo: 2023/4/10 失败
                override fun onFailed(message: String) {
                    showError(message)
                }
            },"账号登录认证中..."
        )
    }

    /**
     * 上传航点数据
     * @param ptList List<AircraftWaypointModel>
     * @param callback ICompletion<List<AircraftWaypointModel>>?
     */
    fun uploadAirlineWaypoint(ptList:List<AircraftWaypointModel>,callback: ICompletion<List<AircraftWaypointModel>>?){
        // todo: 2023/9/20 组装JSON字符串
        var jsonData = JSONManager.transformToString(ptList)
        // todo: 2023/9/20 上传
        TCPDataTask.getInstance().sendJSON(
            getNetworkUrl("appSubmitPath"),
            jsonData,
            object : TCPDataTask.IChangeCallback {
                // todo: 2023/4/10 成功
                override fun onSuccess(jsonArray: JSONArray) {
                    var resList = mutableListOf<AircraftWaypointModel>()
                    for(index in 0 until jsonArray.length()){
                        resList.add(AircraftWaypointModel.toModel(jsonArray.optJSONObject(index).toString())!!)
                    }
                    callback?.let { it.onCompletion(CompletionModel(true, resList)) }
                }

                // todo: 2023/4/10 失败
                override fun onFailed(message: String) {
                    showError(message)
                }
            }, "航点数据上传中..."
        )
    }

    /**
     * 上传航点数据（不显示等待消息）
     * @param ptList List<AircraftWaypointModel>
     * @param callback ICompletion<List<AircraftWaypointModel>>?
     */
    fun uploadAirlineWaypointNoLoading(
        ptList:List<AircraftWaypointModel>,
        callback: ICompletion<List<AircraftWaypointModel>>?
    ){
        // todo: 2023/9/20 组装JSON字符串
        var jsonData = JSONManager.transformToString(ptList)
        // todo: 2023/9/20 上传
        TCPDataTask.getInstance().sendJSON(
            getNetworkUrl("appSubmitPath"),
            jsonData,
            object : TCPDataTask.IChangeCallback {
                // todo: 2023/4/10 成功
                override fun onSuccess(jsonArray: JSONArray) {
                    var resList = mutableListOf<AircraftWaypointModel>()
                    for(index in 0 until jsonArray.length()){
                        resList.add(AircraftWaypointModel.toModel(jsonArray.optJSONObject(index).toString())!!)
                    }
                    callback?.let { it.onCompletion(CompletionModel(true, resList)) }
                }

                // todo: 2023/4/10 失败
                override fun onFailed(message: String) {
                    callback?.let { it.onCompletion(CompletionModel(false,null,message)) }
                }
            }
        )
    }
}