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 androidx.transition.Visibility
import com.cr.common.CrCameraInfo
import com.cr.cruav.CrApplication
import com.cr.cruav.R
import com.cr.data.CrUtil
import com.cr.data.DEFAULT_STR
import com.cr.event.CrCommonAction
import com.cr.event.EventCommon
import com.cr.viewmodel.CrCameraVM
import com.cr.viewmodel.CrFlightControlVM
import com.cr.widget.CrSpeedWidget
import com.squareup.otto.Subscribe
import dji.sdk.keyvalue.key.CameraKey
import dji.sdk.keyvalue.key.KeyTools
import dji.sdk.keyvalue.value.common.EmptyMsg
import dji.v5.common.callback.CommonCallbacks
import dji.v5.common.error.IDJIError
import dji.v5.manager.account.LoginInfo
import dji.v5.manager.account.LoginInfoUpdateListener
import dji.v5.manager.account.LoginState
import dji.v5.manager.account.UserAccountManager
import org.w3c.dom.Text

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/7/29 16:30
 * 描述：大疆动态数据页面
 */
class FragmentDynamicInfo : CrFragment(), View.OnClickListener {
    // todo: 2023/8/2 绑定模型
    private val cameraVm: CrCameraVM by activityViewModels()
    private val flightControlVm: CrFlightControlVM by activityViewModels()

    // todo: 2023/8/2 组件定义
    private var lblCameraISO: TextView? = null // define: 2023/8/2 ISO值
    private var lblCameraSpeed: TextView? = null // define: 2023/8/2 快门速度
    private var lblCameraFocal: TextView? = null // define: 2023/8/2 相机焦距
    private var lblCameraEv: TextView? = null // define: 2023/8/2 补偿值
    private var lblSDPhotoCount: TextView? = null // define: 2023/8/2 SD卡中可存储的照片数量
    private var lblSDVideoTime: TextView? = null // define: 2023/8/2 SD卡中可以录制的视频时间
    private var lblDJILogin: TextView? = null // define: 2023/8/2 是否登录大疆账户

    private var flagPhoto: TextView? = null  // define: 2023/8/3 照片模式标志
    private var flagVideo: TextView? = null // define: 2023/8/3 视频模式标志

    private var lblMessage: TextView? = null // define: 2023/8/7 消息
    private var lblAltitude: TextView? = null // define: 2023/8/15 相对航高
    private var lblTakeoffAltitude: TextView? = null  // define: 2023/8/15 起飞海拔
    private var lblDistanceByHome: TextView? = null // define: 2023/8/15 返航距离
    private var lblAltitudeByHome: TextView? = null // define: 2023/8/15 返航高度

    private var speedX: CrSpeedWidget? = null  // define: 2023/8/16 x方向速度
    private var speedY: CrSpeedWidget? = null  // define: 2023/8/16 y方向速度
    private var speedZ: CrSpeedWidget? = null // define: 2023/8/16 z方向速度

    /**
     * 初始化
     * @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_dynamic_info, null)
        // todo: 2023/8/2 挂载控件
        joinControls()
        // todo: 2023/8/7 注册事件
        CrApplication.getEventBus().register(this)
        // todo: 2023/8/15 绑定大疆账号登录状态
        bindDjiUserAccountLogin()
        return mainView
    }

    /**
     * 覆写挂载控件
     */
    override fun joinControls() {
        super.joinControls()
        // todo: 2023/8/2 挂载控件
        mainView?.let {
            lblCameraISO = it.findViewById(R.id.camera_iso)
            lblCameraSpeed = it.findViewById(R.id.camera_speed)
            lblCameraFocal = it.findViewById(R.id.camera_focal)
            lblCameraEv = it.findViewById(R.id.camera_ev)

            lblSDPhotoCount = it.findViewById(R.id.sd_photo_count)
            lblSDVideoTime = it.findViewById(R.id.sd_video_time)

            lblDJILogin = it.findViewById(R.id.dji_login)

            // todo: 2023/8/3 挂载相机模式标志
            flagPhoto = it.findViewById(R.id.camera_model_photo)
            flagPhoto?.visibility = View.GONE
            flagVideo = it.findViewById(R.id.camera_model_video)
            flagVideo?.visibility = View.GONE

            // todo: 2023/8/7 挂载消息控件
            lblMessage = it.findViewById(R.id.lbl_message)

            // todo: 2023/8/15 挂载返航高度及相对航高
            lblAltitude = it.findViewById(R.id.lbl_altitude)
            lblTakeoffAltitude = it.findViewById(R.id.lbl_takeoff_altitude)
            lblDistanceByHome = it.findViewById(R.id.lbl_home_distance)
            lblAltitudeByHome = it.findViewById(R.id.lbl_home_altitude)

            // todo: 2023/8/16 挂载速度
            speedX = it.findViewById(R.id.speed_x)
            speedY = it.findViewById(R.id.speed_y)
            speedZ = it.findViewById(R.id.speed_z)

            speedX?.setProgressMax(30)
            speedY?.setProgressMax(30)
            speedZ?.setProgressMax(10)

            // todo: 2023/8/2 挂载事件
            lblSDPhotoCount?.setOnClickListener(this)
        }
    }

