package com.zj365.health.act.datamanage

import android.annotation.SuppressLint
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.xty.base.act.BaseVmAct
import com.xty.common.TimeSelect
import com.xty.common.TimeUtils
import com.xty.common.arouter.ARouterUrl
import com.xty.common.util.CommonToastUtils
import com.xty.common.util.GetJsonDataUtil
import com.xty.common.util.JsonBean
import com.xty.common.weight.AreaSelectDialog
import com.zj365.health.R
import com.zj365.health.databinding.ActBaseInfoBinding
import com.zj365.health.vm.BaseInfoVm
import com.zj365.health.weight.EatTypeDialog
import com.xty.network.model.SettingBean
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import java.text.SimpleDateFormat
import java.util.Calendar

@SuppressLint("SimpleDateFormat")
@Route(path = ARouterUrl.DATA_MANAGE_BASE_INFO)
class DataManageBaseInfoAct : BaseVmAct<BaseInfoVm>() {

    private val binding by lazy { ActBaseInfoBinding.inflate(layoutInflater) }
    override fun setLayout(): View = binding.root

    private val MSG_LOAD_DATA = 0x0001
    private val MSG_LOAD_SUCCESS = 0x0002
    private val MSG_LOAD_FAILED = 0x0003

    private var selectNationKey: String = ""
    private var selectNationValue: String = ""
    private val timeSelect by lazy {
        TimeSelect(this) {}.apply {
            val dataStr = binding.mBirthday.text.toString()
            val dateCalendar = Calendar.getInstance()
            if (dataStr.isNotEmpty()) {
                val date = SimpleDateFormat("yyyy-MM-dd").parse(dataStr)
                dateCalendar.time = date
                selectedDate = dateCalendar
            }
        }
    }
    private val nationSelect by lazy {
        EatTypeDialog(this, "民族", "取消", "确定") { selectValue, selectKey ->
            selectNationKey = selectKey
            selectNationValue = selectValue

            binding.tvNationName.text = selectKey
        }
    }

    var userInfo: SettingBean.User? = null

    private var areaSelectDialog: AreaSelectDialog? = null//地区选择弹窗
    private val options1Items = ArrayList<String>() //一级菜单数据

    private val options2Items = ArrayList<ArrayList<String>>() //二级菜单数据
    private val options3Items = ArrayList<ArrayList<ArrayList<String>>>() //三级菜单数据
    private var open_province: String? = null
    private var open_city: String? = null//选中的省 市 code
    private var open_area: String? = null

    override fun liveObserver() {
        mViewModel.nationData.observe(this) {
            nationSelect.setNationWheelViewData(it.data, selectNationKey)
        }

        mViewModel.updateSuccess.observe(this) {
            EventBus.getDefault().post(it.data)
            CommonToastUtils.showSucceedToast("保存成功")
            finish()
        }
    }

