package com.abbidot.tracker.ui.common

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.location.LocationManager
import android.provider.Settings
import com.abbidot.baselibrary.list.BaseRecyclerAdapter
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.DataBean
import com.abbidot.tracker.constant.ConstantInt
import com.abbidot.tracker.receiver.GPSMonitorReceiver
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.bluetooth.SRBleUtil
import com.baidu.mshield.x0.EngineImpl.mContext
import com.clj.fastble.BleManager
import com.hjq.permissions.XXPermissions
import com.hjq.permissions.permission.PermissionLists

/**
 *Created  by .yzq on 2024/6/12/012.
 * @link
 * @description:
 */
class PermissionsActivityCommon(activity: BaseActivity<*>) {

    private val mLocationManager =
        activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    private val mActivity = activity
    private var mGPSListenerReceiver: GPSMonitorReceiver? = null

    /**
     * 注册GPS开关广播
     */
    fun registerGpsReceiver() {
        if (null == mGPSListenerReceiver) {
            mGPSListenerReceiver = GPSMonitorReceiver(mLocationManager)
        }
        val intentFilter = IntentFilter()
        intentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION)
        // 注册广播
        mContext.registerReceiver(mGPSListenerReceiver!!, intentFilter)
    }

    fun unregisterGpsReceiver() {
        mGPSListenerReceiver?.let {
            mContext.unregisterReceiver(it)
        }
    }

    /**
     * 添加list数据
     */
    fun addListData(context: Context): MutableList<DataBean> {
        val list = mutableListOf<DataBean>()
        DataBean().apply {
            name = context.getString(R.string.txt_bluetooth_enabled)
            value = context.getString(R.string.txt_ble_permissions_tip)
            list.add(this)
        }
        DataBean().apply {
            name = context.getString(R.string.txt_location_enabled)
            value = context.getString(R.string.txt_location_permissions_tip)
            list.add(this)
        }
        DataBean().apply {
            name = context.getString(R.string.txt_receive_notice)
            value = context.getString(R.string.txt_notice_permissions_tip)
            list.add(this)
        }
        return list
    }

    /**
     * 更新选中的状态item
     */
    fun updateDataBeanSelectedItem(
        adapter: BaseRecyclerAdapter<*>, list: MutableList<DataBean>, position: Int
    ) {
        for (i in 0 until list.size) {
            val data = list[i]
            if (i == position) continue
            if (data.selected) {
                data.selected = false
                adapter.notifyItemChanged(i)
                break
            }
        }
        list[position].apply {
            selected = !selected
            if (state == ConstantInt.SpecialType) state = ConstantInt.Type0
        }
        adapter.notifyItemChanged(position)
    }

    /**
     * 更新权限状态
     */
    fun updatePermissionsState(adapter: BaseRecyclerAdapter<DataBean>, errorType: Int) {
        val list = adapter.getData()


        //检测蓝牙权限和蓝牙开关
        if (XXPermissions.isGrantedPermissions(
                mContext, mutableListOf(
                    PermissionLists.getBluetoothScanPermission(),
                    PermissionLists.getBluetoothConnectPermission()
                )
            ) && SRBleUtil.instance.isBleEnable(mContext)
        ) {
            list[0].state = ConstantInt.Type1
            list[0].selected = false
            adapter.notifyItemChanged(0)
        } else {
            if (list[0].state == ConstantInt.Type1) {
                list[0].state = errorType
                adapter.notifyItemChanged(0)
            }
        }
        mutableListOf(
            PermissionLists.getAccessFineLocationPermission(),
            PermissionLists.getAccessCoarseLocationPermission()
        )
        //检查定位权限
        if (XXPermissions.isGrantedPermissions(
                mContext, mutableListOf(
                    PermissionLists.getAccessFineLocationPermission(),
                    PermissionLists.getAccessCoarseLocationPermission()
                )
            ) && mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        ) {
            list[1].state = ConstantInt.Type1
            list[1].selected = false
            adapter.notifyItemChanged(1)
        } else {
            if (list[1].state == ConstantInt.Type1) {
                list[1].state = errorType
                adapter.notifyItemChanged(1)
            }
        }

        //检测通知权限
        if (XXPermissions.isGrantedPermissions(
                mContext, mutableListOf(
                    PermissionLists.getPostNotificationsPermission(),
                    PermissionLists.getNotificationServicePermission()
                )
            )
        ) {
            list[2].state = ConstantInt.Type1
            list[2].selected = false
            adapter.notifyItemChanged(2)
        } else {
            if (list[2].state == ConstantInt.Type1) {
                list[2].state = errorType
                adapter.notifyItemChanged(2)
            }
        }

        //自动展开更多的说明项
        for (i in 0 until list.size) {
            val data = list[i]
            if (data.state == ConstantInt.Type0) {
                data.selected = true
                adapter.notifyItemChanged(i)
                break
            }
        }
    }

    /**
     * 操作蓝牙权限和开关
     */
    fun operateBluetooth() {
        Util.checkPermissions(
            mActivity,
            object : Util.RequestPermissionCallback {
                override fun onRequestPermissionSuccess() {
                    if (BleManager.getInstance().isSupportBle) {
                        SRBleUtil.instance.openBluetooth(mContext)
                    }
                }
            },
            "蓝牙权限",
            PermissionLists.getBluetoothScanPermission(),
            PermissionLists.getBluetoothConnectPermission()
        )
    }

    /**
     * 操作定位权限和GPS开关
     */
    fun operateGPSLocation() {
        Util.checkPermissions(
            mActivity,
            object : Util.RequestPermissionCallback {
                override fun onRequestPermissionSuccess() {
                    if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        val intent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        mContext.startActivity(intent)
                    }
                }
            },
            "定位权限",
            PermissionLists.getAccessFineLocationPermission(),
            PermissionLists.getAccessCoarseLocationPermission()
        )
    }

    /**
     * 操作通知权限
     */
    fun operateNotifications(adapter: BaseRecyclerAdapter<DataBean>, expansionState: Int) {
        Util.checkPermissions(
            mActivity,
            object : Util.RequestPermissionCallback {
                override fun onRequestPermissionSuccess() {
                    updatePermissionsState(adapter, expansionState)
                }
            },
            "通知权限",
            PermissionLists.getPostNotificationsPermission(),
            PermissionLists.getNotificationServicePermission()
        )
    }
}