using UnityEngine;
using UnityEngine.UI;
using SmartBowSDK;
using Newtonsoft.Json;

public class DemoStarter : MonoBehaviour
{
    [SerializeField] Toggle _DetectingMacToggle;
    [SerializeField] Button _btnConnect;
    [SerializeField] Button _btnClearDeviceInfo;
    [SerializeField] Text textMacAddress;
    [SerializeField] Text textBattery;
    [SerializeField] Button _btnCalibrateGyr;
    [SerializeField] Button _btnCalibrateMag;
    [SerializeField] Button _btnResetAim;

    [SerializeField] Button _btnStartRotationSensor;
    [SerializeField] Button _btnStopRotationSensor;
    [SerializeField] Button _btnStartShootingSensor;
    [SerializeField] Button _btnStopShootingSensor;

    [SerializeField] InputField _inputFieldGameID;
    [SerializeField] InputField _inputFieldChannelID;
    [SerializeField] InputField _inputFieldUsername;
    [SerializeField] InputField _inputFieldPassword;
    [SerializeField] Button _btnLogin;
    [SerializeField] Button _btnLogout;
    [SerializeField] Button _btnGetUserInfo;
    [SerializeField] Image _imgAvatar;
    [SerializeField] Text _textNickname;
    [SerializeField] Text _textGender;


    //数据存储标识
    string userTags = "test";
    //建立的设备信息id.
    int deviceId = 1;
    void Awake()
    {
        _btnConnect.onClick.AddListener(OnClick_Connect);
        _btnClearDeviceInfo.onClick.AddListener(OnClick_ClearDeviceInfo);

        _btnCalibrateGyr.onClick.AddListener(OnClick_CalibrateGyr);
        _btnCalibrateMag.onClick.AddListener(OnClick_CalibrateMag);
        _btnResetAim.onClick.AddListener(OnClick_ResetAim);

        _btnStartRotationSensor.onClick.AddListener(OnClick_StartRotationSensor);
        _btnStopRotationSensor.onClick.AddListener(OnClick_StopRotationSensor);
        _btnStartShootingSensor.onClick.AddListener(OnClick_StartShootingSensor);
        _btnStopShootingSensor.onClick.AddListener(OnClick_StopShootingSensor);

        _btnLogin.onClick.AddListener(OnClick_Login);
        _btnLogout.onClick.AddListener(OnClick_Logout);
        _btnGetUserInfo.onClick.AddListener(OnClick_GetUserInfo);

        UpdateLoginUI(0);
    }

    void Start()
    {
        SmartBowHelper.GetInstance().OnBluetoothStatusChanged += OnBluetoothStatusChanged;
        SmartBowHelper.GetInstance().OnBluetoothError += OnBluetoothError;
        SmartBowHelper.GetInstance().OnBluetoothModuleInited += OnBluetoothModuleInited;
        SmartBowHelper.GetInstance().OnRotationUpdate += OnRotationUpdate;
        SmartBowHelper.GetInstance().OnShooting += OnShooting;
        SmartBowHelper.GetInstance().OnFunctionKeyPress += OnFunctionKeyPress;
        SmartBowHelper.GetInstance().OnFunctionKeyLongPress += OnFunctionKeyLongPress;
    }

    void OnBluetoothStatusChanged(BluetoothStatusEnum oldStatus, BluetoothStatusEnum newStatus)
    {
        
    }

    void OnBluetoothError(BluetoothError error, string message)
    {
        Debug.Log("OnBluetoothError:" + error);
        if (error == BluetoothError.ScanNotFoundTargetDevice)
        {
            TipText.Show("连接失败，未发现目标设备！");
            return;
        }
        TipText.Show(message);
    }

    void OnBluetoothModuleInited()
    {
        SmartBowHelper.GetInstance().StartRotationSensor();
        SmartBowHelper.GetInstance().StartShootingSensor();
    }

    void OnRotationUpdate(Quaternion rotation)
    {
        Bow.Instance.transform.localRotation = rotation;
    }

    void OnShooting(float speed)
    {
        Bow.Instance.Shoot();
    }

