package com.cr.cruav

import android.annotation.SuppressLint
import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.fragment.app.commit
import com.cr.common.DataManager
import com.cr.data.CrConfig
import com.cr.data.CrUtil
import com.cr.event.*
import com.cr.map.CaseModel
import com.cr.map.EventMap
import com.cr.map.MapAction
import com.cr.models.AircraftWaypointModel
import com.cr.pages.*
import com.cr.viewmodel.*
import com.cr.pages.FragmentInformationBar
import com.squareup.otto.Subscribe
import dji.v5.common.error.IDJIError
import dji.v5.common.register.DJISDKInitEvent
import dji.v5.manager.interfaces.SDKManagerCallback
import kotlinx.android.synthetic.main.av_main.*
import kotlinx.android.synthetic.main.tools_top.*
import java.util.*

class AvMain : CrActivity(), View.OnClickListener {
    // todo: 2023/9/14 视图模型绑定
    private val msdkRegisterVm: CrMSDKRegisterVM by viewModels() // define: 2023/3/10 将App视图绑定到模型
    private val msdkInfoVm: CrMSDKInfoVM by viewModels()  // define: 2023/3/10 将MSDK视图绑定到模型
    private val remoteControlVm: CrRemoteControlVM by viewModels() // define: 2023/3/10 将遥控器视图绑定到模型
    private val flightControlVm: CrFlightControlVM by viewModels() // define: 2023/3/10 将飞行器视图绑定到模型
    private val liveStreamVm: CrLiveStreamVM by viewModels() // define: 2023/9/13 将直播视图绑定到模型
    private val linkVm: CrLinkVM by viewModels() // define: 2023/3/14 将链路视图绑定到模型
    private val cameraVm:CrCameraVM by viewModels() // define: 2023/8/2 绑定相机视图到模型

    // todo: 2023/9/14 Fragment定义
    private var fragmentTopInfo: FragmentTopInfo? = null // define: 2023/3/13 顶部视图容器
    private var fragmentFPV: FragmentFPV? = null // define: 2023/3/13 图传容器
    private var fragmentMap: FragmentMap? = null // define: 2023/3/14 地图容器
    private var fragmentSet: FragmentSet? = null // define: 2023/4/11 初始化设置页面
    private var fragmentLayerControl: FragmentLayerControl? = null // define: 2023/4/14 图层控制页面
    private var fragmentDoodle: FragmentDoodle? = null // define: 2023/4/17 涂鸦页面
    private var fragmentMark: FragmentMark? = null  // define: 2023/4/18 标志页面
    private var fragmentTools: FragmentTools? = null  // define: 2023/4/21 工具页面
    private var fragmentCaseTools: FragmentCaseTools? = null  // define: 2023/6/9 案件图斑编辑页面
    private var fragmentUploadCase: FragmentUploadCase? = null // define: 2023/6/15 案件上传页面
    private var fragmentDynamicInfo:FragmentDynamicInfo?= null  // define: 2023/7/29 大疆动态信息
    private var fragmentLiveStream:FragmentLiveStream?= null  // define: 2023/9/13 直播页面
    private var fragmentInformationBar:FragmentInformationBar?= null // define: 2023/9/19 信息栏

    // todo: 2023/9/14 变量定义
    private var isFpvSmallWindow: Boolean = true  // define: 2023/3/14 图传窗口是不是小窗口

    /**
     * 入口函数
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // todo: 2023/9/13 开启屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        setContentView(R.layout.av_main);
        // todo: 2023/4/11 挂载控件
        joinControls()
        // todo: 2023/4/11 初始化
//        init()
        // todo: 2023/4/3 订阅事件
        CrApplication.getEventBus().register(this)
        // todo: 2023/8/14 此语句非常重要 需要创建一个静态的Context，且该上下文可以用于创建对话框
        // todo: 2023/8/14 如果AvMain窗体关闭，则在窗体中继续执行该方法
        CrApplication.setContext(this)
    }

    /**
     * 挂载控件
     */
    override fun joinControls() {
        // todo: 2023/4/11 设置点击事件
        tools_set.setOnClickListener(this)
        tools_layer.setOnClickListener(this)
        tools_doodle.setOnClickListener(this)
        tools_mark.setOnClickListener(this)
        tools_wx.setOnClickListener(this)
        tools_tools.setOnClickListener(this)
        tools_case_tools.setOnClickListener(this)
        tools_append_point_from_map.setOnClickListener(this)
        tools_case_local.setOnClickListener(this)
        tools_case_net.setOnClickListener(this)
        tools_live.setOnClickListener(this)
    }

