package com.driver.igotrip.ui.main import android.Manifest import android.content.ActivityNotFoundException import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Message import android.provider.Settings import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.core.net.toUri import cn.sinata.rxnetty.LogHelper import cn.sinata.rxnetty.NettyClient import cn.sinata.xldutils.utils.SPUtils import cn.sinata.xldutils.utils.clickDelay import cn.sinata.xldutils.utils.doubleOne import cn.sinata.xldutils.utils.getVersionName import cn.sinata.xldutils.utils.gone import cn.sinata.xldutils.utils.setDrawableLeft import cn.sinata.xldutils.utils.textColor import com.driver.igotrip.R import com.driver.igotrip.base.BaseEvent import com.driver.igotrip.base.Const import com.driver.igotrip.base.MyApplication import com.driver.igotrip.base.MyBaseActivity import com.driver.igotrip.base.gaode.AMapKit import com.driver.igotrip.bean.BooleanBean import com.driver.igotrip.bean.HomeDataBean import com.driver.igotrip.bean.MyCarBean import com.driver.igotrip.bean.OrderSimpleData import com.driver.igotrip.bean.SelectServerModeBean import com.driver.igotrip.bean.TimeBean import com.driver.igotrip.bean.UpCarInfo import com.driver.igotrip.bean.UserBean import com.driver.igotrip.bean.VersionBean import com.driver.igotrip.netUtls.Api import com.driver.igotrip.netUtls.callNet import com.driver.igotrip.netUtls.getMapByAny import com.driver.igotrip.service.LocationForegroundService import com.driver.igotrip.ui.DialogUtil import com.driver.igotrip.ui.DialogUtil.getDelAndSureDialog import com.driver.igotrip.ui.main.event.MineEventActivity import com.driver.igotrip.ui.mine.BalanceTopupActivity import com.driver.igotrip.ui.mine.ChangeCarActivity import com.driver.igotrip.ui.mine.DriverAttestationActivity import com.driver.igotrip.ui.mine.MineActivity import com.driver.igotrip.ui.mine.MsgActivity import com.driver.igotrip.ui.mine.OfflinePayActivity import com.driver.igotrip.utils.Cache.CacheKey import com.driver.igotrip.utils.DateUtil import com.driver.mask_talk.utils.toTime import com.driver.mask_talk.utils.toTimeEnglish import com.driver.mask_talk.utils.toTimeFrench import com.google.android.gms.maps.GoogleMap import com.google.gson.Gson import com.tbruyelle.rxpermissions2.RxPermissions import com.wang.avi.AVLoadingIndicatorView import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.jetbrains.anko.browse import org.jetbrains.anko.find import org.jetbrains.anko.startActivity import org.jetbrains.anko.toast class MainActivity : MyBaseActivity()/*, DriverContext.DriverStatusListener*/ { val mainFragment by lazy { MainFragment() } var homeDataBean: HomeDataBean? = null /* var navigator: Navigator? = null var vehicleReporter: RidesharingVehicleReporter? = null*/ private val MSG_REFRESH_LOCATIAON = 1 private val iv_main_icon by lazy { find(R.id.iv_main_icon) } private val tv_active by lazy { find(R.id.tv_active) } private val tv_today_time by lazy { find(R.id.tv_today_time) } private val tv_week_time by lazy { find(R.id.tv_week_time) } private val tv_month_time by lazy { find(R.id.tv_month_time) } private val avv_anim by lazy { find(R.id.avv_anim) } private val tv_up_avv by lazy { find(R.id.tv_up_avv) } private val tv_order_num by lazy { find(R.id.tv_order_num) } private val tv_month_order by lazy { find(R.id.tv_month_order) } private val tv_task by lazy { find(R.id.tv_task) } private val tv_car_num by lazy { find(R.id.tv_car_num) } private val tv_core by lazy { find(R.id.tv_core) } private val tv_lien_name by lazy { find(R.id.tv_lien_name) } private val tv_time by lazy { find(R.id.tv_time) } private val tv_car by lazy { find(R.id.tv_car) } private val tv_server_ing by lazy { find(R.id.tv_server_ing) } private val tv_history_order by lazy { find(R.id.tv_history_order) } private val tv_wait_server by lazy { find(R.id.tv_wait_server) } private val ll_task by lazy { find(R.id.ll_task) } private val handler by lazy { object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { super.handleMessage(msg) if (msg.what == MSG_REFRESH_LOCATIAON) { //刷新位置信息 Refresh location information // AMapKit.initLocation(this@MainActivity){ // MyApplication.aMapLocation = it // } } } } } override fun setContentView() { setContentView(R.layout.activity_main) /* lifecycleScope.launch { while (true){ delay(5000) var map = getMapByAny() callNet(false,getDriverOrderMessage, map) { Log.e("长连接接口消息: ",it.toString() ) } } }*/ } override fun initView() { // setTitleText(getString(R.string.IGO司机)) tv_Left.setDrawableLeft(R.mipmap.icon_nav_user) // iv_right_title.setImageResource(R.mipmap.icon_nav_news) findViewById(R.id.img_leftuser).setOnClickListener { startActivity() } findViewById(R.id.iv_right_titlenew).setOnClickListener { startActivity() } addFragment(mainFragment, R.id.rl_container) // AMapKit.initLocation(this){ // MyApplication.aMapLocation = it // } iv_main_icon.clickDelay { // AMapKit.initLocation(this){ // MyApplication.aMapLocation = it // } // showOrder("","12634","1",10,1) } // initDriver() MyApplication.isLogin = true beOnDuty(false) initCall() NettyClient.getInstance().startService() callVersion() checkGps() MyApplication.addOrderView(qeeOrderView) callcarAll() toastTo() callTime("1") showTitle(false) showHeader(false) /*lifecycleScope.launch { while (true){ var map = getMapByAny() callNet(showDialog=false,getDriverOrderMessage, map) { Log.e("获取消息: ",it .toString()) } delay(5000) } }*/ } /** * 初始化司机sdk */ /* private fun initDriver() { if (CacheKey.getKeyStr("vehicleId").isNullOrEmpty()) return NavigationApi.getNavigator( this, // Activity object : NavigationApi.NavigatorListener { override fun onError(p0: Int) { Log.e(Const.GoogleDriver.TAG, "初始化司机sdk失败$p0") } override fun onNavigatorReady(navigator: Navigator) { // Keep a reference to the Navigator (used to configure and start nav) this@MainActivity.navigator = navigator Log.e(Const.GoogleDriver.TAG, "初始化司机sdk成功") val driverContext = DriverContext.builder(application) //.setProviderId("i-go-odrd-testing") .setProviderId("gopost-475301") .setVehicleId(CacheKey.getKeyStr("vehicleId")) .setAuthTokenFactory(JsonAuthTokenFactory()) .setNavigator(navigator) .setRoadSnappedLocationProvider( NavigationApi.getRoadSnappedLocationProvider( application ) ) .setDriverStatusListener(this@MainActivity) .build() val ridesharingDriverApi = RidesharingDriverApi.createInstance(driverContext) vehicleReporter = ridesharingDriverApi.ridesharingVehicleReporter vehicleReporter!!.enableLocationTracking() } } ) }*/ override fun onRestart() { super.onRestart() callTime("1") } @Subscribe fun onStopLocation(e: BaseEvent) { if (e.code == 542) handler?.removeMessages(MSG_REFRESH_LOCATIAON) } private fun callTime(type: String) { var map = getMapByAny() callNet(Api.getDriverOnlineTime, map) { var bean = gson.fromJson(it, TimeBean::class.java) if (bean.data.attendance == 0.0) { tv_active.text = "0.0h" } else { tv_active.text = doubleOne(bean.data.attendance / 60 / 60) + "h" } if (bean.data.today == 0.0) { tv_today_time.text = "0.0h" } else { tv_today_time.text = doubleOne(bean.data.today / 60 / 60) + "h" } if (bean.data.thisWeek == 0.0) { tv_week_time.text = "0.0h" } else { tv_week_time.text = doubleOne(bean.data.thisWeek / 60 / 60) + "h" } if (bean.data.thisMonth == 0.0) { tv_month_time.text = "0.0h" } else { tv_month_time.text = doubleOne(bean.data.thisMonth / 60 / 60) + "h" } } } private fun toastTo() { var jumpCode = CacheKey.getKeyStr("jumpCode") if (jumpCode == "100000") { DialogUtil.getDelAndSureDialog(this, getString(R.string.是否完善个人资料), {}, { startActivity() }) } } private fun callcarAll() { callNet(Api.queryMyCar, getMapByAny()) { var bean = gson.fromJson(it, MyCarBean::class.java) if (bean.data.car.isNullOrEmpty()) { DialogUtil.getDelAndSureDialog(this, getString(R.string.您还没有完善车辆信息), {}, { startActivity() }) } } } private var qeeOrderView = object : MyApplication.OrderStatueView { override fun orderInfo(data: OrderSimpleData?) { data?.let { when (it.orderType) { 1, 2, 3 -> { if (it.status == 10 || it.status == 12) { Handler(Looper.getMainLooper()).post { mainFragment?.refresh() // MyApplication.getTTsManager().setVideoText(getString(R.string.有用户订单被取消或改派)) } } } } } } } private fun checkGps() { if (!AMapKit.isLocServiceEnable(this)) { DialogUtil.getDelAndSureDialog( this, getString(R.string.查看定位), getString(R.string.退出), getString( R.string.您暂未开启手机定位 ), { onBackPressedHandle() }) { val intent = Intent() intent.action = Settings.ACTION_LOCATION_SOURCE_SETTINGS; intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK; try { startActivity(intent) } catch (ex: ActivityNotFoundException) { //如果页面无法打开,进入设置页面 intent.action = Settings.ACTION_SETTINGS try { startActivity(intent) } catch (e: Exception) { e.printStackTrace() } } } } // if (!MyUtils.canBackgroundStart(this)) { // DialogUtil.getDelAndSureDialog(this, getString(R.string.前往开启), getString(R.string.退出), getString( // R.string.可能导致无法接单), { // onBackPressedHandle() // }) { // MyUtils.toSettingPro(this) // } // } } private fun callVersion() { val map = getMapByAny() // map["id"] = CacheKey.getUserId() callNet(isUseAllTrustService = true, showDialog = true, api = Api.queryNewData, map = map, clickAction = { val data = gson.fromJson(it, VersionBean::class.java) if (data.data.version != "" && data.data.version != getVersionName()) { when (data.data.mandatory) { 2 -> { DialogUtil.getDelAndSureDialog( this, getString(R.string.新版本更新), data.data.content, {}, { browse(data.data.url) }) } 1 -> { DialogUtil.getDelAndSureDialog( this, getString(R.string.新版本更新), data.data.content, { EventBus.getDefault().post(BaseEvent(BaseEvent.OUT_APP)) }, { browse(data.data.url) }) } else -> { // toast("已经是最新版本") } } } else { // toast("已经是最新版本") } }) { _, _ -> } } lateinit var aMap: GoogleMap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (CacheKey.getKeyStr(Const.REFUSE_LOCATION).isNotEmpty() && !RxPermissions(this).isGranted(Manifest.permission.ACCESS_FINE_LOCATION) ) { toast(getString(R.string.没有定位权限提示)) } else { if (!RxPermissions(this).isGranted(Manifest.permission.ACCESS_FINE_LOCATION)) { DialogUtil.getDelAndSureDialog( this, getString(R.string.确认), getString(R.string.拒绝权限), getString(R.string.定位权限说明), { LogHelper.logRecord("用户拒绝定位权限1") }) { val subscribe = RxPermissions(this).request(Manifest.permission.ACCESS_FINE_LOCATION) .subscribe { it -> if (!it) { toast(getString(R.string.没有定位权限提示)) CacheKey.putKeyStr(Const.REFUSE_LOCATION, "1") LogHelper.logRecord("用户拒绝定位权限2") } else { val subscribe = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { RxPermissions(this).request(Manifest.permission.ACCESS_BACKGROUND_LOCATION) .subscribe { if (!it) { toast(getString(R.string.没有定位权限提示)) CacheKey.putKeyStr(Const.REFUSE_LOCATION, "1") LogHelper.logRecord("用户拒绝定位权限3") } else { initLocation() initFloatingWindow() } } } else { initLocation() initFloatingWindow() } } } } } else { initLocation() initFloatingWindow() } } } //初始化定位 private fun initLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return } LocationForegroundService.start() } //初始化悬浮窗 private fun initFloatingWindow() { if (!Settings.canDrawOverlays(this) && CacheKey.getKeyStr(Const.REFUSE_FLOATING_WINDOW) != "1") { DialogUtil.getDelAndSureDialog( this, getString(R.string.确认), getString(R.string.拒绝权限), getString(R.string.悬浮窗说明), { CacheKey.putKeyStr(Const.REFUSE_FLOATING_WINDOW, "1") }) { val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, "package:${packageName}".toUri()).apply { putExtra("package", packageName) } startActivity(intent) } } } override fun onResume() { super.onResume() MyApplication.couldShowFloatingWindow = Settings.canDrawOverlays(this) && CacheKey.getKeyStr(Const.REFUSE_FLOATING_WINDOW) != "1" mainFragment?.refresh() callNet(Api.needToSettle, getMapByAny()) { var bean = gson.fromJson(it, BooleanBean::class.java).data if (bean) { showPayDialog() } } } fun beOnDuty(b: Boolean) { if (b) { // avv_anim.visible() // tv_up_avv.visible() } else { avv_anim.gone() tv_up_avv.gone() } } private fun initCall() { var map = getMapByAny() callNet(Api.queryHomeData, map) { var data = gson.fromJson(it, HomeDataBean::class.java) homeDataBean = data clickCallOrder() tv_order_num.text = data.data.dayNum.toString() tv_month_order.text = data.data.mouthNum.toString() // tv_grade.text = getFormatOne(data.data.score) tv_task.text = data.data.activity.toString() tv_car_num.text = data.data.licensePlate tv_core.text = doubleOne(data.data.score).toString() tv_lien_name.text = data.data.brand.toString() tv_car.text = if (data.data.work == 1) getString(R.string.下班) else getString(R.string.出车) MyApplication.isWorking = data.data.work == 1 if (data.data.work == 1) { /*try { vehicleReporter?.setVehicleState(RidesharingVehicleReporter.VehicleState.ONLINE) } catch (e: Exception) { }*/ // MyApplication.getTTsManager().setVideoText(getString(R.string.您正在上班中)) beOnDuty(true) } else { // MyApplication.getTTsManager().setVideoText(getString(R.string.您已下班)) beOnDuty(false) } tv_time.text = getFormantDay(System.currentTimeMillis()) + " " + DateUtil.getWeek( this, System.currentTimeMillis() ) } } fun callNum() { var map = getMapByAny() callNet(Api.queryHomeData, map) { var data = gson.fromJson(it, HomeDataBean::class.java) homeDataBean = data tv_order_num.text = data.data.dayNum.toString() tv_month_order.text = data.data.mouthNum.toString() // tv_grade.text = getFormatOne(data.data.score) tv_task.text = data.data.activity.toString() tv_car_num.text = data.data.licensePlate tv_lien_name.text = data.data.brand.toString() tv_time.text = getFormantDay(System.currentTimeMillis()) + " " + DateUtil.getWeek( this, System.currentTimeMillis() ) } } /** * 根据语言格式化日期显示 */ private fun getFormantDay(time: Long): String { val language = SPUtils.getString(Const.language) return if (language == Const.Language.ENGLISH) time.toTimeEnglish() else if (language == Const.Language.FRENCH) time.toTimeFrench() else time.toTime( "MM月dd日" ) } override fun setOnclick() { tv_server_ing.setOnClickListener { tv_server_ing.textColor(this, R.color.blue_1) tv_wait_server.textColor(this, R.color.main_gray) mainFragment.state = 1 mainFragment.autoRefresh() } tv_wait_server.setOnClickListener { tv_server_ing.textColor(this, R.color.main_gray) tv_wait_server.textColor(this, R.color.blue_1) mainFragment.state = 2 mainFragment.autoRefresh() } tv_Left.clickDelay { startActivity() } iv_right_title.clickDelay { } tv_history_order.clickDelay { startActivity() } ll_task.clickDelay { startActivity() } clickCallOrder() } private fun clickCallOrder() { tv_car.clickDelay { if (homeDataBean?.data?.work == 1) { callNet(Api.work, getMapByAny()) { homeDataBean?.data?.work = 2 tv_car.text = getString(R.string.出车) MyApplication.isWorking = false beOnDuty(false) val bean = Gson().fromJson(it, UpCarInfo::class.java) MyApplication.getTTsManager().setVideoText(bean.data?.audioUrl) } } else { callNet(Api.needToSettle, getMapByAny()) { var bean = gson.fromJson(it, BooleanBean::class.java).data if (bean) { showPayDialog() } else { judgeAccountEffective { callNet(Api.queryMyBusiness, getMapByAny()) { var bean = gson.fromJson(it, SelectServerModeBean::class.java).data if (bean.isEmpty()) { toast(getString(R.string.请选择接单业务)) return@callNet } if (bean.size > 1) { startActivity() } else { var map = getMapByAny() map["type"] = bean[0].id callNet(Api.work, map) { var carinfo = gson.fromJson( it, UpCarInfo::class.java ) if (carinfo.data?.jumpCode == "200000") { DialogUtil.getDelAndSureDialog( this, getString(R.string.您还没有完善车辆信息), {}, { startActivity() }) } else { toast(getString(R.string.上班成功)) beOnDuty(true) MyApplication.getTTsManager() .setVideoText(carinfo.data?.audioUrl) CacheKey.putKeyStr( "vehicleId", carinfo.data?.vehicleId ?: "" ) EventBus.getDefault() .post(BaseEvent(BaseEvent.START_CAR)) } } } } } } } } } } /**判断账户是否有效 * @param effectiveCallback 能够操作的回调*/ private fun judgeAccountEffective(effectiveCallback: () -> Unit) { callNet(Api.queryInfo, getMapByAny()) { val user = gson.fromJson(it, UserBean::class.java) if (user.data == null) { return@callNet } if (!user.data.couldTakeOrder()) { showNoticeAccountBalanceDialog(user.data.orderMinBalance) return@callNet } effectiveCallback.invoke() } } /**显示提示账户余额弹窗 * @param min 最低金额*/ private fun showNoticeAccountBalanceDialog(min: String) { val l = SPUtils.getString(Const.language) val sure: String val cancel: String val content: String val warn: String when (l) { Const.Language.FRENCH -> { sure = getString(R.string.充值) cancel = "Fermer" warn = "Rappel" content = "Solde inférieur à FCFA$min, s'il vous plaît recharger d'abord" } Const.Language.CHINESE, "zh" -> { sure = getString(R.string.充值) cancel = "关闭" warn = "提示" content = "余额不足FCFA${min},请先充值" } else -> { sure = getString(R.string.充值) cancel = "Close" warn = "Reminder" content = "The balance is less than FCFA$min, please recharge first" } } val delAndSureDialog = getDelAndSureDialog( this, sure, cancel, content, {}) { startActivity() } delAndSureDialog.window?.decorView?.let { it.find(R.id.tv_hint_base).text = warn } } private fun showPayDialog() { val l = SPUtils.getString(Const.language) val pay: String val off: String val msg: String val warn: String when (l) { Const.Language.FRENCH -> { pay = "Payer" off = "Fermer" warn = "Rappel" msg = "Vous avez des frais de règlement en attente de paiement, vous ne pouvez recevoir des commandes qu’après paiement, veuillez payer dès que possible" } Const.Language.CHINESE, "zh" -> { pay = "支付" off = "关闭" warn = "提示" msg = "您有一笔结算费待支付,须支付后才能接单,请尽快支付" } else -> { pay = "Pay" off = "Close" warn = "Reminder" msg = "You have a settlement fee pending payment, you can only receive orders after payment, please pay as soon as possible" } } val delAndSureDialog = getDelAndSureDialog( this, pay, off, msg, {}) { startActivity() } delAndSureDialog.window?.decorView?.let { it.find(R.id.tv_hint_base).text = warn } } private var mBackAppTime: Long = 0 override fun onBackPressedHandle() { if (System.currentTimeMillis() - mBackAppTime > 2000) { Toast.makeText(this, getString(R.string.再按一次退出程序), Toast.LENGTH_SHORT).show() mBackAppTime = System.currentTimeMillis() } else { closeAll() MyApplication.hasAutoGoTripping = false } } override fun onEventMainThread(event: BaseEvent?) { super.onEventMainThread(event) when (event!!.code) { BaseEvent.START_CAR -> { beOnDuty(true) /* if (vehicleReporter == null) { initDriver() }*/ initCall() } BaseEvent.CHANGE_CAR_SUCCESS -> { initCall() } BaseEvent.CALL_NUM_MAIN -> { callNum() } BaseEvent.REFREASH_MAIN -> { mainFragment?.refresh() } BaseEvent.FORCED_OFFLINE -> { initCall() } } } override fun onStop() { super.onStop() } /* override fun updateStatus( p0: DriverContext.DriverStatusListener.StatusLevel, p1: DriverContext.DriverStatusListener.StatusCode, p2: String, p3: Throwable?, ) { Log.e( Const.GoogleDriver.TAG, "StatusLevel:${p0.name},StatusCode:${p1},p2:${p2},错误信息:${p3?.message}" ) } */ override fun onDestroy() { MyApplication.couldShowFloatingWindow = false LocationForegroundService.stop() super.onDestroy() MyApplication.removeOrderView(qeeOrderView) } }