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

import android.os.Bundle
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.yidian.common.XEventConfig
import com.yidian.common.XRouterPathConstants
import com.yidian.common.base.BaseActivity
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.IAuthMerchantCheckCallback
import com.yidian.shenghuoquan.newscontent.http.callback.IGetConfigListCallback
import com.yidian.shenghuoquan.newscontent.http.callback.IGetLifeAccountInfoByIdCallback
import com.yidian.shenghuoquan.newscontent.http.callback.IGetLifeAccountListCallback
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.GetConfigListBean
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.widget.CommonTopBarView
import com.yidian.shenghuoquan.newscontent.widget.LifeAccountLabelView
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>(),
  IGetConfigListCallback, IGetLifeAccountListCallback, MerchantSwitchDialog.OnMerchantSwitchCallback,
  LifeAccountLabelView.OnLifeAccountLabelCallback, IGetLifeAccountInfoByIdCallback,
  MerchantCenterBottomHintDialog.OnMerchantCenterBottomHintCallback, IAuthMerchantCheckCallback,
  MerchantServiceFunctionAdapter.OnItemClickListener, CommonTopBarView.OnCommonTopBarActionCallback {

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

    // 本期需求无资产功能 仅做UI展示
    viewBind.avMerchantAsset.setMerchantAssetData("8856.88", "675.00")
  }

  private fun initListener() {
    viewBind.lvLifeAccountLabel.setOnLifeAccountLabelCallback(this)
  }

  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.lvLifeAccountLabel.setLifeAccountData(curLifeAccount)

    // 请求功能入口配置清单
    ApiService.getConfigList(this)

    // 判断是否提示升级企业认证或提示认证驳回
    if (curLifeAccount.life_account_type == Constant.TYPE_LIFE_ACCOUNT_PERSONAL && curLifeAccount.life_account_auth_status == Constant.STATUS_AUTH_FINISH) {
      // 当前是个人已认证生活号 提示升级
      MerchantCenterBottomHintDialog(
        this,
        MerchantCenterBottomHintDialog.TYPE_AUTH_UPGRADE, this
      ).show()
    }
    if (curLifeAccount.enterprise_audit_status == Constant.STATUS_AUDIT_REJECT) {
      // 当前企业认证驳回 提示修改
      MerchantCenterBottomHintDialog(
        this,
        MerchantCenterBottomHintDialog.TYPE_AUTH_REJECT, this
      ).show()
    }
  }

  /**
   * 生成FunctionId和XPage页面节点映射
   * todo Activity传参
   */
  private fun generateFunctionPageMap(data: GetConfigListBean.Response) {
    // 我要发布-优惠券
    functionPageMap[data.merchant_manager_center.items[0].functions[0].function_id] = null
    // 我要发布-招聘
    functionPageMap[data.merchant_manager_center.items[0].functions[1].function_id] = null
    // 管理服务-权限管理
    functionPageMap[data.merchant_manager_center.items[1].functions[0].function_id] = null
    // 管理服务-人员管理
    functionPageMap[data.merchant_manager_center.items[1].functions[1].function_id] =
      XRouterPathConstants.PERSONAL_MY_STAFF
    // 其他服务-优惠券管理
    functionPageMap[data.merchant_manager_center.items[2].functions[0].function_id] = null
    // 其他服务-职位管理
    functionPageMap[data.merchant_manager_center.items[2].functions[1].function_id] = null
    // 其他服务-门店管理
    functionPageMap[data.merchant_manager_center.items[2].functions[2].function_id] =
      XRouterPathConstants.STORE_MANAGEMENT
    // 其他服务-系统设置
    functionPageMap[data.merchant_manager_center.items[2].functions[3].function_id] =
      XRouterPathConstants.SYSTEM_SETTING
  }

  /**
   * 对应生活号权限下的功能集
   * @param tagKey 生活号认证类型/状态
   * todo 优化逻辑
   */
  private fun generateFunctionPermissionMap(data: GetConfigListBean.Response, tagKey: Int) {
    when (tagKey) {
      Constant.LIFE_ACCOUNT_TAG_COMMON_ENTERPRISE_AUTH -> {
        // 普通企业认证
        // 所有服务都可用
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[0].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[1].functions[0].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[1].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[0].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[2].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[3].function_id)
      }
      Constant.LIFE_ACCOUNT_TAG_INDIVIDUAL_BUSINESS_AUTH -> {
        // 个体工商户认证
        // 所有服务都可用
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[0].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[1].functions[0].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[1].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[0].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[2].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[3].function_id)
      }
      Constant.LIFE_ACCOUNT_TAG_PERSONAL_AUTH -> {
        // 个人认证
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[1].function_id)
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[3].function_id)
      }
      Constant.LIFE_ACCOUNT_TAG_NOT_AUTH -> {
        // 未认证
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[3].function_id)
      }
      Constant.LIFE_ACCOUNT_TAG_AUDIT_UNDER -> {
        // 审核中
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[2].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[3].function_id)
      }
      Constant.LIFE_ACCOUNT_TAG_AUTH_REJECT -> {
        // 认证驳回
        // 我要发布-招聘 其他服务-职位管理 其他服务-系统设置
        functionPermissionList.add(data.merchant_manager_center.items[0].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[1].function_id)
        functionPermissionList.add(data.merchant_manager_center.items[2].functions[3].function_id)
      }
    }
  }

  override fun getConfigListSuccess(result: GetConfigListBean.Response?) {
    result?.let {
      generateFunctionPageMap(it)
      generateFunctionPermissionMap(it, curLifeAccount.tag.tag_key)
    }
    viewBind.rvServiceGroup.layoutManager =
      LinearLayoutManager(this)
    viewBind.rvServiceGroup.addItemDecoration(MerchantServiceGroupAdapter.MerchantServiceGroupItemDecorator())
    viewBind.rvServiceGroup.adapter =
      MerchantServiceGroupAdapter(this, result?.merchant_manager_center?.items, this)
  }

  override fun getConfigListFailure(message: String?) {

  }

  override fun getLifeAccountListSuccess(result: ArrayList<LifeAccountItemBean.Response>?) {
    // 生活号列表请求成功 弹出切换主体弹窗
    result?.let { MerchantSwitchDialog(this, curLifeAccount.life_account_id, it, this).show() }
  }

  override fun getLifeAccountListFailure(message: String?) {

  }


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

  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 onUpgradeEnterpriseAuth() {
    // 升级企业认证 先请求企业认证信息
    ApiService.authMerchantCheck(
      this,
      hashMapOf(
        Pair(
          MerchantInfoActivity.PARAMS_LIFE_ACCOUNT_ID,
          curLifeAccount.life_account_id
        )
      )
    )
  }

  override fun onModifyEnterpriseAuth() {
    // 修改企业认证 先请求企业认证信息
    ApiService.authMerchantCheck(
      this,
      hashMapOf(
        Pair(
          MerchantInfoActivity.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)
      )
    )
  }

  override fun authMerchantCheckFailure(message: String?) {

  }

  override fun onItemClick(view: View, position: Int, data: GetConfigListBean.Function) {
    // 选择某一个功能
    // 若在当前权限功能集中则跳转指定页
    if (functionPermissionList.contains(data.function_id)) {
      functionPageMap[data.function_id]?.let { XPageManager.push(it, null) } ?: 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(this)
  }

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