    /**
     * 初始化
     */
    private fun init() {
        // todo: 2023/3/11 注册App到DJI
        registerApp();
        // todo: 2023/3/11 初始化视图
        initView()
        // todo: 2023/4/10 初始化页面
        initPage()
    }

    /**
     * 初始化页面
     */
    private fun initPage() {
        // todo: 2023/4/10 显示登录账号
        fragmentInformationBar!!.setUserAccount(CrConfig.user?.userName!!)
        // todo: 2023/4/11 初始化设置页面
        fragmentSet = FragmentSet()
        fragmentSet?.let {
            addFragment(it, R.id.av_frm_right_panel)
            hideFragment(it)
        }
        // todo: 2023/4/14 初始化图层控制页面
        fragmentLayerControl = FragmentLayerControl()
        fragmentLayerControl?.let {
            addFragment(it, R.id.av_frm_right_panel)
            hideFragment(it)
        }
        // todo: 2023/4/17 初始化涂鸦操作页面
        fragmentDoodle = FragmentDoodle()
        fragmentDoodle?.setListener(doodleListener)
        fragmentDoodle?.let {
            addFragment(it, R.id.av_frm_left_smart_panel)
            hideFragment(it)
        }
        // todo: 2023/4/18 初始化标志页面
        fragmentMark = FragmentMark()
        fragmentMark?.setListener(markListener)
        fragmentMark?.let {
            addFragment(it, R.id.av_frm_left_big_panel)
            hideFragment(it)
        }
        // todo: 2023/4/21 初始化工具页面
        fragmentTools = FragmentTools()
        fragmentTools?.let {
            it.setListener(toolsListener)
            addFragment(it, R.id.av_frm_left_smart_panel)
            hideFragment(it)
        }
        // todo: 2023/6/9 初始化案件图斑编辑页面
        fragmentCaseTools = FragmentCaseTools()
        fragmentCaseTools?.let {
            it.setListener(caseToolsListener)
            addFragment(it, R.id.av_frm_left_smart_panel)
            hideFragment(it)
        }
        // todo: 2023/6/15 初始化案件上传页面
        fragmentUploadCase = FragmentUploadCase()
        fragmentUploadCase?.let {
            addFragment(it, R.id.av_frm_center_panel)
            hideFragment(it)
        }
        // todo: 2023/9/13 初始化直播页面
        fragmentLiveStream = FragmentLiveStream()
        fragmentLiveStream?.let {
            addFragment(it,R.id.av_frm_right_panel)
            hideFragment(it)
        }
    }

