package com.cr.pages

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.activityViewModels
import com.cr.common.CrInterfaceManager
import com.cr.common.CrJTMManager
import com.cr.common.DataManager
import com.cr.cruav.R
import com.cr.data.CrConfig
import com.cr.data.CrUtil
import com.cr.models.AircraftWaypointModel
import com.cr.models.CompletionModel
import com.cr.models.ICompletion
import com.cr.viewmodel.CrFlightControlVM

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/9/19 15:28
 * 描述：信息栏组件
 */
class FragmentInformationBar :CrFragment(){
    // todo: 2023/9/19 控件定义
    private var lblAccount:TextView?= null  // define: 2023/9/19 账号信息
    private var lblServer:TextView?= null // define: 2023/9/19 航线点上传信息

    // todo: 2023/9/19 绑定模型
    private val flightControlVm:CrFlightControlVM by activityViewModels()

    // todo: 2023/9/19 变量定义
    private var oldLongitude:Double = 0.0  // define: 2023/9/19 前一经度
    private var oldLatitude:Double = 0.0  // define: 2023/9/19 前一纬度
    private val IMPOSE_DIS:Double = 50.0  // define: 2023/9/19 限制距离
    private var countSave:Long = 0  // define: 2023/9/19 存储计数
    private var countUpdate:Long = 0  // define: 2023/9/19 上传计数

    private var userName:String?= null // define: 2023/9/20 登录的用户名称

    /**
     * 初始化
     * @param inflater LayoutInflater
     * @param container ViewGroup?
     * @param savedInstanceState Bundle?
     * @return View?
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        self = this
        mainView = inflater.inflate(R.layout.frag_infomation_bar,null)
        // todo: 2023/9/19 挂载控件
        joinControls()
        // todo: 2023/9/19 初始化页面
        initPage()
        return mainView
    }

    /**
     * 覆写挂载控件
     */
    override fun joinControls() {
        mainView?.let {
            lblAccount = it.findViewById(R.id.lbl_account)
            userName?.let {
                lblAccount?.text = userName
            }
            lblServer = it.findViewById(R.id.lbl_server)
        }
    }

    /**
     * 页面初始化
     */
    override fun initPage() {
        // todo: 2023/9/19 订阅
        mainHandler.post {
            flightControlVm.flightControlInfo.observe(requireActivity()){
                it?.let {
                    calculateAndSave(it.longitude,it.latitude,it.altitude + it.takeoffAltitude,it.yaw)
                }
            }
        }
        // todo: 2023/9/19 更新信息
        updateInfo()
    }

    /**
     * 计算并保存
     * @param longitude Double 经度
     * @param latitude Double 纬度
     * @param altitude Double 高度
     * @param angle Double 角度
     */
    private fun calculateAndSave(longitude:Double,latitude:Double,altitude:Double,angle:Double){
        // todo: 2023/9/26 0 不存储
        if(longitude < 10 || latitude < 10) return
        // todo: 2023/9/19 计算距离
        var dis = CrJTMManager.calculateDistance(longitude,latitude,oldLongitude,oldLatitude)
        if(dis>= IMPOSE_DIS){
            oldLongitude = longitude
            oldLatitude = latitude
            // todo: 2023/9/19 创建存储模型
            var saveModel = AircraftWaypointModel(CrConfig.user!!.userId!!)
            saveModel.longitude = String.format("%.6f",longitude)
            saveModel.latitude = String.format("%.6f",latitude)
            saveModel.altitude = String.format("%.2f",altitude)
            saveModel.angle = String.format("%.2f",angle)
            // todo: 2023/9/20 保存至数据库
            val ptId = DataManager.saveAircraftLine(saveModel)
            if(ptId != -1) {
                countSave++
                saveModel.ptId = "$ptId"
                // todo: 2023/9/20 上传数据
                var ptList = mutableListOf<AircraftWaypointModel>()
                ptList.add(saveModel)
                CrInterfaceManager.getInstance().uploadAirlineWaypointNoLoading(ptList,object:ICompletion<List<AircraftWaypointModel>>{
                    // todo: 2023/9/20 上传后回调
                    override fun onCompletion(completion: CompletionModel<List<AircraftWaypointModel>>) {
                        if(completion.isSuccess){
                            var isUpdate = DataManager.updateWaypointState(CrConfig.user!!.userId!!,completion.result!!)
                            CrUtil.print("更新${isUpdate}")
                            if(isUpdate){
                                countUpdate ++
                            }
                        }else{
                            CrUtil.print("航点上传失败！${completion.message}")
                        }
                        updateInfo()
                    }
                })
            }
        }
    }

    /**
     * 更新信息
     */
    private fun updateInfo(){
        mainHandler.post {
            lblServer?.text = String.format("%d - %d",countSave,countUpdate)
        }
    }

    /**
     * 设置显示账号
     * @param userAccount String 账号
     */
    fun setUserAccount(userAccount:String){
        this.userName = userAccount
        lblAccount?.text = userAccount
    }
}