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.HintOptionBean
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.utils.StorageUtil
import com.yidian.bcommon.widget.dialog.HintDialog
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.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.CommonTopBarView
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountLabelView
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,
  LifeAccountLabelView.OnLifeAccountLabelCallback, MerchantCenterBottomHintDialog.OnMerchantCenterBottomHintCallback,
  IAuthMerchantCheckCallback, MerchantServiceFunctionAdapter.OnItemClickListener, CommonTopBarView.OnCommonTopBarActionCallback,
  OnRefreshListener, DialogInterface.OnShowListener, DialogInterface.OnDismissListener {

  companion object {
    const val PARAMS_LIFE_ACCOUNT_ID = "life_account_id"
  }

  /**
   * 当前生活号
   */
  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() }

  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.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() {
    viewBind.rlRefresh.autoRefresh()
  }

  /**
   * 刷新商户管理中心相关数据
   */
  private fun refreshMerchantCenterData(
    lifeAccountData: LifeAccountItemBean.Response,
    configData: GetCommonConfigBean.Data
  ) {
    // 设置标签
    viewBind.lvLifeAccountLabel.isVisible = true
    viewBind.lvLifeAccountLabel.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,
      getCurLifeAccountLabel(),
      JudgeClientUtils.judgeClient(packageName)
    )?.let { functionPermissionList = it }
    // 过滤商户服务数据
    filterMerchantServiceData(configData.merchantManagerCenter.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()
    }
  }

  /**
   * 过滤商户服务数据
   * 目前处理 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) {
    // 跳转生活号基本信息
    XPageManager.push(XRouterPathConstants.LIFE_ACCOUNT_INFO, null)
  }

  override fun onUpgradeAuth() {
    // 由未认证升级认证 跳转认证首页
    XPageManager.push(
      XRouterPathConstants.LIFE_ACCOUNT_AUTH,
      hashMapOf(
        Pair(IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_AUTH_FROM, LifeAccountAuthActivity.FROM_B_MANAGER_CENTER),
        Pair(IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_ID, curLifeAccount?.life_account_id)
      )
    )
  }

  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]) }
    } 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(IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_AUTH_FROM, LifeAccountAuthActivity.FROM_B_MANAGER_CENTER),
                  Pair(IntentConstants.KEY_EXTRA_LIFE_ACCOUNT_ID, curLifeAccount?.life_account_id)
                )
              )
            }

          }).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通用配置
    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 = StorageUtil.getLifeAccountId()
            if (lifeAccountIdList?.contains(curLifeAccountId) == false) {
              // 当前选择的生活号已不存在则切换第一个生活号 目前为企业员工被解除关系会触发
              // C端开店赚钱生成未认证生活号进入管理中心会触发 curLifeAccountId为null且生活号列表只有一条数据
              curLifeAccount = lifeAccountResult[0]
              // 更新本地存储的生活号id
              StorageUtil.putLifeAccountId(lifeAccountResult[0].life_account_id)
              // 刷新数据
              configResult?.data?.let { refreshMerchantCenterData(lifeAccountResult[0], it) }
              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()
  }
}
