package com.seatel.mobilehall.ui.home.fragment

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import coil.load
import com.android.volley.Request
import com.seatel.mobilehall.R
import com.seatel.mobilehall.data.network.SeatelJSONArrayRequest
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.data.prefs.ProfileSharedPreference
import com.seatel.mobilehall.data.prefs.SeatelSharePreferences
import com.seatel.mobilehall.ui.base.fragment.BaseFragment
import com.seatel.mobilehall.ui.home.activity.YesHubNearestActivity
import com.seatel.mobilehall.ui.home.model.SeatelShopLocationModel
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.SeatelAlertDialog
import com.seatel.mobilehall.util.SeatelUtils
import com.seatel.mobilehall.util.customview.BottomChooserDialog
import com.seatel.mobilehall.util.manager.OrderProfileSingleton
import com.seatel.mobilehall.util.manager.OrderingManager
import kotlinx.android.synthetic.main.activity_profile.view.image_view_profile
import kotlinx.android.synthetic.main.activity_updated_sim_profile.activate_sim_view
import kotlinx.android.synthetic.main.fragment_order_pick_up.*
import kotlinx.android.synthetic.main.fragment_order_pick_up.view.edit_text_first_name
import kotlinx.android.synthetic.main.view_activate_buy_sim.view.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.regex.Matcher
import java.util.regex.Pattern

