package com.yidian.shenghuoquan.newscontent.ui.center

import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.yidian.common.AppConfig
import com.yidian.common.XBirdPageConstants
import com.yidian.common.XEventConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.common.base.BaseActivity
import com.yidian.common.http.CommonDataSource
import com.yidian.common.http.bean.GetCommonConfigBean
import com.yidian.common.http.callback.IGetCommonConfigCallback
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.adapter.MerchantServiceFunctionAdapter
import com.yidian.shenghuoquan.newscontent.adapter.MerchantServiceGroupAdapter
import com.yidian.shenghuoquan.newscontent.bean.HintOptionBean
import com.yidian.shenghuoquan.newscontent.constant.Constant
import com.yidian.shenghuoquan.newscontent.databinding.ActivityMerchantCenterBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.callback.*
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.GetLifeAccountInfoByIdBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.LifeAccountItemBean
import com.yidian.shenghuoquan.newscontent.ui.auth.LifeAccountAuthActivity
import com.yidian.shenghuoquan.newscontent.ui.auth.LifeAccountEnterpriseAuthActivity
import com.yidian.shenghuoquan.newscontent.ui.dialog.HintDialog
import com.yidian.shenghuoquan.newscontent.ui.dialog.MerchantCenterBottomHintDialog
import com.yidian.shenghuoquan.newscontent.utils.StorageUtil
import com.yidian.shenghuoquan.newscontent.widget.CommonTopBarView
import com.yidian.shenghuoquan.newscontent.widget.LifeAccountLabelView
import com.yidian.shenghuoquan.newscontent.widget.MerchantAssetView
import com.yidian.utils.ToastUtil
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xarc.xevent.XEventManager
import com.yidian.xpage.XPageManager
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * author: yinjiacheng
 * date: 6/8/21 8:11 PM
 * description: 商户管理中心
 */
