package com.zxbw.modulemain.box.activity

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.provider.ContactsContract
import android.text.TextUtils
import android.view.View
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.google.gson.Gson
import com.zxbw.modulemain.R
import com.zxbw.modulemain.box.bean.JsonBean
import com.zxbw.modulemain.box.contract.EditAddressContract
import com.zxbw.modulemain.box.presenter.EditAddressPresenter
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 kotlinx.android.synthetic.main.activity_layout_edit_address.*
import org.json.JSONArray


class EditAddressActivity : BaseActivity(), EditAddressContract.View {
    private var enity: AddressEntity? = null
    private var mPresenter: EditAddressPresenter? = null
    private var defaultAddress: String = "0"
    private var options1Items: ArrayList<JsonBean> = ArrayList() //省

    private val options2Items: ArrayList<ArrayList<String>> = ArrayList() //市

    private val options3Items: ArrayList<ArrayList<ArrayList<String>>> = ArrayList() //区

    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() {
        initJsonData()
        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 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.equals("0")) {
                defaultAddress = "1"
                id_img_moren.setImageResource(R.drawable.icon_kai)
            } else {
                defaultAddress = "0"
                id_img_moren.setImageResource(R.drawable.icon_guan)
            }
        }
        id_tv_choose_city?.setOnClickListener {
            hideKeyBoard()
            showPickerView()
        }
        id_edit_name?.setText(username)
        id_edit_phone?.setText(mobile)
        id_tv_choose_city?.setText(region)
        id_edit_address?.setText(address)
        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_tv_choose_city.text.toString()
                ) || TextUtils.isEmpty(id_edit_address.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_tv_choose_city.text.toString().trim()
                enity?.address = id_edit_address.text.toString().trim()
                enity?.defaultAddress = "1"
                mPresenter?.editAddress(enity)
            }

        }
    }

    fun showPickerView() {
        val pvOptions: OptionsPickerView<*> = OptionsPickerBuilder(
            this
        ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
            id_tv_choose_city.setText(
                options1Items[options1].pickerViewText
                        + options2Items[options1][options2]
                        + options3Items[options1][options2][options3]
            )
        }
            .setTitleText("城市选择")
            .setSubmitColor(resources.getColor(R.color.color_333333))
            .setTitleBgColor(Color.WHITE)
            .setCancelColor(resources.getColor(R.color.color_333333))//取消按钮文字颜色
            .setDividerColor(resources.getColor(R.color.color_ededed))
            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
            .setContentTextSize(20)
            .build<Any>()
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(
            options1Items as List<Nothing>?,
            options2Items as List<Nothing>?, options3Items as List<Nothing>?
        ) //三级选择器

        pvOptions.show()

    }

    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()
    }

    fun parseData(result: String?): ArrayList<JsonBean>? { //Gson 解析
        val detail: ArrayList<JsonBean> = ArrayList()
        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()
        }
        return detail
    }

    private fun initJsonData() { //解析数据 （省市区三级联动）
        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         */
        val JsonData = GetJsonDataUtil().getJson(this, "province.json") //获取assets目录下的json文件数据
        val jsonBean = parseData(JsonData) //用Gson 转成实体
        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean!!
        for (i in 0 until jsonBean.size) { //遍历省份
            val CityList: ArrayList<String> = ArrayList() //该省的城市列表（第二级）
            val Province_AreaList: ArrayList<ArrayList<String>> = ArrayList() //该省的所有地区列表（第三级）
            for (c in 0 until jsonBean[i].cityList.size) { //遍历该省份的所有城市
                val CityName = jsonBean[i].cityList[c].name
                CityList.add(CityName) //添加城市
                val City_AreaList: ArrayList<String> = ArrayList() //该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean[i].cityList[c].area == null
                    || jsonBean[i].cityList[c].area.size === 0
                ) {
                    City_AreaList.add("")
                } else {
                    City_AreaList.addAll(jsonBean[i].cityList[c].area)
                }
                Province_AreaList.add(City_AreaList) //添加该省所有地区数据
            }
            /**
             * 添加城市数据
             */
            options2Items.add(CityList)
            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList)
        }
    }

}