class OrderPickUpDeliveryFragment : BaseFragment(), OrderingManager.OrderCallback,
    View.OnClickListener, TextWatcher {

    private var shopName: String = ""
    private var shopId: String = ""
    private var tempShopId: String = ""
    private var phoneNumber: String = ""
    private var address: String = OrderingManager.getInstance().addressSave
    private var firstNameDelivery: String = OrderingManager.getInstance().firstNameSave
    private var lastNameDelivery: String = OrderingManager.getInstance().lastNameSave
    private var emailDelivery: String = OrderingManager.getInstance().emailSave
    private var phoneNumberDelivery: String = OrderingManager.getInstance().phoneNumberSave
    private var province: String = OrderingManager.getInstance().provinceSave
    private var strTempAddrss: String = OrderingManager.getInstance().addressSave
    private val provinceModel = ArrayList<BottomChooserDialog.BottomChooserModel>()
    private var postDelay: Handler? = null

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.view_title_pickup, R.id.image_view_edit, R.id.radio_pick -> {
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.DELIVERY && checkIsInfoAddressUpdated()) {
                    setDataInputDeliveryDefault()
                }
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.PICKUP && v.id != R.id.image_view_edit && ctv_edit_pickup.visibility == View.GONE) {
                    return
                }
                if (ctv_edit_pickup.visibility == View.GONE && ctv_save_pickup.visibility == View.GONE) OrderingManager.getInstance().deliverStatus =
                    null
                OrderingManager.getInstance().isSelectedDelivery = false
                updateLayoutService(OrderingManager.DeliverStatus.PICKUP)
                radio_delivery.isChecked = false
                radio_pick.isChecked = true
                if (radio_pick.isChecked) {
                    if (postDelay == null) postDelay = Handler()
                    if (postDelay != null) postDelay?.postDelayed({
                        setDataPickupInfoInput()
                        if (ctv_edit_pickup.visibility == View.GONE && ctv_save_pickup.visibility == View.GONE) radio_pick.isChecked =
                            false
                        postDelay?.removeCallbacksAndMessages(this)
                        postDelay = null
                    }, 200)
                }
            }

            R.id.view_title_delivery, R.id.radio_delivery -> {
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.PICKUP && checkIsInfoAddressUpdated()) {
                    setDataPickupInfoInput()
                }
                if ((OrderingManager.getInstance().claimFreeSim || OrderingManager.getInstance().winPromotionFreeSim) && checkIsDeliveryClaimFreeSim()) {
                    radio_delivery.isChecked = false
                    return
                }
                if (OrderingManager.getInstance().deliverStatus == OrderingManager.DeliverStatus.DELIVERY && ctv_edit_delivery.visibility == View.GONE) {
                    return
                }
                OrderingManager.getInstance().isSelectedDelivery = true
                radio_delivery.isChecked = false
                updateLayoutService(OrderingManager.DeliverStatus.DELIVERY)
                radio_pick.isChecked = false
                view_edit_pickup.visibility = View.GONE

            }

            R.id.ctv_edit_delivery -> {
                showDeliveryInput()
                checkIsInfoAddressUpdated()
            }

            R.id.ctv_done_save -> {
                if (checkValidateFieldInput()) return
                if (checkIsInfoAddressUpdated()) {
                    firstNameDelivery = edit_text_first_name.text.toString()
                    lastNameDelivery = edit_text_last_name.text.toString()
                    emailDelivery = edit_text_email.text.toString()
                    phoneNumberDelivery = edit_text_phone_number.text.toString()
                    address = edit_text_address.text.toString()
                    province = edit_text_province.text.toString()
                    putDeliveryInfo()
                }

                showDeliveryLocation(address, province)
                SeatelUtils.hideKeyboard(getmContext() as Activity)
            }

            R.id.ctv_done_cancel -> {
                if (checkIsEmptyAll()) {
                    OrderingManager.getInstance().locationModel = SeatelShopLocationModel("", "")
                    OrderingManager.getInstance().deliverStatus = null
                    layout_delivery_location.visibility = View.GONE
                    ctv_done_save.visibility = View.GONE
                    ctv_done_cancel.visibility = View.GONE
                    ctv_edit_delivery.visibility = View.GONE
                    view_input_pickup.visibility = View.GONE
                    radio_delivery.isChecked = false
                    OrderingManager.getInstance().isSelectedDelivery = false
                    layout_delivery.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
                } else {
                    showDeliveryLocation(address, province)
                    SeatelUtils.hideKeyboard(getmContext() as Activity)
                }
                setDataInputDeliveryDefault()
                checkIsInfoAddressUpdated()
            }

            R.id.edit_text_province -> {
                showProvinceBottomDialog()
            }

            R.id.ctv_edit_pickup -> {
                checkIsInfoAddressUpdated()
                setDataPickupInfoInput()
                ctv_edit_pickup.visibility = View.GONE
                ctv_cancel_pickup.visibility = View.VISIBLE
                ctv_save_pickup.visibility = View.VISIBLE
                view_show_pickup.visibility = View.GONE
                view_input_pickup.visibility = View.VISIBLE
            }

            R.id.ctv_save_pickup -> {
                if (checkValidateFieldInputPickUp()) return
                if (checkIsInfoAddressUpdated()) {
                    firstNameDelivery = edit_text_first_name_pickup.text.toString()
                    lastNameDelivery = edit_text_last_name_pickup.text.toString()
                    emailDelivery = edit_text_email_pickup.text.toString()
                    phoneNumberDelivery = edit_text_phone_number_pickup.text.toString()
                    putDeliveryInfo(true)
                } else showInputPickup()
                SeatelUtils.hideKeyboard(getmContext() as Activity)
                OrderingManager.getInstance().updatedPickupAddress = false
            }

            R.id.ctv_cancel_pickup -> {
                if (checkIsEmptyAll(true)) {
                    OrderingManager.getInstance().locationModel = SeatelShopLocationModel("", "")
                    OrderingManager.getInstance().deliverStatus = null
                    layout_pick_location.visibility = View.GONE
                    ctv_save_pickup.visibility = View.GONE
                    ctv_cancel_pickup.visibility = View.GONE
                    ctv_edit_pickup.visibility = View.GONE
                    image_view_edit.visibility = View.GONE
                    radio_pick.isChecked = false
                    tv_pick_des.visibility = View.GONE
                    view_show_pickup.visibility = View.GONE
                    view_input_pickup.visibility = View.GONE
                    OrderingManager.getInstance().isSelectedDelivery = false
                    layout_pick_up.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
                } else {
                    showInputPickup()
                    setDataPickupInfoInput()
                    checkIsInfoAddressUpdated()
                }
                SeatelUtils.hideKeyboard(getmContext() as Activity)
            }
        }
    }

    private fun checkIsEmptyAll(isPickup: Boolean = false): Boolean {
        if (isPickup) return firstNameDelivery.isEmpty() || lastNameDelivery.isEmpty() || emailDelivery.isEmpty() || phoneNumberDelivery.isEmpty()
        return address.isEmpty() || province.isEmpty() || firstNameDelivery.isEmpty() || lastNameDelivery.isEmpty() || emailDelivery.isEmpty() || phoneNumberDelivery.isEmpty()
    }

    fun checkIsInfoAddressUpdated(): Boolean {
        var check = false
        if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) {
            when {
                !TextUtils.equals(
                    edit_text_first_name.text.toString(), firstNameDelivery
                ) || TextUtils.equals(edit_text_first_name.text.toString(), "") -> check = true

                !TextUtils.equals(
                    edit_text_last_name.text.toString(), lastNameDelivery
                ) || TextUtils.equals(edit_text_last_name.text.toString(), "") -> check = true

                !TextUtils.equals(
                    edit_text_email.text.toString(), emailDelivery
                ) || TextUtils.equals(edit_text_email.text.toString(), "") -> check = true

                !TextUtils.equals(
                    edit_text_phone_number.text.toString(), phoneNumberDelivery
                ) || TextUtils.equals(edit_text_phone_number.text.toString(), "") -> check = true

                !TextUtils.equals(edit_text_address.text.toString(), address) || TextUtils.equals(
                    edit_text_address.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(
                    edit_text_province.text.toString(),
                    SeatelUtils.translatForDialog(context, province)
                ) || TextUtils.equals(edit_text_province.text.toString(), "") -> check = true
            }
        } else if (tmpDeliveryStatus == OrderingManager.DeliverStatus.PICKUP) {
            when {
                !TextUtils.equals(
                    edit_text_first_name_pickup.text.toString(), firstNameDelivery
                ) || TextUtils.equals(
                    edit_text_first_name_pickup.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(
                    edit_text_last_name_pickup.text.toString(), lastNameDelivery
                ) || TextUtils.equals(
                    edit_text_last_name_pickup.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(
                    edit_text_email_pickup.text.toString(), emailDelivery
                ) || TextUtils.equals(edit_text_email_pickup.text.toString(), "") -> check = true

                !TextUtils.equals(
                    edit_text_phone_number_pickup.text.toString(), phoneNumberDelivery
                ) || TextUtils.equals(
                    edit_text_phone_number_pickup.text.toString(), ""
                ) -> check = true

                !TextUtils.equals(shopId, tempShopId) || TextUtils.equals(tempShopId, "") -> check =
                    true
            }
        }
        OrderingManager.getInstance().updatedPickupAddress = check
        OrderingManager.getInstance().updatedDeliveryAddress = check


        return check
    }


    private fun setDataPickupInfoInput() {
        edit_text_first_name_pickup.setText(firstNameDelivery)
        edit_text_last_name_pickup.setText(lastNameDelivery)
        edit_text_email_pickup.setText(emailDelivery)
        edit_text_phone_number_pickup.setText(phoneNumberDelivery)
    }

    private fun setDataDeliveryDisplayInfo() {
        ctv_address_delivery.text = address
        ctv_city_delivery.text = province
        ctv_first_name_delivery.text = firstNameDelivery
        ctv_last_name_delivery.text = lastNameDelivery
        ctv_email_delivery.text = emailDelivery
        ctv_phone_number_delivery.text = phoneNumberDelivery
    }

    private fun setDataPickupDisplayInfo() {
        ctv_first_name_pickup.text = firstNameDelivery
        ctv_last_name_pickup.text = lastNameDelivery
        ctv_email_pickup.text = emailDelivery
        ctv_phone_number_pickup.text = phoneNumberDelivery
    }

    private fun showInputPickup() {
        view_edit_pickup.visibility = View.VISIBLE
        if (checkIsEmptyAll(true)) {
            ctv_edit_pickup.visibility = View.GONE
            ctv_cancel_pickup.visibility = View.VISIBLE
            ctv_save_pickup.visibility = View.VISIBLE
            view_show_pickup.visibility = View.GONE
            view_input_pickup.visibility = View.VISIBLE
        } else {
            ctv_save_pickup.visibility = View.GONE
            ctv_cancel_pickup.visibility = View.GONE
            ctv_edit_pickup.visibility = View.VISIBLE
            view_show_pickup.visibility = View.VISIBLE
            view_input_pickup.visibility = View.GONE
            SeatelUtils.hideKeyboard(getmContext() as Activity)
        }
    }

    private fun visiblePickupAddress() {
        view_edit_pickup.visibility = View.VISIBLE
        ctv_save_pickup.visibility = View.GONE
        ctv_cancel_pickup.visibility = View.GONE
        ctv_edit_pickup.visibility = View.VISIBLE
        view_show_pickup.visibility = View.VISIBLE
        view_input_pickup.visibility = View.GONE
        SeatelUtils.hideKeyboard(getmContext() as Activity)
        checkIsInfoAddressUpdated()
    }

    private fun checkIsDeliveryClaimFreeSim(): Boolean {
        if (OrderingManager.getInstance().topupAmountClaimFreeSim == 0.0) {
            SeatelAlertDialog.with(
                getmContext(), "To select delivery, you need to top up at least $1."
            ).show()
            return true
        }
        return false
    }

    private fun checkValidateFieldInputPickUp(): Boolean {
        var str = ""
        val ps: Pattern = Pattern.compile("^[a-zA-Z]+$")
        //First Name
        val firstName: Matcher = ps.matcher(edit_text_first_name_pickup.text.toString().trim())
        val bs: Boolean = firstName.matches()
        if (!bs) {
            str = getString(R.string.please_enter_valid_first_name)
            edit_text_first_name.requestFocus()
        }

        //Last Name
        val lastName: Matcher = ps.matcher(edit_text_last_name_pickup.text.toString().trim())
        val bsLastName: Boolean = lastName.matches()
        if (!bsLastName) {
            edit_text_last_name.requestFocus()
            str = getString(R.string.please_enter_valid_last_name)
        }
        when {
            TextUtils.isEmpty(edit_text_first_name_pickup.text.toString().trim()) -> {
                str = getString(R.string.please_enter_delivery_first_name)
                edit_text_first_name_pickup.requestFocus()
            }

            TextUtils.isEmpty(edit_text_last_name_pickup.text.toString().trim()) -> {
                edit_text_last_name_pickup.requestFocus()
                str = getString(R.string.please_enter_delivery_last_name)
            }

            TextUtils.isEmpty(edit_text_email_pickup.text.toString().trim()) -> {
                edit_text_email_pickup.requestFocus()
                str = getString(R.string.please_enter_delivery_email)
            }

            SeatelUtils.isEmailValid(edit_text_email_pickup.text.toString().trim()) -> {
                edit_text_email_pickup.requestFocus()
                str = getString(R.string.email_invalid)
            }

            TextUtils.isEmpty(edit_text_phone_number_pickup.text.toString().trim()) -> {
                edit_text_phone_number_pickup.requestFocus()
                str = getString(R.string.please_enter_delivery_phone_number)
            }

            !SeatelUtils.isValidatePhoneFormat(
                edit_text_phone_number_pickup.text.toString().trim()
            ) -> {
                edit_text_phone_number_pickup.requestFocus()
                str = getString(R.string.valid_phone_number)
            }
        }
        if (str.isNotEmpty()) {
            SeatelAlertDialog.with(requireContext(), str).show()
            return true
        }
        return false
    }

    private fun checkValidateFieldInput(): Boolean {
        var str = ""
        val ps: Pattern = Pattern.compile("^[a-zA-Z]+$")
        //First Name
        val firstName: Matcher = ps.matcher(edit_text_first_name.text.toString().trim())
        val bs: Boolean = firstName.matches()
        if (!bs) {
            str = getString(R.string.please_enter_valid_first_name)
            edit_text_first_name.requestFocus()
        }
        //Last Name
        val lastName: Matcher = ps.matcher(edit_text_last_name.text.toString().trim())
        val bsLastName: Boolean = lastName.matches()
        if (!bsLastName) {
            edit_text_last_name.requestFocus()
            str = getString(R.string.please_enter_valid_last_name)
        }
        when {
            TextUtils.isEmpty(edit_text_first_name.text.toString().trim()) -> {
                str = getString(R.string.please_enter_delivery_first_name)
                edit_text_first_name.requestFocus()
            }

            TextUtils.isEmpty(edit_text_last_name.text.toString().trim()) -> {
                edit_text_last_name.requestFocus()
                str = getString(R.string.please_enter_delivery_last_name)
            }

            TextUtils.isEmpty(edit_text_email.text.toString().trim()) -> {
                edit_text_email.requestFocus()
                str = getString(R.string.please_enter_delivery_email)
            }

            SeatelUtils.isEmailValid(edit_text_email.text.toString().trim()) -> {
                edit_text_email.requestFocus()
                str = getString(R.string.email_invalid)
            }

            TextUtils.isEmpty(edit_text_phone_number.text.toString().trim()) -> {
                edit_text_phone_number.requestFocus()
                str = getString(R.string.please_enter_delivery_phone_number)
            }

            !SeatelUtils.isValidatePhoneFormat(edit_text_phone_number.text.toString().trim()) -> {
                edit_text_phone_number.requestFocus()
                str = getString(R.string.valid_phone_number)
            }

            TextUtils.isEmpty(edit_text_address.text.toString().trim()) -> {
                edit_text_address.requestFocus()
                str = getString(R.string.please_enter_delivery)
            }

            TextUtils.isEmpty(edit_text_province.text.toString()) -> str =
                getString(R.string.please_select_delivery_province)
        }
        if (str.isNotEmpty()) {
            SeatelAlertDialog.with(requireContext(), str).show()
            return true
        }
        return false
    }


    fun isValidData(): Boolean {
        if (TextUtils.isEmpty(
                activate_sim_view.tv_id_type.text.toString().trim()
            ) || TextUtils.isEmpty(activate_sim_view.getCertificationNamePost())
        ) {
            SeatelAlertDialog.with(requireContext(), "Please select Document Type.").show()
            return false
        }
        if (TextUtils.isEmpty(activate_sim_view.edit_text_name.text.toString())) {
            SeatelAlertDialog.with(requireContext(), "Please input your name.").show()
            return false
        }
        if (TextUtils.isEmpty(activate_sim_view.edit_text_card_number.text.toString())) {
            SeatelAlertDialog.with(requireContext(), "Please input your ID number.").show()
            return false
        }

        if (TextUtils.isEmpty(activate_sim_view.tv_sex.text.toString())) {
            SeatelAlertDialog.with(requireContext(), "Please select your gender.").show()
            return false
        }

        if (TextUtils.isEmpty(activate_sim_view.tv_date.text.toString()) || (TextUtils.isEmpty(
                activate_sim_view.tv_month.text.toString()
            )) || (TextUtils.isEmpty(activate_sim_view.tv_year.text.toString()))
        ) {
            SeatelAlertDialog.with(requireContext(), "Please select your date of birth.").show()
            return false
        }

        if (activate_sim_view.mOutputFront.isNullOrBlank()) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID front.").show()
            return false
        }

        if (activate_sim_view.mOutputBack.isNullOrBlank()) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID back.").show()
            return false
        }

        if (activate_sim_view.mOutputUser.isNullOrBlank()) {
            SeatelAlertDialog.with(requireContext(), "Please take your photo.").show()
            return false
        }

        /*if (activate_sim_view.mOutputFileFront == null) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID front.").show()
            return false
        }
        if (activate_sim_view.mOutputFileBack == null) {
            SeatelAlertDialog.with(requireContext(), "Please take picture ID back.").show()
            return false
        }
        if (activate_sim_view.mOutputFileUser == null) {
            SeatelAlertDialog.with(requireContext(), "Please take your photo.").show()
            return false
        }*/
        return true
    }

    fun showValidateFieldOnNextClick() {
        when (OrderingManager.getInstance().deliverStatus) {
            OrderingManager.DeliverStatus.DELIVERY -> checkValidateFieldInput()
            OrderingManager.DeliverStatus.PICKUP -> checkValidateFieldInputPickUp()
        }

    }

    fun setPhoneNumber(phone: String) {
        this.phoneNumber = phone
    }

    override fun onCartModify() {
    }

    override fun onCartModifyQty() {
    }

    override fun onDeliveryData(seatelShopLocationModel: SeatelShopLocationModel?) {
        if (seatelShopLocationModel != null) updateData(seatelShopLocationModel)
    }

    private var tmpDeliveryStatus: OrderingManager.DeliverStatus? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        setmContext(context)
        setFragmentLayout(R.layout.fragment_order_pick_up)
    }

    private fun showProvinceBottomDialog() {
        if (provinceModel.size > 0) {
            BottomChooserDialog(requireContext()).addItems(
                provinceModel,
                object : BottomChooserDialog.OnItemChooser {
                    override fun onChose(
                        position: Int, data: BottomChooserDialog.BottomChooserModel
                    ) {
                        OrderingManager.getInstance().updatedDeliveryAddress =
                            !TextUtils.equals(data.name, edit_text_province.text.toString())
                        edit_text_province.text = data.name
                    }
                }).show()
        }
    }

    private fun getProvinceData() {
        object : SeatelJSONArrayRequest(context) {
            override fun getFunctionName(): String {
                return "province?lang=$languageCode"
            }
        }.execute {
            val provinceJson = it as JSONArray
            val provinceSet = hashSetOf<String>()
            for (i in 0 until provinceJson.length()) {
                provinceSet.add(provinceJson.optJSONObject(i).optString("title"))
                provinceModel.add(
                    BottomChooserDialog.BottomChooserModel(
                        0, provinceJson.optJSONObject(i).optString("title")
                    )
                )
            }
            SeatelSharePreferences.getInstance(requireContext())?.setProvinceData(provinceSet)
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        activate_sim_view.displayForOrderPickUp()
        Log.d("TAG", "onViewCreated: ${activate_sim_view.mOutputFront}")

        if ((OrderingManager.getInstance().claimFreeSim)) view_note_claim_free_sim.visibility =
            View.VISIBLE
        if (OrderingManager.getInstance().winPromotionFreeSim) layout_delivery.visibility =
            View.GONE

        if (OrderingManager.getInstance().buyTopUpCard) layout_profile_id.visibility = View.GONE

        title_address.text = title_address.text.toString() + ":"
        edit_text_address.hint =
            SeatelUtils.translatForDialog(context, "Address (Ex: House #, Street 22, Chamkamon)")
        edit_text_province.hint =
            SeatelUtils.translatForDialog(context, "City/Province (Ex: Phnom Penh)")

        val provinceData = SeatelSharePreferences.getInstance(requireContext())?.getProvinceData()
        if (provinceData != null) {
            for (i in provinceData.indices) {
                provinceModel.add(
                    BottomChooserDialog.BottomChooserModel(
                        0, provinceData.elementAt(i)!!
                    )
                )
            }
        } else {
            getProvinceData()
        }

        ctv_edit_pickup.setOnClickListener(this)
        ctv_save_pickup.setOnClickListener(this)
        ctv_cancel_pickup.setOnClickListener(this)

        view_title_pickup.setOnClickListener(this)
        radio_pick.setOnClickListener(this)
        radio_delivery.setOnClickListener(this)
        view_title_delivery.setOnClickListener(this)
        OrderingManager.getInstance().orderCallback = this
        if (OrderingManager.getInstance().locationModel != null) {
            tmpDeliveryStatus = OrderingManager.getInstance().deliverStatus
            updateData(OrderingManager.getInstance().locationModel, true)
        }
        edit_text_province.setOnClickListener(this)
        ctv_done_save.setOnClickListener(this)
        ctv_done_cancel.setOnClickListener(this)
        if (OrderingManager.getInstance().locationModel == null) getDeliveryInfo()
        else {
            address = OrderingManager.getInstance().addressSave
            province = OrderingManager.getInstance().provinceSave
            firstNameDelivery = OrderingManager.getInstance().firstNameSave
            lastNameDelivery = OrderingManager.getInstance().lastNameSave
            emailDelivery = OrderingManager.getInstance().emailSave
            phoneNumberDelivery = OrderingManager.getInstance().phoneNumberSave
            setDataPickupInfoInput()
            setDataDeliveryDisplayInfo()
            setDataInputDeliveryDefault()
            checkIsInfoAddressUpdated()
        }
        edit_text_first_name.addTextChangedListener(this)
        edit_text_last_name.addTextChangedListener(this)
        edit_text_email.addTextChangedListener(this)
        edit_text_phone_number.addTextChangedListener(this)
        edit_text_address.addTextChangedListener(this)

        edit_text_first_name_pickup.addTextChangedListener(this)
        edit_text_last_name_pickup.addTextChangedListener(this)
        edit_text_email_pickup.addTextChangedListener(this)
        edit_text_phone_number_pickup.addTextChangedListener(this)

        //  getProfileData()
        Log.d(
            "profile:>>>", "onViewCreated: ${
                ProfileSharedPreference.getInstance(requireContext())?.getDocumentType()
            } ${ProfileSharedPreference.getInstance(requireContext())?.getName()}"
        )
    }

    private fun getProfileData() {

        val orderProfile = OrderProfileSingleton.getInstance(requireContext())

        activate_sim_view.tv_id_type.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setDocType(activate_sim_view.getCertificationNamePost()!!)
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        activate_sim_view.edit_text_card_number.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setNationalityId(activate_sim_view.edit_text_card_number.text.toString())
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        activate_sim_view.edit_text_name.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setName(activate_sim_view.edit_text_name.text.toString())
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        activate_sim_view.tv_sex.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setGender(activate_sim_view.getGenderKeyPost())
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        activate_sim_view.tv_date.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                orderProfile?.setDateOfBirth(activate_sim_view.dateOfBirth)
            }

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

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })


        activate_sim_view.tv_id_type.text = orderProfile?.getDocType()
        activate_sim_view.edit_text_card_number.setText(orderProfile?.getNationalityId())
        activate_sim_view.edit_text_name.setText(orderProfile?.getName())
        activate_sim_view.tv_sex.text = orderProfile?.getGender()
        activate_sim_view.tv_date.text = orderProfile?.getDateOfBirth()

    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        checkIsInfoAddressUpdated()
    }

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

    override fun afterTextChanged(s: Editable?) {
    }

    private fun updateLayoutService(deliverStatus: OrderingManager.DeliverStatus) {
        tmpDeliveryStatus = deliverStatus
        if (tmpDeliveryStatus == OrderingManager.DeliverStatus.PICKUP) {
            layout_delivery.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
            layout_delivery_location.visibility = View.GONE
            ctv_done_save.visibility = View.GONE
            ctv_done_cancel.visibility = View.GONE
            ctv_edit_delivery.visibility = View.GONE
            YesHubNearestActivity.lunchWithResult(context)
            if (ctv_edit_pickup.visibility == View.GONE && ctv_save_pickup.visibility == View.GONE) radio_pick.isChecked =
                false
        } else if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) showDeliveryLocation(
            address, province
        )

    }

    private fun putDeliveryInfo(isPickup: Boolean = false) {
        object : SeatelJSONObjectRequest(getmContext()) {
            override fun getFunctionName(): String {
                return if (phoneNumber.isEmpty()) {
                    "users/${Constant.DELIVERY_INFO}"
                } else "users/${Constant.DELIVERY_INFO}?phoneNumber=$phoneNumber"
            }

            override fun getMethod(): Int {
                return Request.Method.PUT
            }

            override fun onGetBodyRequest(): String {
                val deliveryAddress = JSONObject()
                try {
                    if (isPickup) {
                        deliveryAddress.put("shopName", shopName)
                        deliveryAddress.put("shopId", shopId)
                        tempShopId = shopId
                    }
                    deliveryAddress.put("address", address)
                    deliveryAddress.put("province", province)
                    deliveryAddress.put("firstName", firstNameDelivery)
                    deliveryAddress.put("lastName", lastNameDelivery)
                    deliveryAddress.put("email", emailDelivery)
                    deliveryAddress.put("phoneNumber", phoneNumberDelivery)
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
                return deliveryAddress.toString()
            }
        }.execute {
            OrderingManager.getInstance().firstNameSave = firstNameDelivery
            OrderingManager.getInstance().lastNameSave = lastNameDelivery
            OrderingManager.getInstance().emailSave = emailDelivery
            OrderingManager.getInstance().phoneNumberSave = phoneNumberDelivery
            OrderingManager.getInstance().addressSave = address
            OrderingManager.getInstance().provinceSave = province
            if (edit_text_province != null) {
                setDataPickupInfoInput()
                setDataInputDeliveryDefault()
                setDataPickupDisplayInfo()
                setDataDeliveryDisplayInfo()
                checkIsInfoAddressUpdated()
                if (isPickup) visiblePickupAddress()
            }
        }
    }

    private fun getDeliveryInfo() {
        object : SeatelJSONObjectRequest(getmContext()) {
            override fun getFunctionName(): String {
                return if (phoneNumber.isEmpty()) {
                    "users/${Constant.DELIVERY_INFO}"
                } else "users/${Constant.DELIVERY_INFO}?phoneNumber=$phoneNumber"
            }

            override fun getMethod(): Int {
                return Request.Method.GET
            }
        }.execute {
            it as JSONObject
            firstNameDelivery = it.optString("firstName", "")
            lastNameDelivery = it.optString("lastName", "")
            emailDelivery = it.optString("email", "")
            phoneNumberDelivery = it.optString("phoneNumber", "")
            address = it.optString("address", "")
            province = it.optString("province", "")
            strTempAddrss = address
            OrderingManager.getInstance().firstNameSave = firstNameDelivery
            OrderingManager.getInstance().lastNameSave = lastNameDelivery
            OrderingManager.getInstance().emailSave = emailDelivery
            OrderingManager.getInstance().phoneNumberSave = phoneNumberDelivery
            OrderingManager.getInstance().addressSave = address
            OrderingManager.getInstance().provinceSave = province
            setDataInputDeliveryDefault()
            setDataPickupInfoInput()
            if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) {
                showDeliveryLocation(address, province)
            }
            checkIsInfoAddressUpdated()
        }
    }

    private fun showDeliveryInput() {
        ctv_done_save.visibility = View.VISIBLE
        ctv_edit_delivery.visibility = View.GONE
        view_edit_pickup.visibility = View.GONE
        ctv_done_cancel.visibility = View.VISIBLE
        view_show_delivery.visibility = View.GONE
        view_input_delivery.visibility = View.VISIBLE
        setDataInputDeliveryDefault()
    }

    private fun setDataInputDeliveryDefault() {
        if (edit_text_province != null) {
            edit_text_province.text = province
            edit_text_address.setText(address)
            edit_text_first_name.setText(firstNameDelivery)
            edit_text_last_name.setText(lastNameDelivery)
            edit_text_email.setText(emailDelivery)
            edit_text_phone_number.setText(phoneNumberDelivery)
        }
    }

    private fun saveAddressPickupAfterSelectYesHub() {
        if (ctv_edit_pickup.visibility == View.VISIBLE && firstNameDelivery.isNotEmpty() && lastNameDelivery.isNotEmpty() && emailDelivery.isNotEmpty() && phoneNumberDelivery.isNotEmpty() && shopName.isNotEmpty() && shopId.isNotEmpty()) {

            firstNameDelivery = edit_text_first_name_pickup.text.toString()
            lastNameDelivery = edit_text_last_name_pickup.text.toString()
            emailDelivery = edit_text_email_pickup.text.toString()
            phoneNumberDelivery = edit_text_phone_number_pickup.text.toString()

            showInputPickup()
            putDeliveryInfo(true)
        }
    }

    private fun showDeliveryLocation(address: String = "", province: String = "") {

        if (layout_delivery_location == null) return
        ctv_save_pickup.visibility = View.GONE
        ctv_edit_pickup.visibility = View.GONE
        layout_delivery_location.visibility = View.VISIBLE
        radio_pick.isChecked = false
        radio_delivery.isChecked = true
        layout_pick_up.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
        layout_delivery.setBackgroundResource(R.drawable.bg_box_white_stroke_primary)

        image_view_edit.visibility = View.GONE
        layout_pick_location.visibility = View.GONE
        tv_pick_des.visibility = View.GONE
        view_input_pickup.visibility = View.GONE
        view_show_pickup.visibility = View.GONE


        if (TextUtils.isEmpty(address) && TextUtils.isEmpty(province)) {
            OrderingManager.getInstance().locationModel = SeatelShopLocationModel("", "")
            showDeliveryInput()
        } else {
            OrderingManager.getInstance().locationModel = SeatelShopLocationModel(address, province)

            setDataDeliveryDisplayInfo()
            ctv_done_save.visibility = View.GONE
            ctv_done_cancel.visibility = View.GONE
            ctv_edit_delivery.visibility = View.VISIBLE
            view_show_delivery.visibility = View.VISIBLE
            view_input_delivery.visibility = View.GONE
            checkIsInfoAddressUpdated()
        }

    }

    private fun updateData(data: SeatelShopLocationModel, initial: Boolean = false) {
        if (tmpDeliveryStatus == OrderingManager.DeliverStatus.PICKUP) {
            OrderingManager.getInstance().deliverStatus = OrderingManager.DeliverStatus.PICKUP

            layout_pick_up.setBackgroundResource(R.drawable.bg_box_white_stroke_primary)
            radio_pick.isChecked = true
            image_view_edit.visibility = View.VISIBLE
            image_view_edit.setOnClickListener(this)
            layout_pick_location.visibility = View.VISIBLE
            tv_pick_des.visibility = View.VISIBLE

            showInputPickup()
            shopName = data.name
            shopId = data.id
            if (initial) tempShopId = shopId

            layout_delivery.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
            view_title_delivery.setOnClickListener(this)
            radio_delivery.isChecked = false
            layout_delivery_location.visibility = View.GONE

            setDataPickupDisplayInfo()
            tv_pick_des.text = data.address
            tv_pick_location.text = data.name
            if (data.address.isEmpty() && data.name.isEmpty()) radio_pick.isChecked = false
            if (!initial) saveAddressPickupAfterSelectYesHub()
        } else if (tmpDeliveryStatus == OrderingManager.DeliverStatus.DELIVERY) {
            OrderingManager.getInstance().deliverStatus = OrderingManager.DeliverStatus.DELIVERY

            layout_delivery.setBackgroundResource(R.drawable.bg_box_white_stroke_primary)
            radio_delivery.isChecked = true
            ctv_edit_delivery.visibility = View.VISIBLE
            ctv_edit_delivery.setOnClickListener(this)
            layout_delivery_location.visibility = View.VISIBLE

            layout_pick_up.setBackgroundResource(R.drawable.bg_box_white_stroke_grey)
            view_title_pickup.setOnClickListener(this)
            radio_pick.isChecked = false
            image_view_edit.visibility = View.GONE
            layout_pick_location.visibility = View.GONE
            tv_pick_des.visibility = View.GONE
            view_input_pickup.visibility = View.GONE
            view_show_pickup.visibility = View.GONE

            if (initial) {
                if (checkIsEmptyAll()) {
                    ctv_done_save.visibility = View.VISIBLE
                    ctv_done_cancel.visibility = View.VISIBLE
                    ctv_edit_delivery.visibility = View.GONE
                    view_input_delivery.visibility = View.VISIBLE
                    view_show_delivery.visibility = View.GONE
                } else {
                    ctv_done_save.visibility = View.GONE
                    ctv_done_cancel.visibility = View.GONE
                    ctv_edit_delivery.visibility = View.VISIBLE
                    view_input_delivery.visibility = View.GONE
                    view_show_delivery.visibility = View.VISIBLE
                }
            } else {
                ctv_done_save.visibility = View.GONE
                ctv_done_cancel.visibility = View.GONE
                ctv_edit_delivery.visibility = View.VISIBLE
                view_input_delivery.visibility = View.GONE
                view_show_delivery.visibility = View.VISIBLE
            }
        }
    }


}