package com.zj365.dc.activity

import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.RxKeyboardTool
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.arouter.RouteManager
import com.xty.common.event.MyInfoEvent
import com.xty.common.picture.PictureUtils
import com.xty.common.setImage
import com.xty.common.util.CommonToastUtils
import com.zj365.dc.R
import com.zj365.dc.databinding.ActInfoSimpleBinding
import com.zj365.dc.vm.InfoSimpleVm
import org.greenrobot.eventbus.EventBus
import java.util.regex.Pattern

/**
 * 基本信息
 * 简单信息填写
 */
@Route(path = ARouterUrl.INFO_SIMPLE)
class InfoSimpleAct : BaseVmAct<InfoSimpleVm>() {

    val binding by lazy { ActInfoSimpleBinding.inflate(layoutInflater) }
    override fun setLayout() = binding.root

    private var isBinding: Boolean = false
    private var sexType = 1
    private var birthdayType = 1

    var phone: String = ""
    private var pwd: String = ""

    private val timeSelect by lazy { TimeSelect(this) {} }
    private val textListener by lazy {
        object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                binding.mName.removeTextChangedListener(this)
                val str = s.toString().trim()
                if (str.isNotEmpty()) {
                    val isNum = Pattern.matches("[0-9]", str.substring(0, 1))
                    if (isNum) {
                        if (str.length > 2) {
                            binding.mName.setText(str.substring(1, str.length))
                        } else {
                            binding.mName.setText("")
                        }
                        CommonToastUtils.showToast(R.string.name_first_num)
                    }
                }
                binding.mName.addTextChangedListener(this)
            }
        }
    }

    override fun initData() {
        super.initData()
        isDarkBar = true
        phone = intent.getStringExtra("phone").toString()
        pwd = intent.getStringExtra("password").toString()
    }

    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mTvTitle.text = getString(R.string.base_info)
        binding.title.mIvBack.setOnClickListener { finish() }
        binding.mImage.setOnClickListener { PictureUtils.openCamera(this) }
        timeSelect.startDate.set(1922, 0, 1)
        binding.llBirthday.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timeSelect.selectTime(binding.mBirthday)
        }
        sexType = if (binding.checkSex.isChecked) 2 else 1
        birthdayType = if (binding.checkBirthday.isChecked) 2 else 1
        binding.bindingTv.setOnClickListener {
            isBinding = true
            turnToSaveBaseData()


        }
        binding.mName.addTextChangedListener(textListener)

        binding.mSubmit.setOnClickListener {
            isBinding = false
            turnToSaveBaseData()
        }
    }

    /**
     * 调用接口保存
     */
    private fun turnToSaveBaseData() {

        val birthDay = binding.mBirthday.text.toString().trim()
        val name = binding.mName.text.toString().trim()
        if (TimeUtils.getAgeByBirth(birthDay) < 14) {
            CommonToastUtils.showToast("需要年满14岁才可使用")
            isBinding = false
            return
        }
        val avatar = binding.mImage.tag
        val datanal = avatar?.toString() ?: ""
        val sexValue = if (binding.checkSex.isChecked) "2" else "1"
        birthdayType = if (binding.checkBirthday.isChecked) 2 else 1
        //调用接口
        if (name.trim().isEmpty()) {
            mViewModel.submit(datanal, null, sexValue, birthdayType.toString(), birthDay)
        } else {
            mViewModel.submit(datanal, name, sexValue, birthdayType.toString(), birthDay)
        }
    }

    override fun liveObserver() {
        mViewModel.setBasic.observe(this) {

            //不管点击绑定还是完成都会去登录
            EventBus.getDefault().post(MyInfoEvent())
            mViewModel.login(phone, pwd)

            if (isBinding) {
                return@observe
            }
            CommonToastUtils.showSucceedToast("信息设置成功")
        }

        mViewModel.mLogin.observe(this) {
            //登录成功请求用户token
            mViewModel.getImUserSig("user_${it.data.id}")
        }

        mViewModel.getImUserSig.observe(this) {
            Log.e("simon", "login" + it.data)
            /*TUILogin.login(
                applicationContext,
                0,
                it.paramsData,
                it.data,
                object : TUICallback() {
                    override fun onSuccess() {
                        Log.e("simon", "onSuccess")
                        if (!isBinding) { //如果是直接点击完成，跳转到主页面
                            ARouter.getInstance().build(ARouterUrl.MAIN_ACT).navigation()
                            RxActivityTool.finishAllActivity()
                        } else { //如果是去绑定设备，跳转到设备选择界面，同是给予标记，告诉该界面已经登录
                            bundle.clear()
                            bundle.putBoolean("isLogin", true)
                            RouteManager.goAct(ARouterUrl.DEVICE_CHOICE, bundle)
                        }
                    }

                    override fun onError(errorCode: Int, errorMessage: String?) {
                        Log.e("simon", "onError")
                    }
                })*/
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode === RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    var result = PictureSelector.obtainMultipleResult(data)
                    if (result.size > 0) {
                        var path = if (result[0].compressPath.isEmpty()) {
                            result[0].androidQToPath
                        } else {
                            result[0].compressPath
                        }
                        binding.mImage.setImage(this, path)
                        binding.mImage.tag = path
                    }
                }

                1000 -> {
                    finish()
                }
            }
        }
    }
}