    /**
     * 初始化视图
     */
    @SuppressLint("SuspiciousIndentation")
    private fun initView() {
        // todo: 2023/3/10 加入大疆顶部视图
        fragmentTopInfo = FragmentTopInfo()
        supportFragmentManager.commit {
            replace(R.id.av_fragment_top, fragmentTopInfo!!)
        }
        // todo: 2023/3/10 加入图传视图
        fragmentFPV = FragmentFPV()
        fragmentFPV?.listener = object : FragmentFPV.FPVListener {
            // todo: 2023/3/13 切换图传窗口
            override fun triggerWindow() {
                CrUtil.print("切换图传窗口")
                av_fragment_fpv.removeAllViews()
                av_fragment_map.removeAllViews()
                if (isFpvSmallWindow) {
                    isFpvSmallWindow = false
                    av_fragment_map.addView(fragmentFPV!!.view)
                    av_fragment_fpv.addView(fragmentMap!!.view)
                } else {
                    isFpvSmallWindow = true
                    av_fragment_map.addView(fragmentMap!!.view)
                    av_fragment_fpv.addView(fragmentFPV!!.view)
                }
            }
        }
        supportFragmentManager.commit {
            replace(R.id.av_fragment_fpv, fragmentFPV!!)
        }
        // todo: 2023/3/14 加入地图视图
        fragmentMap = FragmentMap()
        fragmentMap?.crSetEventListener(mapEventListener)
        supportFragmentManager.commit {
            replace(R.id.av_fragment_map, fragmentMap!!)
        }
        // todo: 2023/7/29 加入大疆动态信息视图
        fragmentDynamicInfo = FragmentDynamicInfo()
        supportFragmentManager.commit {
            replace(R.id.av_fragment_dynamic_info,fragmentDynamicInfo!!)
        }
        // todo: 2023/9/19 加入信息栏视
        fragmentInformationBar = FragmentInformationBar()
        supportFragmentManager.commit {
            replace(R.id.av_information_bar,fragmentInformationBar!!)
        }
    }

    /**
     * 注册App SDK
     */
    private fun registerApp() {
        msdkRegisterVm.registerApp(this, object : SDKManagerCallback {
            // todo: 2023/3/13 App注册成功回调
            override fun onRegisterSuccess() {
                CrUtil.print("App注册成功")
                // todo: 2023/3/9 MSDK初始化监听
                msdkInfoVm.initListener()
                // todo: 2023/3/9 遥控器初始化监听
                remoteControlVm.initListener()
                // todo: 2023/3/9 初始化飞行器监听
                flightControlVm.initListener()
                // todo: 2023/3/14 初始化链路监听
                linkVm.initListener()
                // todo: 2023/8/2 相机监听初始化
                cameraVm.initListener()
                // todo: 2023/9/13 订阅直播信息
                initObserve()
            }

            // todo: 2023/3/13 App注册失败回调
            override fun onRegisterFailure(error: IDJIError?) {
                CrUtil.print("App注册失败" + error.toString())
            }

            // todo: 2023/9/14 产品失连
            override fun onProductDisconnect(productId: Int) {

            }

            // todo: 2023/9/14 产品连接
            override fun onProductConnect(productId: Int) {

            }

            // todo: 2023/9/14 产品变化
            override fun onProductChanged(productId: Int) {

            }

            // todo: 2023/9/14 产品变化过程
            override fun onInitProcess(event: DJISDKInitEvent?, totalProcess: Int) {

            }

            // todo: 2023/9/14 基础数据下载进程
            override fun onDatabaseDownloadProgress(current: Long, total: Long) {

            }
        })
    }

    /**
     * 初始化订阅
     */
    private fun initObserve(){
        mainHandler.post{
            // todo: 2023/9/13 订阅直播信息
            liveStreamVm.streamStatusInfo.observe(this){
                it?.let {
                    CrApplication.getEventBus().post(EventCommon(CrCommonAction.UPDATE_LIVE_INFO,it))
                }
            }
        }
    }

