package com.zj365.mime.act

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.gson.Gson
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.mylhyl.acp.Acp
import com.mylhyl.acp.AcpListener
import com.mylhyl.acp.AcpOptions
import com.tamsiree.rxkit.RxKeyboardTool
import com.tamsiree.rxkit.RxRegTool
import com.xty.base.act.BaseVmAct
import com.xty.base.weight.GpsToastDialog
import com.xty.base.weight.TipDialog
import com.xty.common.Const
import com.xty.common.LogUtils
import com.xty.common.MMkvHelper
import com.xty.common.TimeSelect
import com.xty.common.TimeUtils
import com.xty.common.aMapUtils.AmapInit
import com.xty.common.arouter.ARouterUrl
import com.xty.common.arouter.RouteManager
import com.xty.common.bracelet.isGpsOpen
import com.xty.common.event.MyInfoEvent
import com.xty.common.picture.PictureUtils
import com.xty.common.setImage
import com.xty.common.setImageUser
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.mime.R
import com.zj365.mime.databinding.ActBaseInfoChangeBinding
import com.zj365.mime.vm.BaseInfoVm
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import pub.devrel.easypermissions.EasyPermissions
import java.util.regex.Pattern

/**
 * 激活信息修改
 */
@Route(path = ARouterUrl.BASE_INFO_CHANGE)
class BaseInfoChangeAct : BaseVmAct<BaseInfoVm>(){

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

    //身份证  等实名信息描述
    private val tipInfoDialog by lazy {
        TipDialog(
            this,
            getString(R.string.card_id_desc), false, "", "我知道了"
        ) {
            finish()
        }
    }
    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 = ""
    private var open_city: String = ""//选中的省 市 code
    private var open_area: String = ""
    private var str_province: String? = null
    private var str_city: String? = null//选中的省 市 code