class MerchantCenterActivity : BaseActivity<ActivityMerchantCenterBinding>(), MerchantSwitchDialog.OnMerchantSwitchCallback,
  LifeAccountLabelView.OnLifeAccountLabelCallback, IGetLifeAccountInfoByIdCallback,
  MerchantCenterBottomHintDialog.OnMerchantCenterBottomHintCallback, IAuthMerchantCheckCallback,
  MerchantServiceFunctionAdapter.OnItemClickListener, CommonTopBarView.OnCommonTopBarActionCallback, OnRefreshListener, IUserLogoutCallBack,
  DialogInterface.OnShowListener, DialogInterface.OnDismissListener, IGetCommonConfigCallback {

  companion object {
    // 传递的生活号信息
    const val EXTRA_LIFE_ACCOUNT_INFO = "lifeAccountInfo"

    // 是否有多个生活号
    const val EXTRA_IS_MULTI = "isMulti"

    const val PARAMS_LIFE_ACCOUNT_ID = "life_account_id"
  }

  /**
   * 当前生活号
   */
  private lateinit var curLifeAccount: LifeAccountItemBean.Response

  /**
   * 功能入口-页面路由映射
   */
  private val functionPageMap by lazy { HashMap<Int, String?>() }

  /**
   * 功能入口-页面参数映射
   */
  private val functionParamsMap by lazy { HashMap<Int, HashMap<String, Any?>>() }

  /**
   * 当前生活号状态下功能集
   */
  private val functionPermissionList by lazy { ArrayList<Int>() }

  override fun createViewBinding(): ActivityMerchantCenterBinding {
    return ActivityMerchantCenterBinding.inflate(layoutInflater)
  }

  override fun getXPageName(): String {
    return XRouterPathConstants.MERCHANT_CENTER
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    initView()
    initListener()
    initData()
    XEventManager.register(this)
  }

  override fun onDestroy() {
    super.onDestroy()
    XEventManager.unRegister(this)
  }

  private fun initView() {
    // 此页面不能返回
    viewBind.bvTopBar.setBackVisibility(false)
    viewBind.bvTopBar.setOnCommonTopBarCallback(null, this)

    // 服务列表展示
    viewBind.rvServiceGroup.layoutManager = LinearLayoutManager(this)
    viewBind.rvServiceGroup.addItemDecoration(MerchantServiceGroupAdapter.MerchantServiceGroupItemDecorator())
    viewBind.rvServiceGroup.adapter = MerchantServiceGroupAdapter(this, null, this)
  }

  private fun initListener() {
    viewBind.lvLifeAccountLabel.setOnLifeAccountLabelCallback(this)
    // 点击钱包余额进入我的钱包
    viewBind.avMerchantAsset.setOnClickWalletCallback(object : MerchantAssetView.OnClickWalletCallback {
      override fun toMyWallet(balance: String) {
        val map = HashMap<String, String?>()
        map["balance"] = balance
        XPageManager.push(XRouterPathConstants.MY_WALLET, map)
      }
    })
    // 设置下拉刷新监听
    viewBind.rlRefresh.setOnRefreshListener(this)
    // 禁用上拉加载更多
    viewBind.rlRefresh.setEnableLoadMore(false)
  }

  private fun initData() {
    val params = intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let { it as HashMap<*, *> }
    // 切换主体入口是否展示判断
    viewBind.bvTopBar.setActionVisibility(params?.get(EXTRA_IS_MULTI)?.let { it as Boolean } ?: false)
    curLifeAccount = params?.get(EXTRA_LIFE_ACCOUNT_INFO)?.let { it as LifeAccountItemBean.Response } ?: return
    viewBind.rlRefresh.autoRefresh()
  }

  /**
   * 刷新商户管理中心相关数据
   */
  private fun refreshMerchantCenterData(
    lifeAccountData: LifeAccountItemBean.Response,
    configData: GetCommonConfigBean.MerchantManagerCenter
  ) {
    // 设置标签
    viewBind.lvLifeAccountLabel.setLifeAccountData(lifeAccountData)
    // 设置钱包
    if (configData.isShowWallet == Constant.MERCHANT_SERVICE_SHOW) {
      viewBind.avMerchantAsset.isVisible = true
      viewBind.avMerchantAsset.setMerchantAssetData("0.00", "0.00")
    }
    // 展示底部浮窗
    showMerchantCenterBottomHint(lifeAccountData)
    // 生成FunctionId和XPage页面节点映射
    generateFunctionPageMap(configData.items)
    // 生成FunctionId和跳转页面参数映射
    generateFunctionParamsMap(configData.items)
    // 生成当前生活号状态下的功能集
    generateFunctionPermissionMap(configData.items)
    // 过滤商户服务数据
    filterMerchantServiceData(configData.items)
  }

  /**
   * 展示商户管理中心底部浮窗
   * 判断是否提示认证升级或提示认证驳回
   * @param data 当前生活号数据
   */
  private fun showMerchantCenterBottomHint(data: LifeAccountItemBean.Response) {
    if (data.life_account_auth_status == Constant.STATUS_AUTH_NOT && data.enterprise_auth_record_id == 0) {
      // 当前是个人未认证生活号 提示认证升级
      MerchantCenterBottomHintDialog(
        this,
        MerchantCenterBottomHintDialog.TYPE_AUTH_UPGRADE, this
      ).show()
    }
    if (data.enterprise_audit_status == Constant.STATUS_AUDIT_REJECT && data.role_type != Constant.TYPE_ROLE_ORDINARY) {
      // 当前企业认证驳回 提示修改
      MerchantCenterBottomHintDialog(
        this,
        MerchantCenterBottomHintDialog.TYPE_AUTH_REJECT, this
      ).show()
    }
  }

  /**
   * 生成FunctionId和XPage页面节点映射
   */
  private fun generateFunctionPageMap(data: List<GetCommonConfigBean.Item>) {
    if (data.isEmpty()) return
    functionPageMap.clear()
    // 我要发布-优惠券
    functionPageMap[data[0].functions[0].functionId] = XRouterPathConstants.COMMON_WEB_VIEW_ACTIVITY
    // 我要发布-招聘
    functionPageMap[data[0].functions[1].functionId] = null
    // 管理服务-权限管理
    functionPageMap[data[1].functions[0].functionId] = null
    // 管理服务-人员管理
    functionPageMap[data[1].functions[1].functionId] = XRouterPathConstants.PERSONAL_MY_STAFF
    // 其他服务-优惠券管理
    functionPageMap[data[2].functions[0].functionId] = XRouterPathConstants.COMMODITY_MANAGEMENT
    // 其他服务-职位管理
    functionPageMap[data[2].functions[1].functionId] = null
    // 其他服务-门店管理
    functionPageMap[data[2].functions[2].functionId] = XRouterPathConstants.STORE_MANAGEMENT
    // 其他服务-系统设置
    functionPageMap[data[2].functions[3].functionId] = XRouterPathConstants.SYSTEM_SETTING
    // 其他服务-认证管理
    functionPageMap[data[2].functions[4].functionId] = XRouterPathConstants.MERCHANT_AUTH_MANAGEMENT
  }

  /**
   * 生成FunctionId和跳转页面参数映射
   */
  private fun generateFunctionParamsMap(data: List<GetCommonConfigBean.Item>) {
    if (data.isEmpty()) return
    functionParamsMap.clear()
    // 认证管理传参生活号id和生活号key tag
    functionParamsMap[data[2].functions[4].functionId] =
      hashMapOf(
        MerchantAuthManagementActivity.EXTRA_LIFE_ACCOUNT_ID to curLifeAccount.life_account_id,
        MerchantAuthManagementActivity.EXTRA_LIFE_ACCOUNT_TAG_KEY to curLifeAccount.tag.tag_key
      )
    // 进入发布商品的url
    val pageUrl = XBirdPageConstants.COMMODITY_PUBLISH_COMMODITY + "?life_account_id=${curLifeAccount.life_account_id}"
    functionParamsMap[data[0].functions[0].functionId] =
      hashMapOf(
        XBirdPageConstants.PAGE_URL to pageUrl
      )
  }

  /**
   * 对应生活号权限下的功能集
   * 不在功能集中即为仅展示
   */
  private fun generateFunctionPermissionMap(data: List<GetCommonConfigBean.Item>) {
    if (data.isEmpty()) return
    functionPermissionList.clear()
    when (getCurLifeAccountLabel()) {
      Constant.LIFE_ACCOUNT_TAG_ENTERPRISE_AUTH -> {
        // 企业认证
        // 所有服务都可用
        functionPermissionList.add(data[0].functions[0].functionId)
        functionPermissionList.add(data[0].functions[1].functionId)
        functionPermissionList.add(data[1].functions[0].functionId)
        functionPermissionList.add(data[1].functions[1].functionId)
        functionPermissionList.add(data[2].functions[0].functionId)
        functionPermissionList.add(data[2].functions[1].functionId)
        functionPermissionList.add(data[2].functions[2].functionId)
        functionPermissionList.add(data[2].functions[3].functionId)
        functionPermissionList.add(data[2].functions[4].functionId)
      }
      Constant.LIFE_ACCOUNT_TAG_COMMON_ENTERPRISE_AUTH -> {
        // 普通企业认证
        // 所有服务都可用
        functionPermissionList.add(data[0].functions[0].functionId)
        functionPermissionList.add(data[0].functions[1].functionId)
        functionPermissionList.add(data[1].functions[0].functionId)
        functionPermissionList.add(data[1].functions[1].functionId)
        functionPermissionList.add(data[2].functions[0].functionId)
        functionPermissionList.add(data[2].functions[1].functionId)
        functionPermissionList.add(data[2].functions[2].functionId)
        functionPermissionList.add(data[2].functions[3].functionId)
        functionPermissionList.add(data[2].functions[4].functionId)
      }
      Constant.LIFE_ACCOUNT_TAG_INDIVIDUAL_BUSINESS_AUTH -> {
        // 个体工商户认证
        // 所有服务都可用
        functionPermissionList.add(data[0].functions[0].functionId)
        functionPermissionList.add(data[0].functions[1].functionId)
        functionPermissionList.add(data[1].functions[0].functionId)
        functionPermissionList.add(data[1].functions[1].functionId)
        functionPermissionList.add(data[2].functions[0].functionId)
        functionPermissionList.add(data[2].functions[1].functionId)
        functionPermissionList.add(data[2].functions[2].functionId)
        functionPermissionList.add(data[2].functions[3].functionId)
        functionPermissionList.add(data[2].functions[4].functionId)
      }
      Constant.LIFE_ACCOUNT_TAG_PERSONAL_AUTH -> {
        // 个人认证
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置 其他服务-认证管理
        functionPermissionList.add(data[0].functions[1].functionId)
        functionPermissionList.add(data[2].functions[1].functionId)
        functionPermissionList.add(data[2].functions[3].functionId)
        functionPermissionList.add(data[2].functions[4].functionId)
      }
      Constant.LIFE_ACCOUNT_TAG_NOT_AUTH -> {
        // 未认证
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置 其他服务-认证管理
        functionPermissionList.add(data[0].functions[1].functionId)
        functionPermissionList.add(data[2].functions[1].functionId)
        functionPermissionList.add(data[2].functions[3].functionId)
        functionPermissionList.add(data[2].functions[4].functionId)
      }
      Constant.LIFE_ACCOUNT_TAG_AUDIT_UNDER -> {
        // 审核中
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置 其他服务-认证管理
        functionPermissionList.add(data[0].functions[1].functionId)
        functionPermissionList.add(data[2].functions[1].functionId)
        functionPermissionList.add(data[2].functions[2].functionId)
        functionPermissionList.add(data[2].functions[3].functionId)
        functionPermissionList.add(data[2].functions[4].functionId)
      }
      Constant.LIFE_ACCOUNT_TAG_AUTH_REJECT -> {
        // 认证驳回
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置 其他服务-认证管理
        functionPermissionList.add(data[0].functions[1].functionId)
        functionPermissionList.add(data[2].functions[1].functionId)
        functionPermissionList.add(data[2].functions[3].functionId)
        functionPermissionList.add(data[2].functions[4].functionId)
      }
    }
  }

  /**
   * 过滤商户服务数据
   * 目前处理 1.个人认证状态下和企业员工角色下不展示管理服务
   * 2.企业员工角色下不展示其他服务-认证管理
   */
  private fun filterMerchantServiceData(data: List<GetCommonConfigBean.Item>) {
    (data as ArrayList<GetCommonConfigBean.Item>).iterator().apply {
      while (hasNext()) {
        val group = next()
        if (group.groupId == Constant.MERCHANT_SERVICE_GROUP_MANAGEMENT) {
          // 个人认证或企业员工不展示管理服务
          if (getCurLifeAccountLabel() == Constant.LIFE_ACCOUNT_TAG_PERSONAL_AUTH || curLifeAccount.role_type == Constant.TYPE_ROLE_ORDINARY) {
            remove()
          }
        }
        if (group.groupId == Constant.MERCHANT_SERVICE_GROUP_OTHER) {
          // 企业员工不展示其他服务-认证管理
          if (curLifeAccount.role_type == Constant.TYPE_ROLE_ORDINARY) {
            (group.functions as ArrayList<GetCommonConfigBean.Function>).iterator().apply {
              while (hasNext()) {
                val function = next()
                if (function.functionId == Constant.MERCHANT_SERVICE_FUNCTION_AUTH_MANAGEMENT) {
                  remove()
                }
              }
            }
          }
        }
      }
    }
    (viewBind.rvServiceGroup.adapter as MerchantServiceGroupAdapter).updateData(data)
  }

  /**
   * 获取当前生活号标签
   * 目前不支持区分个体工商户和普通企业
   */
  private fun getCurLifeAccountLabel(): Int {
    when (curLifeAccount.enterprise_audit_status) {
      Constant.STATUS_AUDIT_UNDER -> return Constant.LIFE_ACCOUNT_TAG_AUDIT_UNDER // 审核中
      Constant.STATUS_AUDIT_REJECT -> return Constant.LIFE_ACCOUNT_TAG_AUTH_REJECT // 认证驳回
    }
    when (curLifeAccount.life_account_auth_status) {
      Constant.STATUS_AUTH_FINISH -> {
        when (curLifeAccount.life_account_type) {
          Constant.TYPE_LIFE_ACCOUNT_PERSONAL -> return Constant.LIFE_ACCOUNT_TAG_PERSONAL_AUTH // 个人已认证
          Constant.TYPE_LIFE_ACCOUNT_ENTERPRISE -> return Constant.TYPE_LIFE_ACCOUNT_ENTERPRISE // 企业已认证
        }
      }
    }
    return Constant.LIFE_ACCOUNT_TAG_NOT_AUTH // 个人未认证
  }

  override fun onLifeAccountSelect(data: LifeAccountItemBean.Response) {
    // 用户切换主体 更新当前生活号信息
    curLifeAccount = data
    viewBind.rlRefresh.autoRefresh()
  }

  override fun onEnterLifeAccountInfo(lifeAccountId: String) {
    // 请求生活号详情接口
    ApiService.getLifeAccountInfoById(
      this,
      hashMapOf(Pair(PARAMS_LIFE_ACCOUNT_ID, lifeAccountId))
    )
  }

  override fun getLifeAccountInfoByIdSuccess(result: GetLifeAccountInfoByIdBean.Response?) {
    // 跳转生活号基本信息
    XPageManager.push(
      XRouterPathConstants.MERCHANT_INFO,
      hashMapOf(Pair(MerchantInfoActivity.EXTRA_LIFE_ACCOUNT_INFO, result))
    )
  }

  override fun getLifeAccountInfoByIdFailure(message: String?) {

  }

  override fun onUpgradeAuth() {
    // 由未认证升级认证 跳转认证首页
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_AUTH,
      hashMapOf(Pair(LifeAccountAuthActivity.EXTRA_PAGE_FROM, LifeAccountAuthActivity.FROM_AUTH))
    )
  }

  override fun onModifyEnterpriseAuth() {
    // 修改企业认证 先请求企业认证信息
    ApiService.authMerchantCheck(this, hashMapOf(Pair(PARAMS_LIFE_ACCOUNT_ID, curLifeAccount.life_account_id)))
  }

  override fun authMerchantCheckSuccess(result: AuthMerchantCheckBean.Response?) {
    // 跳转企业认证流程
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_ENTERPRISE_AUTH,
      hashMapOf(
        Pair(
          LifeAccountEnterpriseAuthActivity.EXTRA_LIFE_ACCOUNT_ID,
          curLifeAccount.life_account_id
        ),
        Pair(LifeAccountEnterpriseAuthActivity.EXTRA_AUTH_DATA, result),
        Pair(LifeAccountEnterpriseAuthActivity.EXTRA_IS_AUTH_MODIFY, curLifeAccount.enterprise_audit_status == Constant.STATUS_AUDIT_REJECT)
      )
    )
  }

  override fun authMerchantCheckFailure(message: String?) {

  }

  override fun onItemClick(view: View, position: Int, data: GetCommonConfigBean.Function) {
    // 选择某一个功能
    // 若在当前权限功能集中则跳转指定页
    if (functionPermissionList.contains(data.functionId)) {
      functionPageMap[data.functionId]?.let { XPageManager.push(it, functionParamsMap[data.functionId]) }
        ?: ToastUtil.showToast(this, "正在建设中...")
    } else {
      // 若当前功能无权限 根据生活号类型做弹窗提示
      if (curLifeAccount.enterprise_audit_status == Constant.STATUS_AUDIT_UNDER) {
        // 审核中 提示加急审核
        HintDialog(
          this,
          resources.getString(R.string.audit_urgent),
          arrayListOf(HintOptionBean(resources.getString(R.string.close))), null
        ).setRightBtnColor(ContextCompat.getColor(this, R.color.color_FF1852F1)).show()
        return
      }
      if (curLifeAccount.enterprise_audit_status == Constant.STATUS_AUDIT_REJECT) {
        // 审核驳回 提示修改认证
        HintDialog(
          this,
          resources.getString(R.string.auth_apply_reject),
          arrayListOf(HintOptionBean(resources.getString(R.string.close)), HintOptionBean(resources.getString(R.string.modify_auth))),
          object : HintDialog.OnHintOptionCallback {
            override fun onLeftOption() {

            }

            override fun onRightOption() {
              // 认证修改 请求商户认证检查
              ApiService.authMerchantCheck(
                this@MerchantCenterActivity,
                hashMapOf(Pair(LifeAccountEnterpriseAuthActivity.EXTRA_LIFE_ACCOUNT_ID, curLifeAccount.life_account_id))
              )
            }

          }).setRightBtnColor(ContextCompat.getColor(this, R.color.color_FFFF3A3A)).show()
        return
      }
      if (curLifeAccount.life_account_type == Constant.TYPE_LIFE_ACCOUNT_PERSONAL && curLifeAccount.life_account_auth_status == Constant.STATUS_AUTH_NOT) {
        // 未认证 提示认证 此处企业审核中也满足此条件但前面审核状态判断已拦截
        HintDialog(
          this,
          resources.getString(R.string.auth_to_use_more_tool),
          arrayListOf(HintOptionBean(resources.getString(R.string.close)), HintOptionBean(resources.getString(R.string.goto_auth))),
          object : HintDialog.OnHintOptionCallback {
            override fun onLeftOption() {

            }

            override fun onRightOption() {
              // 进行认证
              XPageManager.push(
                XRouterPathConstants.LIFE_ACCOUNT_AUTH,
                hashMapOf(Pair(LifeAccountAuthActivity.EXTRA_PAGE_FROM, LifeAccountAuthActivity.FROM_AUTH))
              )
            }

          }).setRightBtnColor(ContextCompat.getColor(this, R.color.color_FF1852F1)).show()
        return
      }
      if (curLifeAccount.life_account_type == Constant.TYPE_LIFE_ACCOUNT_PERSONAL) {
        // 个人认证 提示认证升级
        HintDialog(
          this,
          resources.getString(R.string.upgrade_to_use_more_tool),
          arrayListOf(HintOptionBean(resources.getString(R.string.close)), HintOptionBean(resources.getString(R.string.goto_upgrade))),
          object : HintDialog.OnHintOptionCallback {
            override fun onLeftOption() {

            }

            override fun onRightOption() {
              // 认证升级 请求商户认证检查
              ApiService.authMerchantCheck(
                this@MerchantCenterActivity,
                hashMapOf(Pair(LifeAccountEnterpriseAuthActivity.EXTRA_LIFE_ACCOUNT_ID, curLifeAccount.life_account_id))
              )
            }

          }).setRightBtnColor(ContextCompat.getColor(this, R.color.color_FF1852F1)).show()
      }
    }
  }

  override fun onDoAction() {
    // 切换主体 请求生活号列表接口
    ApiService.getLifeAccountList(object : IGetLifeAccountListCallback {
      override fun getLifeAccountListSuccess(result: ArrayList<LifeAccountItemBean.Response>?) {
        // 生活号列表请求成功 弹出切换主体弹窗
        result?.let {
          val dialog = MerchantSwitchDialog(this@MerchantCenterActivity, curLifeAccount.life_account_id, it, this@MerchantCenterActivity)
          dialog.setOnShowListener(this@MerchantCenterActivity)
          dialog.setOnDismissListener(this@MerchantCenterActivity)
          dialog.show()
        }
      }

      override fun getLifeAccountListFailure(message: String?) {

      }
    })
  }

  @Subscribe(sticky = false, threadMode = ThreadMode.MAIN)
  fun onEvent(event: XBaseEvent?) {
    when (event?.name) {
      XEventConfig.LIFE_ACCOUNT_NAME_MODIFY -> {
        // 更新生活号名称
        val accountName = event.body as String
        viewBind.lvLifeAccountLabel.setLifeAccountName(accountName)
      }
    }
  }

  override fun onRefresh(refreshLayout: RefreshLayout) {
    // 刷新数据
    // 请求TowerPro通用配置
    CommonDataSource.getCommonConfig(
      this,
      hashMapOf(
        "appid" to AppConfig.appid,
        "env" to AppConfig.TowerApiEnv,
        "version" to AppConfig.TowerApiVersion,
        "os" to AppConfig.TowerApiOS,
        "keytag" to AppConfig.TowerApiKeyTag
      )
    )
  }

  override fun userLogoutSuccess() {
    XPageManager.push(XRouterPathConstants.LOGIN_LIFE_CIRCLE, null)
  }

  override fun onShow(dialog: DialogInterface?) {
    // 切换主体弹窗显示
    // 更改页面标题背景色
    viewBind.bvTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.white))
  }

  override fun onDismiss(dialog: DialogInterface?) {
    // 切换主体弹窗消失
    // 更改页面标题背景色
    viewBind.bvTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.transparent))
  }

  override fun getCommonConfigSuccess(@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") configResult: GetCommonConfigBean.GetCommonConfigResponse?) {
    // 请求生活号列表
    ApiService.getLifeAccountList(object : IGetLifeAccountListCallback {
      override fun getLifeAccountListSuccess(@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE") lifeAccountResult: ArrayList<LifeAccountItemBean.Response>?) {
        viewBind.rlRefresh.finishRefresh(true)
        if (lifeAccountResult?.size == 0) {
          // 如果当前无生活号则退出登录
          ToastUtil.showToast(this@MerchantCenterActivity, resources.getString(R.string.no_life_account))
          ApiService.userLogout(this@MerchantCenterActivity)
          return
        }
        if (lifeAccountResult?.contains(curLifeAccount) == false) {
          // 当前选择的生活号已不存在则切换第一个生活号 目前为企业员工被解除关系会触发
          curLifeAccount = lifeAccountResult[0]
          // 更新本地存储的生活号id
          StorageUtil.putLifeAccountId(lifeAccountResult[0].life_account_id)
          // 刷新数据
          configResult?.data?.merchantManagerCenter?.let { refreshMerchantCenterData(lifeAccountResult[0], it) }
          // 切换主体入口是否展示判断
          viewBind.bvTopBar.setActionVisibility(lifeAccountResult.size > 1)
          return
        }
        lifeAccountResult?.let {
          // 切换主体入口是否展示判断
          viewBind.bvTopBar.setActionVisibility(it.size > 1)
        }
        lifeAccountResult?.forEach {
          if (curLifeAccount.life_account_id == it.life_account_id) {
            curLifeAccount = it
            // 刷新数据
            configResult?.data?.merchantManagerCenter?.let { configData -> refreshMerchantCenterData(it, configData) }
          }
        }
      }

      override fun getLifeAccountListFailure(message: String?) {
        viewBind.rlRefresh.finishRefresh(false)
      }
    })
  }

  override fun getCommonConfigFailure(message: String?) {
    viewBind.rlRefresh.finishRefresh(false)
  }
}
