package com.yidian.shenghuoquan.bmanagercenter.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.google.gson.Gson
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
import com.yidian.bcommon.base.BaseActivity
import com.yidian.bcommon.bean.LifeAccountItemBean
import com.yidian.bcommon.constant.*
import com.yidian.bcommon.http.bean.GetCommonConfigBean
import com.yidian.bcommon.sdk.ClientType
import com.yidian.bcommon.sdk.JudgeClientUtils
import com.yidian.bcommon.services.ZapServiceActionConstants
import com.yidian.bcommon.services.ZapServiceNameConstants
import com.yidian.bcommon.widget.CommonHintDialog
import com.yidian.bcommon.widget.CommonTopBarView
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.adapter.MerchantServiceFunctionAdapter
import com.yidian.shenghuoquan.bmanagercenter.adapter.MerchantServiceGroupAdapter
import com.yidian.shenghuoquan.bmanagercenter.config.ManagerCenterConfig
import com.yidian.shenghuoquan.bmanagercenter.constant.Constant
import com.yidian.shenghuoquan.bmanagercenter.databinding.ActivityMerchantCenterBinding
import com.yidian.shenghuoquan.bmanagercenter.http.ApiService
import com.yidian.shenghuoquan.bmanagercenter.http.callback.*
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.bmanagercenter.manager.LifeAccountManager
import com.yidian.shenghuoquan.bmanagercenter.ui.auth.LifeAccountAuthActivity
import com.yidian.shenghuoquan.bmanagercenter.ui.auth.LifeAccountEnterpriseAuthActivity
import com.yidian.shenghuoquan.bmanagercenter.ui.dialog.MerchantCenterBottomHintDialog
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountTitleView
import com.yidian.shenghuoquan.bmanagercenter.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 com.yidian.yac.core.zap.ZapTicket
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import timber.log.Timber

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

  /**
   * 当前生活号
   */
  private var curLifeAccount: LifeAccountItemBean.Response? = null

  /**
   * 功能入口-页面路由映射
   */
  private lateinit var functionPageMap: HashMap<Int, String>

  /**
   * 功能入口-页面参数映射
   */
  private lateinit var functionParamsMap: HashMap<Int, HashMap<String, Any>>

  /**
   * 当前生活号状态下功能集
   */
  private lateinit var functionPermissionList: ArrayList<Int>

  private val gson by lazy { Gson() }
  private val params by lazy {
    intent.getSerializableExtra(XRouterPathConstants.ParamsKey)?.let {
      it as HashMap<*, *>
    }
  }

  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() {
    // 由C端跳转此页面可返回
    if (JudgeClientUtils.judgeClient(packageName) == ClientType.MERCHANT_C) {
      viewBind.bvTopBar.setBackVisibility(true)
    } else {
      viewBind.bvTopBar.setBackVisibility(false)
    }
    // 此页面默认不显示切换主体
    viewBind.bvTopBar.setActionVisibility(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.lvLifeAccountTitle.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() {
    viewBind.rlRefresh.autoRefresh()
  }

  /**
   * 刷新商户管理中心相关数据
   */
  private fun refreshMerchantCenterData(
    lifeAccountData: LifeAccountItemBean.Response,
    configData: GetCommonConfigBean.Data
  ) {
    // 设置标签
    viewBind.lvLifeAccountTitle.isVisible = true
    viewBind.lvLifeAccountTitle.setLifeAccountData(lifeAccountData)
    // 设置钱包
    if (configData.merchantManagerCenter.isShowWallet == Constant.MERCHANT_SERVICE_SHOW) {
      viewBind.avMerchantAsset.isVisible = true
      viewBind.avMerchantAsset.setMerchantAssetData("0.00", "0.00")
    } else {
      viewBind.avMerchantAsset.isVisible = false
    }
    // 展示底部浮窗
    showMerchantCenterBottomHint(lifeAccountData)
    // 生成FunctionId和XPage页面节点映射
    ManagerCenterConfig.getFunctionPageMap(configData.merchantManagerCenter.items, JudgeClientUtils.judgeClient(packageName))
      ?.let { functionPageMap = it }
    // 生成FunctionId和跳转页面参数映射
    ManagerCenterConfig.getFunctionParamsMap(configData, curLifeAccount, JudgeClientUtils.judgeClient(packageName))?.let {
      functionParamsMap = it
    }
    // 生成当前生活号状态下的功能集
    ManagerCenterConfig.getFunctionPermissionMap(
      configData.merchantManagerCenter.items,
      LifeAccountManager.getLifeAccountTag(curLifeAccount?.tag?.tag_key),
      JudgeClientUtils.judgeClient(packageName)
    )?.let { functionPermissionList = it }
    // 过滤商户服务数据
    filterMerchantServiceData(configData.merchantManagerCenter.items)
  }

  /**
   * 展示商户管理中心底部浮窗
   * 判断是否提示认证升级或提示认证驳回
   * @param data 当前生活号数据
   */
  private fun showMerchantCenterBottomHint(data: LifeAccountItemBean.Response) {
    when (LifeAccountManager.getLifeAccountTag(data.tag.tag_key)) {
      LifeAccountManager.LifeAccountTag.LIFE_ACCOUNT_TAG_NOT_AUTH ->
        // 当前是个人未认证生活号 提示认证升级
        MerchantCenterBottomHintDialog(
          this,
          MerchantCenterBottomHintDialog.TYPE_AUTH_UPGRADE, this
        ).show()
      LifeAccountManager.LifeAccountTag.LIFE_ACCOUNT_TAG_AUTH_REJECT ->
        // 当前企业认证驳回 提示修改
        if (data.role_type != Constant.TYPE_ROLE_ORDINARY) {
          // 企业员工不显示
          MerchantCenterBottomHintDialog(
            this,
            MerchantCenterBottomHintDialog.TYPE_AUTH_REJECT, this
          ).show()
        }
    }
  }

  /**
   * 过滤商户服务数据
   * 目前处理 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 (LifeAccountManager.getLifeAccountTag(curLifeAccount?.tag?.tag_key) == LifeAccountManager.LifeAccountTag.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)
  }

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

  override fun onEnterLifeAccountInfo(lifeAccountId: String) {
    // 跳转生活号基本信息
    XPageManager.push(XRouterPathConstants.LIFE_ACCOUNT_INFO, null)
  }

  override fun onEnterLifeAccountAuthInfo(lifeAccountId: String) {
    // 跳转生活号认证信息 未认证跳转认证首页、认证驳回跳转企业认证页
    // 此处落地页和认证管理一致 故直接跳转认证管理页
    XPageManager.push(XRouterPathConstants.AUTH_MANAGEMENT, null)
  }

  override fun onUpgradeAuth() {
    // 未认证进行认证
    startAuth()
  }

  override fun onModifyEnterpriseAuth() {
    // 修改认证
    modifyAuth()
  }

  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,
          LifeAccountManager.getLifeAccountTag(curLifeAccount?.tag?.tag_key) == LifeAccountManager.LifeAccountTag.LIFE_ACCOUNT_TAG_AUTH_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]) }
    } else {
      // 若当前功能无权限 根据生活号类型做弹窗提示
      when (LifeAccountManager.getLifeAccountTag(curLifeAccount?.tag?.tag_key)) {
        LifeAccountManager.LifeAccountTag.LIFE_ACCOUNT_TAG_AUDIT_UNDER ->
          // 审核中 提示加急审核
          showHintDialog(
            resources.getString(R.string.audit_urgent),
            arrayListOf(resources.getString(R.string.close)),
            null, null, null, null
          )
        LifeAccountManager.LifeAccountTag.LIFE_ACCOUNT_TAG_AUTH_REJECT ->
          // 审核驳回 提示修改认证
          showHintDialog(
            resources.getString(R.string.auth_apply_reject),
            arrayListOf(resources.getString(R.string.close), resources.getString(R.string.modify_auth)),
            null, { modifyAuth() }, null, R.color.color_FF3A3A
          )
        LifeAccountManager.LifeAccountTag.LIFE_ACCOUNT_TAG_NOT_AUTH ->
          // 未认证 提示认证
          showHintDialog(
            resources.getString(R.string.auth_to_use_more_tool),
            arrayListOf(resources.getString(R.string.close), resources.getString(R.string.goto_auth)),
            null, { startAuth() }, null, null
          )
        LifeAccountManager.LifeAccountTag.LIFE_ACCOUNT_TAG_PERSONAL_AUTH ->
          // 个人认证 提示认证升级
          showHintDialog(
            resources.getString(R.string.upgrade_to_use_more_tool),
            arrayListOf(resources.getString(R.string.close), resources.getString(R.string.goto_upgrade)),
            null, { upgradeAuth() }, null, null
          )
      }
    }
  }

  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.lvLifeAccountTitle.setLifeAccountName(accountName)
      }
    }
  }

  override fun onRefresh(refreshLayout: RefreshLayout) {
    // 刷新数据
    // 请求TowerPro通用配置
    ZapTicket(ZapServiceNameConstants.GeneralAbilityService).withAction(ZapServiceActionConstants.ActionGetTowerProCommonConfig)
      .onResult { xResult ->
        val configResult = if (xResult.code == 0) {
          Timber.tag(Constant.LOG_TAG).i("get common config success, result: ${xResult.result}")
          gson.fromJson((xResult.result as JSONObject).toString(), GetCommonConfigBean.GetCommonConfigResponse::class.java)
        } else {
          Timber.tag(Constant.LOG_TAG).e("get common config fail, message: ${xResult.mesg}")
          viewBind.rlRefresh.finishRefresh(false)
          return@onResult
        }
        // 请求生活号列表
        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))
              requestLogout()
              return
            }
            lifeAccountResult?.let {
              // 切换主体入口是否展示判断
              viewBind.bvTopBar.setActionVisibility(it.size > 1)
            }
            val lifeAccountIdList = lifeAccountResult?.map { it.life_account_id }
            val curLifeAccountId = LifeAccountManager.getLifeAccountId()
            if (lifeAccountIdList?.contains(curLifeAccountId) == false) {
              // 当前选择的生活号已不存在则切换第一个生活号 目前为企业员工被解除关系会触发
              // C端开店赚钱生成未认证生活号进入管理中心会触发 curLifeAccountId为null且生活号列表只有一条数据
              curLifeAccount = lifeAccountResult[0]
              // 更新本地存储的生活号id
              LifeAccountManager.saveLifeAccountId(lifeAccountResult[0].life_account_id)
              // 刷新数据
              configResult?.data?.let { refreshMerchantCenterData(lifeAccountResult[0], it) }
              // C端开店赚钱直接跳转认证首页
              if (params?.let { it[IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_AUTH_FROM] as String } == LifeAccountAuthActivity.FROM_C) {
                XPageManager.push(
                  XRouterPathConstants.LIFE_ACCOUNT_AUTH,
                  hashMapOf(
                    IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_ID to curLifeAccount?.life_account_id
                  )
                )
              }
              return
            }
            lifeAccountResult?.forEach {
              if (curLifeAccountId == it.life_account_id) {
                curLifeAccount = it
                // 刷新数据
                configResult?.let { configData -> refreshMerchantCenterData(it, configData.data) }
              }
            }
          }

          override fun getLifeAccountListFailure(message: String?) {
            viewBind.rlRefresh.finishRefresh(false)
          }
        })
      }.onLost {
        Timber.tag(Constant.LOG_TAG).e("get common config fail, message: ${it.mesg}")
        viewBind.rlRefresh.finishRefresh(false)
      }.ship()
  }

  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))
  }

  private fun requestLogout() {
    ZapTicket(ZapServiceNameConstants.SettingService).withAction(ZapServiceActionConstants.ActionLogout)
      .onResult { result ->
        if (result.result as Boolean) {
          // 退出登录成功 跳转登录页面
          XPageManager.push(XRouterPathConstants.LOGIN_LIFE_CIRCLE, null)
        }
      }.ship()
  }

  /**
   * 提示弹窗
   * @param content 提示内容
   * @param options 操作项
   * @param leftOption 左操作项函数
   * @param rightOption 右操作项函数
   * @param leftBtnColor 左操作按钮文字颜色
   * @param rightBtnColor 右操作按钮文字颜色
   */
  private fun showHintDialog(
    content: String, options: ArrayList<String>,
    leftOption: (() -> Unit)?, rightOption: (() -> Unit)?,
    leftBtnColor: Int?, rightBtnColor: Int?
  ) {
    CommonHintDialog(
      this,
      content, options,
      object : CommonHintDialog.OnHintOptionCallback {
        override fun onLeftOption() {
          leftOption?.invoke()
        }

        override fun onRightOption() {
          rightOption?.invoke()
        }

      }, leftBtnColor, rightBtnColor
    ).show()
  }

  /**
   * 未认证 跳转认证首页
   */
  private fun startAuth() {
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_AUTH,
      hashMapOf(
        IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_AUTH_FROM to LifeAccountAuthActivity.FROM_B_MANAGER_CENTER,
        IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_ID to curLifeAccount?.life_account_id
      )
    )
  }

  /**
   * 认证修改 跳转企业认证修改
   */
  private fun modifyAuth() {
    // 请求商户认证检查
    ApiService.authMerchantCheck(
      this,
      hashMapOf(LifeAccountEnterpriseAuthActivity.EXTRA_LIFE_ACCOUNT_ID to curLifeAccount?.life_account_id)
    )
  }

  /**
   * 认证升级 跳转企业认证修改
   */
  private fun upgradeAuth() {
    // 请求商户认证检查
    ApiService.authMerchantCheck(
      this,
      hashMapOf(LifeAccountEnterpriseAuthActivity.EXTRA_LIFE_ACCOUNT_ID to curLifeAccount?.life_account_id)
    )
  }
}