    private val MSG_LOAD_DATA = 0x0001
    private val MSG_LOAD_SUCCESS = 0x0002
    private val MSG_LOAD_FAILED = 0x0003
    var sexType = 1
    private var lat = ""
    private var lng = ""
    private var provincey = ""
    private var city = ""
    private var district = ""
    private var diseaseList = "[]" //手术外伤的其他信息
    private var tumour = ""
    private var other = ""
    private var birthdayType = 1
    private var isBind: Int = 1// 0  绑定跳转 完善信息  1 正常跳转 信息修改
    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(com.zj365.mime.R.string.name_first_num)
                    }
                }
                binding.mName.addTextChangedListener(this)
            }
        }
    }

    //gps打开
    val gpsDialog by lazy {
        GpsToastDialog(this, {
//        AmapInit.startLocation(application){
//            lat=it.latitude.toString()
//            lng=it.longitude.toString()
//            city=it.city
//            provincey=it.province
//            district=it.district
//        }
        }) {
            finish()
        }
    }

    override fun initData() {
        super.initData()
        isDarkBar = true
        mHandler.sendEmptyMessage(MSG_LOAD_DATA) //进入这个页面就解析json数据
        binding.title.mTvTitle.text = "信息修改"
        intent.extras?.let {
            isBind = it.getInt("isBind", 1)
            binding.title.mTvTitle.text = "完善信息"
        }



    }

    @SuppressLint("SetTextI18n")
    override fun initView() {
        super.initView()
        statusBar(binding.title.mView)
        binding.title.mIvBack.setOnClickListener { finish() }
        timeSelect.startDate?.set(1922, 0, 1)
        binding.mImage.setOnClickListener {
            if(EasyPermissions.hasPermissions(this,
                    Manifest.permission.CAMERA)){
                PictureUtils.openCamera(this@BaseInfoChangeAct)
            }else{
                EasyPermissions.requestPermissions(this,"",
                    0x00011,
                    Manifest.permission.CAMERA)
            }

        }

        if (isBind == 0) {
            tipInfoDialog.show()
        }
        binding.mName.addTextChangedListener(textListener)
//        binding.mGroup.setOnCheckedChangeListener { group, checkedId ->
//            when(checkedId){
//                R.id.mMale->sexType=1
//                R.id.mGirl->sexType=2
//            }
//        }
//        binding.mRadio.setOnCheckedChangeListener { group, checkedId ->
//            when(checkedId){
//                R.id.mRadio1->birthdayType=1
//                R.id.mRadio2->birthdayType=2
//
//            }
//        }
//        birthdayType = if (binding.checkBirthday.isChecked) 2 else 1
        binding.mBirthday.setOnClickListener {
            RxKeyboardTool.hideSoftInput(this)
            timeSelect.selectTimeTwo(it,binding.tvCalType)
        }
        binding.mArea.setOnClickListener {
            if (areaSelectDialog == null) {
                areaSelectDialog = AreaSelectDialog(
                    this,
                    R.layout.dialog_areaselect_layout,
                    "请选择区域",
                    intArrayOf(),
                    options1Items,
                    options2Items,
                    options3Items
                )
            }
            if (areaSelectDialog != null) {
                areaSelectDialog!!.setOnClickListener { string ->
                    //拿到省市区的字符串回调 需要将字符串以"|"进行切割
                    val str = string.split(",".toRegex()).dropLastWhile { it.isEmpty() }
                        .toTypedArray()
                    Log.e("Log", "str的长度=" + str.size)
                    open_province = str[0] //表示省
                    provincey = str[0] //表示省
                    open_city = str[1] //市
                    city = str[1] //市
                    open_area = str[2] //区
                    district = str[2] //区
                    binding.mArea.postDelayed({
                        binding.mArea.text = "$open_province $open_city $open_area"
                    }, 10)
                }
                areaSelectDialog!!.show()
            }
        }
        binding.mHistoryMedic.setOnClickListener {
            bundle.clear()
            var ids = ""
            if (binding.mHistoryMedic.tag != null) {
                ids = binding.mHistoryMedic.tag.toString()
            }
            bundle.putString("ids", ids)
            bundle.putString("other", other)
            bundle.putString("tumour", tumour)
            bundle.putString("arrays", diseaseList)

            bundle.putBoolean("isShowFoot", true)
            RouteManager.goActRequest(ARouterUrl.MEDICAL_HISTORY, this, 10000, bundle)
        }
        binding.mSubmit.setOnClickListener {
            submitData()
        }
        mViewModel.getAllInfo()
    }

    @SuppressLint("SetTextI18n")
    override fun liveObserver() {
        mViewModel.allData.observe(this) { it ->
            it.data.user.let {
                binding.mImage.setImageUser(this, it.avatarUrl, it.sex.toString())
                binding.mName.setText(it.name)

                binding.checkSex.isChecked = it.sex != 1
                binding.mPhone.text = it.phone
//                binding.mId.setText(it.idCard)
                binding.mBirthday.text = it.birthday
                if (it.birthdayType == 2){
                    binding.tvCalType.text = "公历"
                }else{
                    binding.tvCalType.text = "农历"
                }
                if(binding.tvCalType.text.toString().equals("公历")){
                    it.birthdayType == 2
                }else{
                    it.birthdayType == 1
                }
             //   binding.checkBirthday.isChecked = it.birthdayType == 2
//                when(it.birthdayType){
//                    1-> binding.checkBirthday.isChecked = false
//                    2->binding.checkBirthday.isChecked = true
//                }
                birthdayType = it.birthdayType
                if (TextUtils.isEmpty(it.city) || TextUtils.isEmpty(it.province) || TextUtils.isEmpty(it.district)){
                    getLocaltion()
                }else{
                    city = it.city
                    provincey = it.province //表示省
                    district = it.district //区
                    binding.mArea.text = "${it.province ?: ""} ${it.city ?: ""} ${it.district ?: ""}"
                }

                if (it.height > 0){
                    binding.mHeight.setText("${it.height}")
                }
                if (it.weight > 0){
                    binding.mWeight.setText(it.weight.toString())
                }


                binding.mAddress.setText(it.area)
                val str = StringBuilder()
                if (!it.historyName.isNullOrEmpty()) {
                    if (str.length > 0) {
                        str.append(",")
                    }
                    str.append(it.historyName)
                }
                if (!it.tumour.isNullOrEmpty()) {
                    if (str.length > 0) {
                        str.append(",")
                    }
                    str.append(it.tumour)
                }
                if (!it.other.isNullOrEmpty()) {
                    if (str.length > 0) {
                        str.append(",")
                    }
                    str.append(it.other)
                }
                binding.mHistoryMedic.text = str.toString()

                binding.mHistoryMedic.tag = it.historyId

                other = if (it.other == null) "" else it.other!!
                tumour = if (it.tumour == null) "" else it.tumour!!


                val array = JSONArray()
                it.diseaseList.forEach {
                    val json = JSONObject()
                    json.put("name", it.name)
                    json.put("type", it.type)
                    json.put("time", it.time)
                    array.put(json)
                }

                diseaseList = array.toString()
                binding.mOtherName.setText(it.urgent)
                binding.mOtherPhone.setText(it.urgentPhone)
                binding.mRela.setText(it.urgentRelation)

            }
        }
        mViewModel.setBasic.observe(this) {
            EventBus.getDefault().post(MyInfoEvent())
            if (isBind == 0) {
                RouteManager.goAct(ARouterUrl.MAIN_ACT)
            }
            finish()
        }
    }

    private fun submitData() {
        val name = binding.mName.text.toString().trim()
//        var idCard=binding.mId.text.toString().trim()
        val height = binding.mHeight.text.toString().trim()
        val wieght = binding.mWeight.text.toString().trim()
        val address = binding.mAddress.text.toString().trim()
        birthdayType = if (binding.checkBirthday.isChecked) 2 else 1
        val otherName = binding.mOtherName.text.toString().trim()
        val otherPhone = binding.mOtherPhone.text.toString().trim()
        val rela = binding.mRela.text.toString().trim()
        val medicName = binding.mHistoryMedic.text.toString().trim()
        val medicIds =
            if (binding.mHistoryMedic.tag == null) "" else binding.mHistoryMedic.tag.toString()
        val birthDay = binding.mBirthday.text.toString().trim()
//        city = binding.mArea.text.toString().trim()

        val paht = if (binding.mImage.tag == null) {
            ""
        } else {
            binding.mImage.tag.toString()
        }
        val sexValue = if (binding.checkSex.isChecked) "2" else "1"

        if (name.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入姓名")
            return
        }
        if (height.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入身高")
            return
        }

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

        if (wieght.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入体重")
            return
        }

        if (wieght.toFloat() < 3 || wieght.toFloat() > 300) {
            CommonToastUtils.showToast("请输入正确体重")
            return
        }
        if (birthDay.isNullOrEmpty()) {
            CommonToastUtils.showToast("请选择出生日期")
            return
        }
        if (TimeUtils.getAgeByBirth(birthDay) < 14) {
            CommonToastUtils.showToast("需要年满14岁才可使用")
            return
        }
        if (city.isNullOrEmpty()) {
            CommonToastUtils.showToast("请选择所属地区")
            return
        }
        if (address.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入详细住址")
            return
        }
        if (medicIds.isNullOrEmpty()) {
            CommonToastUtils.showToast("请选择病史")
            return
        }

        if (otherName.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入紧急联系人姓名")
            return
        }

        if (otherPhone.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入紧急联系人联系方式")
            return
        }
        if (!RxRegTool.isMobileSimple(otherPhone)){
            CommonToastUtils.showToast("紧急电话不得少于11位")
            return
        }
        if (otherPhone == binding.mPhone.text.toString()) {
            CommonToastUtils.showToast("紧急联系人电话不能与本人电话一致")
            return
        }

        if (rela.isNullOrEmpty()) {
            CommonToastUtils.showToast("请输入关系")
            return
        }

        mViewModel.submit(
            paht,
            name,
            sexValue,
            height,
            wieght,
            address,
            otherName,
            binding.mPhone.text.toString(),
            otherPhone,
            rela,
            provincey,
            city,
            district,
            lat,
            lng,
            medicName,
            medicIds,
            tumour,
            other,
            diseaseList,
            birthDay,
            birthdayType
        )
    }

    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 = result[0].compressPath.ifEmpty {
                            result[0].androidQToPath
                        }
                        binding.mImage.setImage(this, path)
                        binding.mImage.tag = path
                    }
                }

                10000 -> {
                    var ids = data!!.extras!!.getString("ids")
                    val names = data!!.extras!!.getString("names")
                    tumour = data!!.extras!!.getString("tumour").toString()
                    other = data!!.extras!!.getString("other").toString()
                    diseaseList = data!!.extras!!.getString("diseaseList").toString()
                    binding.mHistoryMedic.text = names
                    binding.mHistoryMedic.tag = ids
                }
            }

        }
    }

    override fun onResume() {
        super.onResume()
//        getPermission()

    }

    private fun getPermission() {
        Acp.getInstance(this).request(
            AcpOptions.Builder()
                .setPermissions(
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                ).build(),
            object : AcpListener {
                override fun onGranted() {
                    if (!isGpsOpen(baseContext)) {
                        if (!gpsDialog.isShowing) {
                            gpsDialog.showDialog()
                        }
                    } else {
//                        AmapInit.startLocation(application){
//                            lat=it.latitude.toString()
//                            lng=it.longitude.toString()
//                            city=it.city
//                            provincey=it.province
//                            district=it.district
//                        }
                    }
                }

                override fun onDenied(permissions: List<String>) {
                    finish()
                }
            })
    }

    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@BaseInfoChangeAct,
                            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"
            }
        }
    }

    fun getLocaltion(){
        if(MMkvHelper.contains(Const.PROVINCE) && MMkvHelper.contains(Const.CITY) && MMkvHelper.contains(Const.DISTRICT)){
            open_province = MMkvHelper.getString(Const.PROVINCE) //表示省
            provincey = MMkvHelper.getString(Const.PROVINCE)  //表示省
            open_city =MMkvHelper.getString(Const.CITY)  //市
            city = MMkvHelper.getString(Const.CITY)  //市
            open_area = MMkvHelper.getString(Const.DISTRICT)  //区
            district = MMkvHelper.getString(Const.DISTRICT)  //区
            binding.mArea.text = "$open_province $open_city $open_area"

        }else{
            if(EasyPermissions.hasPermissions(this,  Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION)){
                AmapInit.startLocation(this) {
                    LogUtils.e("DynamicManagementFrag","${it.city}")
                    MMkvHelper.put(Const.LONGITUDE,it.longitude)
                    MMkvHelper.put(Const.LATITUDE,it.latitude)
                    MMkvHelper.put(Const.PROVINCE,it.province)
                    MMkvHelper.put(Const.CITY,it.city)
                    MMkvHelper.put(Const.DISTRICT,it.district)

                    open_province = MMkvHelper.getString(Const.PROVINCE) //表示省
                    provincey = MMkvHelper.getString(Const.PROVINCE)  //表示省
                    open_city =MMkvHelper.getString(Const.CITY)  //市
                    city = MMkvHelper.getString(Const.CITY)  //市
                    open_area = MMkvHelper.getString(Const.DISTRICT)  //区
                    district = MMkvHelper.getString(Const.DISTRICT)  //区
                    binding.mArea.text = "$open_province $open_city $open_area"

                }
            }else{
                EasyPermissions.requestPermissions(this,"获取天气信息需要申请定位权限",
                    0x00022,
                    Manifest.permission.ACCESS_COARSE_LOCATION,  Manifest.permission.ACCESS_FINE_LOCATION);
            }

        }
    }


    override fun onDestroy() {
        AmapInit.stopLocation()
        super.onDestroy()

    }

    override fun onSuccess(requestCode: Int) {
        super.onSuccess(requestCode)

        LogUtils.e("BaseInfoChangeAct","onSuccess${requestCode}")
        if(requestCode == 0x00011){
            PictureUtils.openCamera(this@BaseInfoChangeAct)
        }else{
            AmapInit.startLocation(this) {
                LogUtils.e("DynamicManagementFrag","${it.city}")
                MMkvHelper.put(Const.LONGITUDE,it.longitude)
                MMkvHelper.put(Const.LATITUDE,it.latitude)
                MMkvHelper.put(Const.PROVINCE,it.province)
                MMkvHelper.put(Const.CITY,it.city)
                MMkvHelper.put(Const.DISTRICT,it.district)

                open_province = MMkvHelper.getString(Const.PROVINCE) //表示省
                provincey = MMkvHelper.getString(Const.PROVINCE)  //表示省
                open_city =MMkvHelper.getString(Const.CITY)  //市
                city = MMkvHelper.getString(Const.CITY)  //市
                open_area = MMkvHelper.getString(Const.DISTRICT)  //区
                district = MMkvHelper.getString(Const.DISTRICT)  //区
                binding.mArea.text = "$open_province $open_city $open_area"

            }
        }
    }

}