package com.yidian.shenghuoquan.bmanagercenter.ui.auth

import android.os.Bundle
import com.google.gson.Gson
import com.yidian.bcommon.constant.XEventConfig
import com.yidian.bcommon.constant.XRouterPathConstants.Companion.CHOOSE_CAREER
import com.yidian.bcommon.base.BaseActivity
import com.yidian.bcommon.extensions.initTitleBar
import com.yidian.bcommon.services.XEventService
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.adapter.FirstCareerListAdapter
import com.yidian.shenghuoquan.bmanagercenter.adapter.SecondCareerListAdapter
import com.yidian.shenghuoquan.bmanagercenter.bean.CareerListBean
import com.yidian.shenghuoquan.bmanagercenter.databinding.ActivityChooseCareerBinding
import com.yidian.shenghuoquan.bmanagercenter.utils.JsonUtils
import com.yidian.xarc.xevent.XBaseEvent
import com.yidian.xpage.XPageManager


/**
 * 选择职业标签
 */
class ChooseCareerActivity : BaseActivity<ActivityChooseCareerBinding>() {

  private var firstCareer = arrayListOf<String>()
  private var secondCareer = arrayListOf<String>()

  private val firstListAdapter: FirstCareerListAdapter by lazy { FirstCareerListAdapter() }
  private val secondListAdapter: SecondCareerListAdapter by lazy { SecondCareerListAdapter() }

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

  override fun getXPageName(): String {
    return CHOOSE_CAREER
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    initView()
  }

  private fun initView() {
    initTitleBar(viewBind.include.toolbar, viewBind.include.tvTitle, resources.getString(R.string.choose_career))
    viewBind.rvListFirst.adapter = firstListAdapter
    viewBind.rvListSecond.adapter = secondListAdapter

    // 解析本地json数据
    val jsonStr = JsonUtils.file2JsonStr(this, "Career.json")
    val gson = Gson()
    val beanList: CareerListBean = gson.fromJson(jsonStr, CareerListBean::class.java)
    // 赋值给一级职业分类
    beanList.forEach {
      firstCareer.add(it.category)
    }
    // 二级列表默认值
    secondCareer.addAll(beanList[0].list)
    // 赋值给适配器
    firstListAdapter.setList(firstCareer)
    secondListAdapter.setList(secondCareer)

    firstListAdapter.setOnItemClickListener { _, _, position ->
      secondListAdapter.setList(beanList[position].list)
      firstListAdapter.setSelectedIndex(position)
    }
    secondListAdapter.setOnItemClickListener { adapter, _, position ->
      secondListAdapter.setSelectedIndex(position)
      val secondCareer = adapter.data[position] as String
      // 回传选择的职业
      val event = XBaseEvent(XEventConfig.CHOOSE_CAREER, secondCareer)
      XEventService.postEvent(event)
      XPageManager.pop(null)
    }
  }

}