    override fun initData() {
        super.initData()
        mHandler.sendEmptyMessage(MSG_LOAD_DATA) //进入这个页面就解析json数据
        userInfo = intent.getSerializableExtra("userInfo") as SettingBean.User?
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener { finish() }
        binding.title.mTvTitle.text = "基础信息"

        mViewModel.getNation()

        binding.llBirthdayLayout.setOnClickListener {
            timeSelect.selectTime(binding.mBirthday)
        }

        binding.llNationLayout.setOnClickListener {
            nationSelect.show()
        }

        areaSelectDialog = AreaSelectDialog(
            this,
            R.layout.dialog_areaselect_layout,
            "请选择区域",
            intArrayOf(),
            options1Items,
            options2Items,
            options3Items
        )
        binding.llCity.setOnClickListener {
            areaSelectDialog!!.setOnClickListener { string ->
                //拿到省市区的字符串回调 需要将字符串以"|"进行切割
                val str = string.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                    .toTypedArray()
                Log.e("Log", "str的长度=" + str.size)
                open_province = str[0] //表示省
                open_city = str[1] //市
                open_area = str[2] //取
                binding.llCity.postDelayed({
                    binding.mArea.text = "$open_province $open_city $open_area"
                }, 10)
            }
            areaSelectDialog!!.show()
        }

        binding.mSubmit.setOnClickListener {
            val name = binding.mName.text.toString()
            if (name.isEmpty()) {
                CommonToastUtils.showToast("请输入姓名")
                return@setOnClickListener
            }

            val sex = if (binding.checkSex.isChecked) 2 else 1
            val birthdayType = if (binding.checkBirthday.isChecked) 2 else 1
            val birthday = binding.mBirthday.text.toString()
            val nation = binding.tvNationName.text.toString()
            val height = binding.mHeight.text.toString()
            val weight = binding.mWeight.text.toString()
            val wait = binding.mYao.text.toString()
            val hobby = binding.etHobby.text.toString()
            val reglition = binding.mReligion.text.toString()

            if (birthday.isEmpty()) {
                CommonToastUtils.showToast("请输入出生日期")
                return@setOnClickListener
            }

            if (height.isEmpty()) {
                CommonToastUtils.showToast("请输入身高")
                return@setOnClickListener
            }

            if (height.toFloat() < 50 || height.toFloat() > 260) {
                CommonToastUtils.showToast("请输入正确身高")
                return@setOnClickListener
            }

            if (weight.isEmpty()) {
                CommonToastUtils.showToast("请输入体重")
                return@setOnClickListener
            }

            if (weight.toFloat() < 3 || weight.toFloat() > 300) {
                CommonToastUtils.showToast("请输入正确体重")
                return@setOnClickListener
            }

            if (TimeUtils.getAgeByBirth(birthday) < 14) {
                CommonToastUtils.showToast("需要年满14岁才可使用")
                return@setOnClickListener
            }
            userInfo?.apply {
                mViewModel.saveInfo(
                    id,
                    name,
                    sex,
                    birthdayType,
                    birthday,
                    nation,
                    height,
                    weight,
                    wait,
                    open_city,
                    open_province,
                    open_area,
                    hobby,
                    reglition
                )
            }
        }

        userInfo?.apply {
            binding.mName.setText(name)
            binding.checkSex.isChecked = sex == 2
            binding.checkBirthday.isChecked = birthdayType == 2
            binding.mBirthday.text = birthday
            binding.tvNationName.text = nation
            binding.mHeight.setText("$height")
            binding.mWeight.setText("$weight")
            if (waistline != 0f) {
                binding.mYao.setText("$waistline")
            }
            binding.mArea.text = "${province ?: ""} ${city ?: ""} ${district ?: ""}"
            binding.etHobby.setText(hobby)
            binding.mReligion.setText(religion)
            selectNationKey = nation
        }
    }

    fun parseData(result: String): ArrayList<JsonBean> {
        val detail = ArrayList<JsonBean>()
        try {
            val data = JSONArray(result)
            val gson = Gson()
            for (i in 0 until data.length()) {
                val entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean::class.java)
                detail.add(entity)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED)
        }
        return detail
    }

    private fun initJsonData() {
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         */
        val jsonData = GetJsonDataUtil().getJson(this, "province.json") // 获取assets目录下的json文件数据
        val jsonBean = parseData(jsonData) // 用Gson 转成实体
        for (i in jsonBean.indices) { // 遍历省份
            /**
             * 添加省份数据
             */
            options1Items.add(jsonBean[i].pickerViewText)
            val cityList = ArrayList<String>() // 该省的城市列表（第二级）
            val provinceAreaList = ArrayList<ArrayList<String>>() // 该省的所有地区列表（第三极）
            for (c in jsonBean[i].cityList.indices) { // 遍历该省份的所有城市
                val cityName = jsonBean[i].cityList[c].name
                cityList.add(cityName) // 添加城市
                val cityAreaList = ArrayList<String>() // 该城市的所有地区列表

                // 如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean[i].cityList[c].area == null
                    || jsonBean[i].cityList[c].area.isEmpty()
                ) {
                    cityAreaList.add("")
                } else {
                    cityAreaList.addAll(jsonBean[i].cityList[c].area)
                }
                provinceAreaList.add(cityAreaList) // 添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(cityList)
            /**
             * 添加地区数据
             */
            options3Items.add(provinceAreaList)
            /**
             * 添加地区数据
             */
            mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS)
        }
    }

    private var thread: Thread? = null

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MSG_LOAD_DATA -> {
                    if (thread == null) { // 如果已创建就不再重新创建子线程了
                        Log.e("Log", "Begin Parse Data")
                        thread = Thread {
                            // 子线程中解析省市区数据
                            initJsonData()
                        }
                        thread?.start()
                    }
                }

                MSG_LOAD_SUCCESS -> {
                    Log.e("Log", "Parse Succeed")
                    if (areaSelectDialog == null) {
                        areaSelectDialog = AreaSelectDialog(
                            this@DataManageBaseInfoAct,
                            R.layout.dialog_areaselect_layout,
                            "请选择地址",
                            intArrayOf(),
                            options1Items,
                            options2Items,
                            options3Items
                        )
                    }
                }

                MSG_LOAD_FAILED -> Log.e("Log", "Parse Failed")
                4 -> binding.mArea.text = "$open_province $open_city $open_area"
            }
        }
    }
}