package com.zxhl.main.page.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.zxhl.cms.AppContext
import com.zxhl.cms.common.base.BaseActivity
import com.zxhl.cms.net.model.box.AddressEntity
import com.zxhl.cms.utils.GetJsonDataUtil
import com.zxhl.cms.utils.Utils
import com.zxhl.main.R
import com.zxhl.main.page.contract.EditAddressContract
import com.zxhl.main.page.entity.AddressBean
import com.zxhl.main.page.presenter.EditAddressPresenter
import kotlinx.android.synthetic.main.activity_layout_edit_address.*
import org.json.JSONArray
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList


class EditAddressActivity : BaseActivity(), EditAddressContract.View {
    private var enity: AddressEntity? = null
    private var mPresenter: EditAddressPresenter? = null
    private var defaultAddress: String = "0"

    private var addressList: ArrayList<AddressBean> = ArrayList() //城市
    private var addressCountryList: ArrayList<String> = ArrayList() //国家

    private var isInitSelect = true

    override fun onClick(v: View?) {

    }

    override fun layoutID(): Int {
        return R.layout.activity_layout_edit_address
    }

    override fun before() {
        super.before()
        setStatusBarBackground(AppContext.get().resources.getColor(R.color.white))
    }

    override fun init() {
        initCityData()
        initSelect()

        var username = intent?.data?.getQueryParameter("username") ?: ""
        var mobile = intent?.data?.getQueryParameter("mobile") ?: ""
      //  var region = intent?.data?.getQueryParameter("region") ?: ""
        var address = intent?.data?.getQueryParameter("address") ?: ""
        var address2 = intent?.data?.getQueryParameter("address2") ?: ""
        var province = intent?.data?.getQueryParameter("province") ?: ""
        var city = intent?.data?.getQueryParameter("city") ?: ""
        var country = intent?.data?.getQueryParameter("country") ?: ""
        var id = intent?.data?.getQueryParameter("id") ?: ""
        // id_edit_phone.setFilters(arrayOf<InputFilter>(SpaceFilter()))
        defaultAddress = intent?.data?.getQueryParameter("defaultAddress") ?: ""
        if (defaultAddress.equals("0")) {
            id_img_moren.setImageResource(R.drawable.icon_guan)
        } else {
            id_img_moren.setImageResource(R.drawable.icon_kai)
        }
        id_img_moren?.setOnClickListener {
            if (defaultAddress == "0") {
                defaultAddress = "1"
                id_img_moren.setImageResource(R.drawable.icon_kai)
            } else {
                defaultAddress = "0"
                id_img_moren.setImageResource(R.drawable.icon_guan)
            }
        }
        //国家选择
        id_select_country.setOnClickListener {
            isInitSelect = false
            id_country_select_spinner.performClick()

        }
//        //城市选择
//        id_select_city?.setOnClickListener {
////            hideKeyBoard()
//            isInitSelect = false
//            id_city_select_spinner.performClick()
//        }

//        id_select_country?.text = addressList[0].country
//        id_select_city?.text = addressList[0].cityLis?.get(0)

        id_edit_name?.setText(username)
        id_edit_phone?.setText(mobile)

        id_edit_address1?.setText(address)
        id_edit_address2?.setText(address2)
        id_edit_province?.setText(province)
        id_select_city?.setText(city)
        id_select_country?.setText(country)
        id_img_back?.setOnClickListener {
            finish()
        }
        mPresenter = EditAddressPresenter(this)
//        id_tv_tongxulu?.setOnClickListener {
//            checkPersion()
//
//        }
        id_tv_save_address?.setOnClickListener {
            if (TextUtils.isEmpty(id_edit_name.text.toString()) || TextUtils.isEmpty(id_edit_phone.text.toString()) || TextUtils.isEmpty(
                    id_edit_address1.text.toString()
                ) || TextUtils.isEmpty(id_edit_address2.text.toString()) || TextUtils.isEmpty(
                    id_select_city.text.toString()
                ) || TextUtils.isEmpty(id_select_country.text.toString()) || TextUtils.isEmpty(
                    id_edit_province.text.toString()
                )
            ) {
//                Utils.showToast(AppContext.get(), "请完整填写信息")
                return@setOnClickListener
            } else {
//                if (id_edit_phone.text.toString()?.length != 11) {
////                    Utils.showToast(AppContext.get(), "请检查手机号码")
//                    return@setOnClickListener
//                }
                enity = AddressEntity()
                if (!TextUtils.isEmpty(id)) {
                    enity?.id = id
                }
                enity?.username = id_edit_name.text.toString().trim()
                enity?.mobile = id_edit_phone.text.toString().trim()
               // enity?.region = id_select_city.text.toString().trim()
                enity?.address = id_edit_address1.text.toString().trim()
                enity?.address2 = id_edit_address2.text.toString().trim()
                enity?.province = id_edit_province.text.toString().trim()
                enity?.city = id_select_city.text.toString().trim()
                enity?.country = id_select_country.text.toString().trim()
                enity?.defaultAddress = "1"
                mPresenter?.editAddress(enity)
            }

        }
    }