    /**
     * 生命周期
     * 后台转前台运行时调用
     */
    override fun onResume() {
        super.onResume()
        // todo: 2023/8/2 初始化订阅
        initObserver()
    }

    /**
     * 生命周期
     * 销毁
     */
    override fun onDestroy() {
        // todo: 2023/8/7 取消事件监听
        CrApplication.getEventBus().unregister(this)
        // todo: 2023/8/15 取消登录状态更新监听绑定
        UserAccountManager.getInstance().removeLoginInfoUpdateListener(djiUserAccountLoginListener)
        super.onDestroy()
    }

    /**
     * 初始化订阅
     */
    private fun initObserver() {
        // todo: 2023/8/2 订阅相机信息
        cameraVm.cameraInfo.observe(requireActivity()) {
            it?.let {
                // todo: 2023/8/4 相机基本参数
                lblCameraISO?.text = it.iso
                lblCameraSpeed?.text = it.speed
                lblCameraFocal?.text = it.focal
                lblCameraEv?.text = it.ev

                // todo: 2023/8/4 可拍照数量或可录制视频时长
                lblSDPhotoCount?.text = it.photoCount
                lblSDVideoTime?.text = it.videoTime

                // todo: 2023/8/4 相机模式
                when (it.cameraModel) {
                    CrCameraInfo.CrCameraMode.NON -> {
                        flagVideo?.visibility = View.GONE
                        flagPhoto?.visibility = View.GONE
                    }
                    CrCameraInfo.CrCameraMode.PHOTO -> {
                        flagVideo?.visibility = View.GONE
                        flagPhoto?.visibility = View.VISIBLE
                    }
                    CrCameraInfo.CrCameraMode.VIDEO -> {
                        flagVideo?.visibility = View.VISIBLE
                        flagPhoto?.visibility = View.GONE
                    }
                }
            }
        }
        // todo: 2023/8/15 订阅飞行器信息
        flightControlVm.flightControlInfo.observe(requireActivity()) {
            it?.let {
                lblAltitude?.text = it.altitudeStr
                lblTakeoffAltitude?.text = it.takeoffAltitudeStr
                lblAltitudeByHome?.text = it.homeAltitudeStr
                lblDistanceByHome?.text = it.homeDistanceStr

                // todo: 2023/8/16 更新速度
                speedX?.setProgressValue(it.speedX.toInt())
                speedY?.setProgressValue(it.speedY.toInt())
                speedZ?.setProgressValue(it.speedZ.toInt())
            }
        }
    }

    /**
     * 绑定大疆登录
     */
    private fun bindDjiUserAccountLogin() {
        var loginState = UserAccountManager.getInstance().loginInfo.loginState
        // todo: 2023/8/15 更新登录信息
        updateDjiUserAccountLoginInfo(loginState)
        // todo: 2023/8/15 绑定监听
        UserAccountManager.getInstance().addLoginInfoUpdateListener(djiUserAccountLoginListener)
    }

    /**
     * 更新大疆账户登录状态信息
     * @param state LoginState 登录状态
     */
    private fun updateDjiUserAccountLoginInfo(state: LoginState) {
        mainHandler.post {
            if (state == LoginState.LOGGED_IN) {
                lblDJILogin?.text = "已登录"
            } else {
                lblDJILogin?.text = DEFAULT_STR
            }
        }
    }

    /**
     * 大疆账户登录变更监听
     */
    private val djiUserAccountLoginListener = LoginInfoUpdateListener {
        // todo: 2023/8/15 更新登录信息
        updateDjiUserAccountLoginInfo(it.loginState)
    }

    /**
     * 视图点击事件
     * @param view View
     */
    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.sd_photo_count -> {
                CrUtil.print("拍照")
                dji.v5.manager.KeyManager.getInstance()
                    .performAction(KeyTools.createKey(CameraKey.KeyStartShootPhoto),
                        object : CommonCallbacks.CompletionCallbackWithParam<EmptyMsg> {
                            override fun onSuccess(t: EmptyMsg?) {
                                CrUtil.print("拍照成功${t.toString()}")
                            }

                            override fun onFailure(error: IDJIError) {
                                CrUtil.print("拍照失败${error.description()}}")
                            }
                        })
            }
        }
    }

    @Subscribe
    fun onMessage(event: EventCommon<String>) {
        event?.let {
            if (it.action == CrCommonAction.SHOW_MESSAGE) {
                lblMessage?.text = event.param
            }
        }
    }
}
