package com.cr.pages

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.cr.adapter.CrPageAdapter
import com.cr.adapter.SettingAdapter
import com.cr.cruav.CrApplication
import com.cr.cruav.R
import com.cr.data.CrUtil
import com.cr.dialog.DialogNormal
import com.cr.event.BarAction
import com.cr.event.EventFragmentBarAction
import com.cr.models.CompletionModel
import com.cr.models.ICompletion
import com.cr.models.SettingAction
import dji.v5.common.callback.CommonCallbacks
import dji.v5.common.error.IDJIError
import dji.v5.manager.account.LoginState
import dji.v5.manager.account.UserAccountManager

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/4/10 17:45
 * 描述：设置管理页面
 */
class FragmentSet : CrNavigationFragment() {
    // define: 2023/4/11 定义变量
    private var adapter:CrPageAdapter? = null

    // define: 2023/4/11 定义页面
    private var pageMain:FragmentSetMain? = null   // define: 2023/9/12 主页面
    private var pageSetIpAndCom:FragmentSetIpAndCom? = null    // define: 2023/9/12 设置Ip和端口页面
    private var pageDownloadData:FragmentSetDataDownload? = null   // define: 2023/9/12 下载数据页面
    private var pageSimulator:FragmentSimulator?= null   // define: 2023/9/12 模拟器页面
    private var pageAirLineManager:FragmentAirLineManager?=null  // define: 2023/9/19 航线管理器页面