    void OnFunctionKeyPress()
    {
        Debug.Log("功能键短按");
        OnClick_ResetAim();
    }

    void OnFunctionKeyLongPress()
    {
        Debug.Log("功能键长按");
    }

    void Update()
    {
        //更新显示蓝牙状态
        BluetoothStatusEnum bluetoothStatus = SmartBowHelper.GetInstance().GetBluetoothStatus();
        Text btnConnectText = _btnConnect.GetComponentInChildren<Text>();
        if (bluetoothStatus == BluetoothStatusEnum.None) btnConnectText.text = "<color=blue>未连接</color>（点击连接）";
        if (bluetoothStatus == BluetoothStatusEnum.Connecting) btnConnectText.text = "<color=#FF670D>连接中</color>";
        if (bluetoothStatus == BluetoothStatusEnum.Connected)
        {
            if (SmartBowHelper.GetInstance().IsBluetoothModuleInited()) btnConnectText.text = "<color=green>已连接</color>（点击断开）";
            else btnConnectText.text = "<color=green>已连接</color><color=blue>（正在初始化）</color>";
        }
        //更新显示电量
        int battery = SmartBowHelper.GetInstance().GetBattery();
        textBattery.text = battery > 0 ? $"电量值:{battery}" : "未获得电量值";
        //更新显示Mac地址
        string macAddress = SmartBowHelper.GetInstance().GetMacAddress();
        textMacAddress.text = macAddress != null ? $"Mac地址:{macAddress}" : "未获得Mac地址";
        //更新显示陀螺仪校准文本
        UpdateCalibrateGyrText();
        //更新显示地磁计校准文本
        UpdateCalibrateMagText();
    }

    public void OnClick_Connect()
    {
        if (SmartBowHelper.GetInstance().GetBluetoothStatus() == BluetoothStatusEnum.Connecting) return;
        if (SmartBowHelper.GetInstance().GetBluetoothStatus() == BluetoothStatusEnum.None)
        {
            //默认需要检测mac，bRecreateDeviceInfo:false.如不需要：设置bRecreateDeviceInfo:true;
            bool bRecreateDeviceInfo = _DetectingMacToggle.isOn ? false : true;
            SmartBowHelper.GetInstance().Connect(userTags, deviceId, bRecreateDeviceInfo);
            return;
        }
        if (SmartBowHelper.GetInstance().GetBluetoothStatus() == BluetoothStatusEnum.Connected)
        {
            SmartBowHelper.GetInstance().Disconnect();
            return;
        }
    }

    public void OnClick_ClearDeviceInfo() {
        SmartBowHelper.GetInstance().ClearDeviceInfo(userTags , deviceId);
    }

    public void OnClick_ResetAim()
    {
        SmartBowHelper.GetInstance().ResetAim();
    }

    public void OnClick_CalibrateGyr()
    {
        if (SmartBowHelper.GetInstance().IsGyrCalibrating())
        {
            SmartBowHelper.GetInstance().StopGyrCalibration();
        }
        else
        {
            SmartBowHelper.GetInstance().StartGyrCalibration();
        }
    }

    void UpdateCalibrateGyrText()
    {
        Text text = _btnCalibrateGyr.GetComponentInChildren<Text>();
        int progress = (int)(SmartBowHelper.GetInstance().GetGyrProgress() * 100);
        string act = SmartBowHelper.GetInstance().IsGyrCalibrating() ? "停止" : "开始";
        text.text = $"点击{act}陀螺仪校准({progress}%)";
    }

    float _clickCalibrateMagTime = -100;
    public void OnClick_CalibrateMag()
    {
        _clickCalibrateMagTime = Time.realtimeSinceStartup;
        SmartBowHelper.GetInstance().StartMagCalibration();
    }

    void UpdateCalibrateMagText()
    {
        Text text = _btnCalibrateMag.GetComponentInChildren<Text>();
        if (SmartBowHelper.GetInstance().IsMagCompleted())
        {
            text.text = $"<color=green>地磁计校准完成</color>(点击重置)";
        }
        else
        {
            string tip = Time.realtimeSinceStartup - _clickCalibrateMagTime < 2 ? "<color=#FF670D>已重置</color>" : "点击重置";
            text.text = $"<color=blue>地磁计自动校准中</color>({tip})";
        }
    }