    /**
     * 视图点击事件
     * @param view View
     */
    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.tools_set -> {
                // todo: 2023/8/14 设置工具
                showFragment(fragmentSet!!)
            }
            R.id.tools_layer -> {
                // todo: 2023/8/14 图层控制
                showFragment(fragmentLayerControl!!)
                fragmentLayerControl?.initPage()
            }
            R.id.tools_doodle -> {
                // todo: 2023/8/14 涂鸦工具
                showFragment(fragmentDoodle!!)
            }
            R.id.tools_mark -> {
                // todo: 2023/8/14 标志工具
                showFragment(fragmentMark!!)
            }
            R.id.tools_tools -> {
                // todo: 2023/8/14 工具箱
                showFragment(fragmentTools!!)
            }
            R.id.tools_case_tools -> {
                // todo: 2023/8/14 案件工具箱
                showFragment(fragmentCaseTools!!)
            }
            R.id.tools_append_point_from_map -> {
                // todo: 2023/8/14 添加案件点
                CrApplication.getEventBus().post(EventMap(MapAction.MapTapAddWaypoint))
            }
            R.id.tools_wx -> {
                // todo: 2023/8/14 微信分享
                CrApplication.getEventBus().post(EventMap(MapAction.MapTapCaseWxAndUpload))
            }
            R.id.tools_case_local->{
                // todo: 2023/8/14 本地案件查询
            }
            R.id.tools_case_net->{
                // todo: 2023/8/14 网络案件查询
                // todo: 2023/9/18 保存航点测试
                var model = AircraftWaypointModel(CrConfig.user!!.userId!!)
                model.longitude = "118.35678"
                model.latitude = "35.67890"
                model.altitude = "14.567"
                model.angle = "216.6"
                val resId = DataManager.saveAircraftLine(model)
                CrUtil.print("存储Id:${resId}")
            }
            R.id.tools_live->{
                // todo: 2023/9/13 打开直播设置
                showFragment(fragmentLiveStream!!)
            }
        }
    }

    /**
     * 涂鸦页面操作监听
     */
    private val doodleListener = object : FragmentDoodle.OnOperationListener {
        // todo: 2023/4/17 开启绘制
        override fun onStartDraw() {
            CrApplication.getEventBus().post(EventMap(MapAction.MapTapDrawDoodle))
        }

        // todo: 2023/4/17 停止绘制
        override fun onStopDraw() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventStopSketch))
        }

        // todo: 2023/4/17 开启选择
        override fun onSelect() {
            CrApplication.getEventBus().post(EventMap(MapAction.MapTapSelectDoodle))
        }

        // todo: 2023/4/17 关闭选择
        override fun onStopSelect() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventStopTouch))
        }

        // todo: 2023/4/17 清除
        override fun onClear() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventDoodleClear))
        }

        // todo: 2023/4/17 保存
        override fun onSave() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventDoodleSave))
        }

        // todo: 2023/4/17 删除全部
        override fun onRemove() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventDoodleRemove))
        }

        // todo: 2023/4/17 移除选择
        override fun onDelete() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventDoodleDelete))
        }
    }

    /**
     * 标志页面操作监听
     */
    private val markListener = object : FragmentMark.OnOperationListener {
        // todo: 2023/4/17 开启绘制
        override fun onStartDraw() {
            CrApplication.getEventBus().post(EventMap(MapAction.MapTapAppendMark, fragmentMark))
        }

        // todo: 2023/4/17 停止绘制
        override fun onStopDraw() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventStopSketch))
        }

        // todo: 2023/4/17 开启选择
        override fun onSelect() {
            CrApplication.getEventBus().post(EventMap(MapAction.MapTapSelectMark))
        }

        // todo: 2023/4/17 关闭选择
        override fun onStopSelect() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventStopTouch))
        }

        // todo: 2023/4/17 清除
        override fun onClear() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventMarkClear))
        }

        // todo: 2023/4/17 保存
        override fun onSave() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventMarkSave))
        }

        // todo: 2023/4/17 删除全部
        override fun onRemove() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventMarkRemove))
        }

        // todo: 2023/4/17 移除选择
        override fun onDelete() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventMarkDelete))
        }
    }

    /**
     * 工具监听
     */
    private var toolsListener = object : FragmentTools.OnOperationListener {
        // todo: 2023/4/21 长度测量
        override fun onMeasureLength() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventSurveyLength))
        }

        // todo: 2023/4/21 面积测量
        override fun onMeasureArea() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventSurveyArea))
        }

        // todo: 2023/4/21 清除测量内容
        override fun onMeasureClear() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventSurveyClear))
        }

        // todo: 2023/4/21 获取经纬度位置
        override fun onGetLocation() {
            CrApplication.getEventBus().post(EventMap(MapAction.MapTapGetLocation))
        }

        // todo: 2023/4/21 地图定位
        override fun onToLocation() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventInputLocationToMap))
        }

    }

    /**
     * 案件图斑编辑工具页面监听
     */
    private val caseToolsListener = object : FragmentCaseTools.OnOperationListener {
        // todo: 2023/6/9 开启绘制案件图斑
        override fun onStartDraw() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventCaseDrawPolygon))
        }

        // todo: 2023/6/9 结束绘制
        override fun onStopDraw() {

        }

        // todo: 2023/6/9 保存
        override fun onSave() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventCaseSavePolygon))
        }

        // todo: 2023/6/9 删除
        override fun onRemove() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventCaseRemovePolygon))
        }

        // todo: 2023/6/9 回退
        override fun onUndo() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventCaseDrawUndo))
        }

        // todo: 2023/6/9 重置
        override fun onReset() {
            CrApplication.getEventBus().post(EventMap(MapAction.EventCaseDrawReset))
        }

        // todo: 2023/6/9 移动违建点
        override fun onMoveCasePoint() {
            CrApplication.getEventBus().post(EventMap(MapAction.MapTapStartMoveWaypoing))
        }

        // todo: 2023/6/13 删除违建点
        override fun onRemoveCasePoint() {
            CrApplication.getEventBus().post(EventMap(MapAction.MapTapDeleteWaypoint))
        }
    }

    /**
     * 地图事件监听
     */
    private val mapEventListener = object :FragmentMap.EventListener{
        // todo: 2023/6/15 案件上传
        override fun onCaseUpdate(selCase: CaseModel) {
            fragmentUploadCase?.crSetJoinCase(selCase)
            showFragment(fragmentUploadCase!!)
        }
    }

    /**
     * 销毁
     */
    override fun onDestroy() {
        CrApplication.getEventBus().unregister(this)
        // todo: 2023/9/13 关闭屏幕常亮
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        // todo: 2023/9/15 释放MSDK
        msdkRegisterVm.destroyMSDK()
        super.onDestroy()
    }

    /**
     * App可见
     */
    override fun onResume() {
        super.onResume()
        init()
    }

    override fun onPause() {
        super.onPause()
//        callExitSystem()
    }

    /**
     * 重启系统
     */
    private fun callExitSystem() {
        // TODO: 2023/7/25 获取包名
        var packageName = CrApplication.getContext().packageName
        // TODO: 2023/7/25 获取重启后页面的类名
        var className = AvLogin::class.java.name
        // TODO: 2023/7/25 创建一个Intent来重启App
        var intent = Intent(Intent.ACTION_MAIN)
        intent.addCategory(Intent.CATEGORY_LAUNCHER)
        var cn = ComponentName(packageName,className)
        intent.component = cn
        // TODO: 2023/7/25 FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TOP即重启应用程序的标识
        // TODO: 2023/7/25 FLAG_ACTIVITY_NEW_TASK告诉系统新的任务需要新的任务栈，FLAG_ACTIVITY_CLEAR_TOP告诉系统清空任务栈
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
        CrApplication.getContext().startActivity(intent);
        // TODO: 2023/7/25 结束当前窗体
        finish();
    }

    /**
     * 订阅Fragment管理事件
     * @param event EventFragmentBarAction
     */
    @Subscribe
    fun onFragmentBar(event: EventFragmentBarAction) {
        if(event.barAction == BarAction.ACTION_DISMISS){
            hideFragment(event.fragment!!)
        }
    }

    /**
     * 订阅视频YUV存储事件
     * @param event EventCommon<String>
     */
    @Subscribe
    fun onVideoYUVSave(event:EventCommon<String>){
        if(event.action == CrCommonAction.VIDEO_SAVE_YUV_FAILURE){
            CrApplication.getEventBus().post(EventCommon<String>(CrCommonAction.SHOW_MESSAGE,event.param))
        }else if(event.action == CrCommonAction.VIDEO_SAVE_YUV_SUCCESS){
            CrApplication.getEventBus().post(EventCommon<String>(CrCommonAction.SHOW_MESSAGE,event.param))
        }
    }
}