    // define: 2023/4/11 定义控件
    private var viewPager: ViewPager2?=null
    /**
     * 创建视图
     * @param inflater LayoutInflater 视图管理器
     * @param container ViewGroup? 视图组
     * @param savedInstanceState Bundle?
     * @return View?
     */
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // todo: 2023/4/11 设置动画方向
        setAnimationDirection(AnimationDirection.RIGHT)
        self = this
        mainView = inflater.inflate(R.layout.frag_set,null)
        // todo: 2023/4/10 设置导航栏
        setBar(R.id.nv)
        // todo: 2023/4/11 挂载控件
        joinControls()
        // todo: 2023/4/11 初始化页面
        initPages()
        return mainView
    }

    /**
     * 初始化导航栏
     */
    private fun initBar(){
        nvBar?.crSetTitle(R.string.nv_title_set)
        nvBar?.crSetVisible(backIsVisible = false, dismissIsVisible = true)
        showPage(pageMain!!)
    }

    /**
     * 初始化页面
     */
    private fun initPages(){
        adapter = CrPageAdapter(this.requireActivity())
        // todo: 2023/4/11 初始化主页面
        pageMain = FragmentSetMain()
        pageMain?.setCallback(mainListener)
        adapter?.addFragment(pageMain!!)

        // todo: 2023/4/11 初始化设置Ip和Com页面
        pageSetIpAndCom = FragmentSetIpAndCom()
        pageSetIpAndCom?.setAnimationDirection(AnimationDirection.RIGHT)
        adapter?.addFragment(pageSetIpAndCom!!)

        // todo: 2023/4/11 初始化数据下载页面
        pageDownloadData = FragmentSetDataDownload()
        adapter?.addFragment(pageDownloadData!!)

        // todo: 2023/9/19 初始化航线管理器页面
        pageAirLineManager = FragmentAirLineManager()
        pageAirLineManager?.setAnimationDirection(AnimationDirection.RIGHT)
        adapter?.addFragment(pageAirLineManager!!)

        // todo: 2023/8/15 初始化模拟器页面
        pageSimulator = FragmentSimulator()
        pageSimulator?.setAnimationDirection(AnimationDirection.RIGHT)
        adapter?.addFragment(pageSimulator!!)



        // todo: 2023/4/11 设置监听
        viewPager?.adapter = adapter

        // todo: 2023/4/11 初始化导航栏和页面
        initBar()
    }

    /**
     * 显示页面
     * @param fragment CrFragment
     */
    private fun showPage(fragment: CrNavigationFragment){
        var fragments = adapter?.getFragments()
        for(i in 0 until fragments!!.size){
            if(fragments?.get(i) == fragment){
                fragment.nvBar?.visibility = View.GONE
                viewPager?.currentItem = i
//                fragment?.initPage()
                break
            }
        }
    }

    /**
     * 菜单点击监听
     */
    private var mainListener =  object:SettingAdapter.SettingListener{
        // todo: 2023/4/11 动作监听
        override fun onAction(action: SettingAction) {
            when(action){
                SettingAction.SA_SET_IP_COM->{
                    showPage(pageSetIpAndCom!!)
                    nvBar?.crSetVisible(backIsVisible = true, dismissIsVisible = false)
                    nvBar?.crSetTitle(R.string.nv_title_set_ip_and_com)
                }
                SettingAction.SA_DOWNLOAD_DATA->{
                    showPage(pageDownloadData!!)
                    nvBar?.crSetVisible(backIsVisible = true, dismissIsVisible = false)
                    nvBar?.crSetTitle(R.string.nv_title_download)
                }
                SettingAction.SA_DJI_LOGIN->{
                    // todo: 2023/8/15 登录大疆账号
                    setLoginDjiUserAccount()
                }
                SettingAction.SA_SIMULATOR->{
                    // todo: 2023/8/15 大疆模拟器页面
                    showPage(pageSimulator!!)
                    nvBar?.crSetVisible(backIsVisible = true, dismissIsVisible = false)
                    nvBar?.crSetTitle(R.string.nv_title_simulator)
                }
                SettingAction.SA_AIR_LINE_MANAGER->{
                    // todo: 2023/9/19 航线管理器
                    showPage(pageAirLineManager!!)
                    nvBar?.crSetVisible(backIsVisible = true, dismissIsVisible = false)
                    nvBar?.crSetTitle(R.string.nv_title_air_line)
                }
            }
        }

        // todo: 2023/4/11 开关监听
        override fun onSwitch(action: SettingAction, isChecked: Boolean) {

        }

    }

    /**
     * 设置登录大疆账号
     */
    private fun setLoginDjiUserAccount(){
        // todo: 2023/8/15 获取大疆账号
        var loginUser = UserAccountManager.getInstance().loginInfo
        if(loginUser.loginState == LoginState.LOGGED_IN){
            var message = "当前登录账号[${loginUser.account}],是否重新登录？"
            showConfirm(message, arrayOf("重新登录","取消"),object:ICompletion<String>{
                override fun onCompletion(completion: CompletionModel<String>) {
                    if(completion.isSuccess == true){
                        // todo: 2023/8/15 先退出当前账号
                        UserAccountManager.getInstance().logOutDJIUserAccount(object:CommonCallbacks.CompletionCallback{
                            // todo: 2023/8/15 退出成功
                            override fun onSuccess() {
                                loginDjiUserAccount()
                            }

                            // todo: 2023/8/15 退出失败
                            override fun onFailure(error: IDJIError) {
                                showError("退出失败:${error.description()}")
                            }

                        })
                    }
                }
            })
        }else{
            // todo: 2023/8/15 如果是未登录或登录已过期 则直接调出登录页面
            loginDjiUserAccount()
        }
    }

    /**
     * 登录大疆账号
     */
    private fun loginDjiUserAccount(){
        // todo: 2023/8/14 登录大疆账号
        UserAccountManager.getInstance().logInDJIUserAccount(self!!.activity,false,null)
    }

    /**
     * 挂载控件
     */
    override fun joinControls() {
        viewPager = mainView?.findViewById(R.id.frag_set_pages)
        viewPager?.isUserInputEnabled = false
    }

    /**
     * 重写关闭事件
     */
    override fun dismiss() {
        CrApplication.getEventBus().post(EventFragmentBarAction(self!!,BarAction.ACTION_DISMISS))
    }

    /**
     * 重写回退事件
     */
    override fun onGotoBack() {
        initBar()
    }
}