    public void OnClick_StartRotationSensor()
    {
        bool success = SmartBowHelper.GetInstance().StartRotationSensor();
        if (!success) TipText.Show("开启九轴传感失败\n原因\n模块未连接或未初始化完成");
        else TipText.Show("开启九轴传感\n指令发送成功");
    }

    public void OnClick_StopRotationSensor()
    {
        bool success = SmartBowHelper.GetInstance().StopRotationSensor();
        if (!success) TipText.Show("停止九轴传感失败\n原因\n模块未连接或未初始化完成");
        else TipText.Show("停止九轴传感\n指令发送成功");
    }

    public void OnClick_StartShootingSensor()
    {
        bool success = SmartBowHelper.GetInstance().StartShootingSensor();
        if (!success) TipText.Show("开启射箭传感失败\n原因\n模块未连接或未初始化完成");
        else TipText.Show("开启射箭传感\n指令发送成功");
    }

    public void OnClick_StopShootingSensor()
    {
        bool success = SmartBowHelper.GetInstance().StopShootingSensor();
        if (!success) TipText.Show("停止射箭传感失败\n原因\n模块未连接或未初始化完成");
        else TipText.Show("停止射箭传感\n指令发送成功");
    }

    public void OnClick_Login()
    {
        if (string.IsNullOrWhiteSpace(_inputFieldUsername.text) || string.IsNullOrWhiteSpace(_inputFieldPassword.text))
        {
            TipText.Show("请输入账号密码");
            return;
        }
        SmartBowHelper.GetInstance().Login(
            _inputFieldGameID.text,
            _inputFieldChannelID.text,
            _inputFieldUsername.text,
            _inputFieldPassword.text,
            (res) =>
            {
                if (res.success)
                {
                    Debug.Log("登录成功");
                    UpdateLoginUI(1);
                }
                TipText.Show(res.message);
            });
    }

    public void OnClick_Logout()
    {
        SmartBowHelper.GetInstance().Logout((success) =>
        {
            if (success)
            {
                TipText.Show($"登出成功");
                UpdateLoginUI(0);
            }
            else TipText.Show($"登出失败");
        });
    }

    public void OnClick_GetUserInfo()
    {
        SmartBowHelper.GetInstance().GetUserInfo((res) =>
        {
            if (res.success)
            {
                Debug.Log("获取用户信息成功");
                UserInfo userInfo = res.userInfo;
                Debug.Log(JsonConvert.SerializeObject(userInfo));
                //渲染UI
                StartCoroutine(SmartBowNetwork.LoadSprite(userInfo.avatarUrl, (sprite) =>
                {
                    _imgAvatar.sprite = sprite;
                    _imgAvatar.enabled = true;
                }));
                _textNickname.text = userInfo.nickname;
                _textNickname.enabled = true;
                _textGender.text = userInfo.gender == 1 ? "男" : "女";
                _textGender.enabled = true;
            }
            TipText.Show(res.message);
        });
    }

    void UpdateLoginUI(int step)
    {
        _inputFieldGameID.gameObject.SetActive(step == 0);
        _inputFieldChannelID.gameObject.SetActive(step == 0);
        _inputFieldUsername.gameObject.SetActive(step == 0);
        _inputFieldPassword.gameObject.SetActive(step == 0);
        _btnLogin.gameObject.SetActive(step == 0);
        _btnLogout.gameObject.SetActive(step == 1);
        _btnGetUserInfo.gameObject.SetActive(step == 1);
        _imgAvatar.gameObject.SetActive(step == 1);
        _textNickname.gameObject.SetActive(step == 1);
        _textGender.gameObject.SetActive(step == 1);
        _imgAvatar.enabled = false;
        _imgAvatar.sprite = null;
        _textNickname.enabled = false;
        _textGender.enabled = false;
    }
}