    fun checkPersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //获取权限（如果没有开启权限，会弹出对话框，询问是否开启权限）
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_CONTACTS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                //请求权限
                ActivityCompat.requestPermissions(
                    this, arrayOf(
                        Manifest.permission.READ_CONTACTS
                    ), 100
                )
            } else {
                val uri: Uri = Uri.parse("content://contacts/people")
                val intent = Intent(Intent.ACTION_PICK, uri)
                startActivityForResult(intent, 0)
            }
        }


    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            100 -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被用户同意。
                    val uri: Uri = Uri.parse("content://contacts/people")
                    val intent = Intent(Intent.ACTION_PICK, uri)
                    startActivityForResult(intent, 0)
                } else {
                    // 权限被用户拒绝了。
                    if (!ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                        || !ActivityCompat.shouldShowRequestPermissionRationale(
                            this,
                            Manifest.permission.ACCESS_COARSE_LOCATION
                        )
                    ) {
                        //提示用户前往设置界面自己打开权限
                        Toast.makeText(this, "请前往设置界面打开权限", Toast.LENGTH_SHORT).show()
                        return
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            0 -> {
                if (data == null) {
                    return
                }
                //处理返回的data,获取选择的联系人信息
                val uri: Uri? = data.data
                val contacts: Array<String?>? = getPhoneContacts(uri!!)
                id_edit_name.setText(contacts?.get(0))
                id_edit_phone.setText(contacts?.get(1).toString().replace(" ", ""))
            }
        }
        super.onActivityResult(requestCode, resultCode, data)

    }

    private fun getPhoneContacts(uri: Uri): Array<String?>? {
        val contact = arrayOfNulls<String>(2)
        //得到ContentResolver对象
        val cr = contentResolver
        //取得电话本中开始一项的光标
        val cursor: Cursor? = cr.query(uri, null, null, null, null)
        if (cursor != null) {
            cursor.moveToFirst()
            //取得联系人姓名
            val nameFieldColumnIndex: Int =
                cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
            contact[0] = cursor.getString(nameFieldColumnIndex)
            //取得电话号码
            val ContactId: String =
                cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
            val phone: Cursor? = cr.query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                null,
                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId,
                null,
                null
            )
            if (phone != null) {
                phone.moveToFirst()
                contact[1] =
                    phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
            }
            phone?.close()
            cursor.close()
        } else {
            return null
        }
        return contact
    }

    override fun saveSunccess() {
        Utils.showToast(AppContext.get(), "保存成功")
        finish()
    }


    private fun initCityData() {
        //获取assets目录下的地址json文件数据
        val addressJson = GetJsonDataUtil().getJson(this, "address.json")

        val addressObj = JSONObject(addressJson)
        //通过迭代器获取这段json当中所有的key值
        val keys = addressObj.keys()
        //然后通过一个循环取出所有的key值
        while (keys.hasNext()) {
            val key = keys.next()
            val value: JSONArray? = addressObj.optJSONArray(key)
            var addressBean = AddressBean()
            var cityList = ArrayList<String>(value?.length() ?: 0)
            if (value != null && value.length() > 0) {
                for (index in 0 until value.length()) {
                    cityList.add(value.getString(index))
                }
            }
            addressBean.country = key
            addressBean.cityLis = cityList

            addressCountryList.add(key)
            addressList.add(addressBean)
        }
    }

    private fun initSelect() {
        val strAdapter: ArrayAdapter<String> =
            ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, addressCountryList)
        strAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        id_country_select_spinner.adapter = strAdapter
        id_country_select_spinner.onItemSelectedListener =
            object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    Log.d("wxw", " 1select")
                    if (!isInitSelect) {
                        id_select_country?.text = addressCountryList[position]
                    }
                    if (addressList[position].cityLis != null) {
                        initCitySelect(addressList[position].cityLis!!)
                    }
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {
                    Log.d("wxw", " 2select")
                }
            }
//        if (defPos != -1) {
//            id_country_select_spinner.setSelection(defPos)
//        }
    }

    private fun initCitySelect(cityList: ArrayList<String>) {
        val strAdapter: ArrayAdapter<String> =
            ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cityList)
        strAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        id_city_select_spinner.adapter = strAdapter
        id_city_select_spinner.onItemSelectedListener =
            object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    if (!isInitSelect) {
                        // id_select_city?.text = cityList[position]
                    }
                }

                override fun onNothingSelected(parent: AdapterView<*>?) {

                }
            }

    }
}