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.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshListener
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.*
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.utils.StorageUtil
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, MerchantSwitchDialog.OnMerchantSwitchCallback,
  LifeAccountLabelView.OnLifeAccountLabelCallback, IGetLifeAccountInfoByIdCallback,
  MerchantCenterBottomHintDialog.OnMerchantCenterBottomHintCallback, IAuthMerchantCheckCallback,
  MerchantServiceFunctionAdapter.OnItemClickListener, CommonTopBarView.OnCommonTopBarActionCallback, OnRefreshListener,
  IUserLogoutCallBack {

  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 curConfigData by lazy { ArrayList<GetConfigListBean.Item>() }

  /**
   * 功能-页面表
   */
  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")

    // 服务列表展示
    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.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.lvLifeAccountLabel.setLifeAccountData(curLifeAccount)
    // 展示底部浮窗
    showMerchantCenterBottomHint(curLifeAccount)
    // 请求功能入口配置清单
    ApiService.getConfigList(this)
  }

  /**
   * 刷新商户管理中心相关数据
   */
  private fun refreshMerchantCenterData(data: LifeAccountItemBean.Response) {
    // 设置标签
    viewBind.lvLifeAccountLabel.setLifeAccountData(data)
    // 展示底部浮窗
    showMerchantCenterBottomHint(data)
    // 生活号状态变更 生成当前生活号状态下的功能集
    generateFunctionPermissionMap(curConfigData)
    // 生活号状态变更 过滤商户服务数据
    filterMerchantServiceData(curConfigData)
  }

  /**
   * 展示商户管理中心底部浮窗
   * 判断是否提示认证升级或提示认证驳回
   * @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页面节点映射
   * todo Activity传参
   */
  private fun generateFunctionPageMap(data: List<GetConfigListBean.Item>) {
    // 我要发布-优惠券
    functionPageMap[data[0].functions[0].function_id] = null
    // 我要发布-招聘
    functionPageMap[data[0].functions[1].function_id] = null
    // 管理服务-权限管理
    functionPageMap[data[1].functions[0].function_id] = null
    // 管理服务-人员管理
    functionPageMap[data[1].functions[1].function_id] = XRouterPathConstants.PERSONAL_MY_STAFF
    // 其他服务-优惠券管理
    functionPageMap[data[2].functions[0].function_id] = null
    // 其他服务-职位管理
    functionPageMap[data[2].functions[1].function_id] = null
    // 其他服务-门店管理
    functionPageMap[data[2].functions[2].function_id] = null
    // 其他服务-系统设置
    functionPageMap[data[2].functions[3].function_id] = XRouterPathConstants.SYSTEM_SETTING
  }

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

  /**
   * 过滤商户服务数据
   * 目前处理个人认证状态下和企业员工角色下不展示管理服务
   */
  private fun filterMerchantServiceData(data: List<GetConfigListBean.Item>) {
    val result = ArrayList<GetConfigListBean.Item>(data.size)
    data.let {
      (it as ArrayList<GetConfigListBean.Item>).iterator().apply {
        while (hasNext()) {
          val group = next()
          if (group.group_id == Constant.MERCHANT_SERVICE_GROUP_MANAGEMENT) {
            // 个人认证或企业员工不展示管理服务
            if (getCurLifeAccountLabel() == Constant.LIFE_ACCOUNT_TAG_PERSONAL_AUTH || curLifeAccount.role_type == Constant.TYPE_ROLE_ORDINARY) {
              continue
            }
          }
          result.add(group)
        }
      }
    }
    (viewBind.rvServiceGroup.adapter as MerchantServiceGroupAdapter).updateData(result)
  }

  /**
   * 获取当前生活号标签
   * 目前不支持区分个体工商户和普通企业
   */
  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 getConfigListSuccess(result: GetConfigListBean.Response?) {
    result?.let {
      // 备份配置数据
      curConfigData.addAll(it.merchant_manager_center.items)
      generateFunctionPageMap(it.merchant_manager_center.items)
      generateFunctionPermissionMap(it.merchant_manager_center.items)
      filterMerchantServiceData(it.merchant_manager_center.items)
    }
  }

  override fun getConfigListFailure(message: String?) {

  }

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

      override fun getLifeAccountListFailure(message: String?) {
        // 刷新失败
        refreshLayout.finishRefresh(false)
      }
    })
  }

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