package com.casic.br.view

import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import com.casic.br.R
import com.casic.br.utils.DeserializeModel
import com.casic.br.utils.LoadingDialogHub
import com.casic.br.vm.AddressViewModel
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.contract.OnAddressPickedListener
import com.github.gzuliyujiang.wheelpicker.entity.CityEntity
import com.github.gzuliyujiang.wheelpicker.entity.CountyEntity
import com.github.gzuliyujiang.wheelpicker.entity.ProvinceEntity
import com.github.gzuliyujiang.wheelpicker.utility.AddressJsonParser
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.convertColor
import com.pengxh.kt.lite.extensions.show
import com.pengxh.kt.lite.extensions.sp2px
import com.pengxh.kt.lite.utils.Constant
import com.pengxh.kt.lite.utils.ImmerseStatusBarUtil
import com.pengxh.kt.lite.vm.LoadState
import kotlinx.android.synthetic.main.activity_address.*
import kotlinx.android.synthetic.main.include_base_title.*

class AddressActivity : KotlinBaseActivity(), OnAddressPickedListener {

    private val kTag = "AddAddressActivity"
    private var id: String? = null
    private lateinit var addressViewModel: AddressViewModel

    override fun initLayoutView(): Int = R.layout.activity_address

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        ImmerseStatusBarUtil.setColor(this, R.color.white.convertColor(this))

        leftBackView.setOnClickListener { finish() }
    }

    override fun initData() {
        id = intent.getStringExtra(Constant.INTENT_PARAM)
        if (id == null) {
            titleView.text = "新建地址"
        } else {
            titleView.text = "更新地址"
        }
        addressViewModel = ViewModelProvider(this)[AddressViewModel::class.java]
    }

    override fun initEvent() {
        addressView.setOnClickListener {
            val addressPicker = AddressPicker(this)
            addressPicker.setAddressMode(
                "china_city_data.json", AddressMode.PROVINCE_CITY_COUNTY,
                AddressJsonParser.Builder()
                    .provinceCodeField("code")
                    .provinceNameField("name")
                    .provinceChildField("city")
                    .cityCodeField("code")
                    .cityNameField("name")
                    .cityChildField("area")
                    .countyCodeField("code")
                    .countyNameField("name")
                    .build()
            )
            addressPicker.setDefaultValue("北京市", "市辖区", "海淀区")
            addressPicker.setOnAddressPickedListener(this)
            val layout = addressPicker.wheelLayout
            layout.setTextSize(14f.sp2px(this).toFloat())
            layout.setSelectedTextSize(16f.sp2px(this).toFloat())
            layout.setSelectedTextColor(Color.BLUE)
            layout.setSelectedTextBold(true)
            layout.setOnLinkageSelectedListener { first, second, third ->
                addressPicker.titleView.text = String.format(
                    "%s%s%s",
                    addressPicker.firstWheelView.formatItem(first),
                    addressPicker.secondWheelView.formatItem(second),
                    addressPicker.thirdWheelView.formatItem(third)
                )
                addressPicker.titleView.setTextColor(Color.BLUE)
            }
            addressPicker.show()
        }

        saveAddressButton.setOnClickListener {
            if (addressView.text.isNullOrBlank()) {
                "请先选择地区".show(this)
                return@setOnClickListener
            }
            if (streetView.text.isNullOrBlank()) {
                "请输入街道或者楼牌号地址".show(this)
                return@setOnClickListener
            }
            if (postalCodeView.text.isNullOrBlank()) {
                "请输入邮政编码".show(this)
                return@setOnClickListener
            }

            val split = addressView.text.split("-")
            val userModel = DeserializeModel.getUserModel()!!
            if (id == null) {
                //新增地址
                addressViewModel.addAddress(
                    userModel.phone,
                    split[0],
                    split[1],
                    split[2],
                    streetView.text.toString(),
                    "${split[0]}${split[1]}${split[2]}${streetView.text.toString()}",
                    postalCodeView.text.toString()
                )
            } else {
                //修改地址
                addressViewModel.updateAddressById(
                    id!!,
                    userModel.phone,
                    split[0],
                    split[1],
                    split[2],
                    streetView.text.toString(),
                    "${split[0]}${split[1]}${split[2]}${streetView.text.toString()}",
                    postalCodeView.text.toString()
                )
            }
        }
    }

    override fun onAddressPicked(
        province: ProvinceEntity?, city: CityEntity?, county: CountyEntity?
    ) {
        addressView.text = String.format("%s-%s-%s", province?.name, city?.name, county?.name)
    }

    override fun observeRequestState() {
        addressViewModel.loadState.observe(this, {
            when (it) {
                LoadState.Loading -> {
                    LoadingDialogHub.show(this, "地址保存中...")
                }
                LoadState.Success -> {
                    LoadingDialogHub.dismiss()
                    finish()
                }
                else -> LoadingDialogHub.dismiss()
            }
        })
    }
}