package com.dahe.pass.ui.home.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.Toast
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.dahe.mylibrary.base.BaseActivity
import com.dahe.mylibrary.net.CommonResponseBean
import com.dahe.pass.R
import com.dahe.pass.bean.*
import com.dahe.pass.net.BaseObserver
import com.dahe.pass.net.DataManager
import com.dahe.pass.net.RxHttpCallBack
import com.dahe.pass.utils.GetJsonDataUtil
import com.dahe.pass.utils.SPUtils
import com.google.gson.Gson
import com.lxj.xpopup.util.KeyboardUtils
import kotlinx.android.synthetic.main.activity_apply.*
import org.json.JSONArray
import java.util.ArrayList

/**
 * @ClassName ApplyActivity
 * @Author 用户
 * @Date 2022/1/13 15:42
 * @Description TODO
 */
class ApplyActivity : BaseActivity(), View.OnClickListener {

    lateinit var curCompanyBean: CompanyBean
    lateinit var curCompanyType: CompanyTypeBean
    lateinit var jb: String
    lateinit var sheng: String
    lateinit var shi: String
    lateinit var xian: String


    override fun getLayout() = R.layout.activity_apply

    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarCancelLightColor()
        setTitleBar("申请") { finish() }
        tvSpdw.setOnClickListener(this)
        tvDz.setOnClickListener(this)
        tvSub.setOnClickListener(this)
        llQylx.setOnClickListener(this)
        tvJb.setOnClickListener(this)
        tvSflx.setOnClickListener(this)

        val userInfo = SPUtils.getUserInfo(this).userInfo
        if (null!=userInfo){
            etLxr.text = userInfo.contacts
            etPhone.text = userInfo.contactsPhone
        }


    }

    override fun initDate() {
        DataManager.getInstance().userInfo
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<BusInfoBean>() {
                override fun onSuccess(t: CommonResponseBean<BusInfoBean>?) {
                    super.onSuccess(t)
                    etQymc.text = t?.data?.enterpriseName

                }
            }))
    }

    override fun onClick(view: View) {
        super.onClick(view)
        when (view.id) {
            R.id.tvSpdw -> spdw()
            R.id.tvSub -> sub()
            R.id.tvDz -> {
                KeyboardUtils.hideSoftInput(etQymc)
                if (isLoaded) {
                    setProText()
                } else {
                    mHandler.sendEmptyMessage(MSG_LOAD_DATA)
                }
            }

            R.id.llQylx -> qymc()
            R.id.tvJb -> gjjb()
            R.id.tvSflx -> freeOrBuy()
        }
    }

    fun freeOrBuy() {
        KeyboardUtils.hideSoftInput(etPhone)
        val mutableListOf = mutableListOf<CompanyBean>()
        val build = OptionsPickerBuilder(mContext
        ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
            mutableListOf.get(options1).signName
            tvSflx.text = mutableListOf.get(options1).signName
        }
            .setTitleText("收费类型")
            .setContentTextSize(20) //设置滚轮文字大小
            .setDividerColor(Color.LTGRAY) //设置分割线的颜色
            .setSelectOptions(0, 1) //默认选中项
            .setTitleColor(Color.BLACK)
            .setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
            .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
            .setTitleBgColor(Color.parseColor("#FFFFFF"))
            .setBgColor(Color.parseColor("#F5F5F5"))
            .setTextColorCenter(Color.LTGRAY)
            .isRestoreItem(true) //切换时是否还原，设置默认选中第一项。
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setLabels("", "", "")
//            .setOutSideColor(0x00000000) //设置外部遮罩颜色
            .setOptionsSelectChangeListener { options1, options2, options3 ->
                val str =
                    "options1: $options1\noptions2: $options2\noptions3: $options3"
//                Toast.makeText(this@MainActivity, str, Toast.LENGTH_SHORT).show()
            }
            .build<CompanyBean>()
        mutableListOf.add(CompanyBean("免费", "0"))
        mutableListOf.add(CompanyBean("收费", "1"))



        build.setPicker(mutableListOf)

        build.show()
    }


    fun gjjb() {
        KeyboardUtils.hideSoftInput(etQymc)
        val mutableListOf = mutableListOf<CompanyBean>()
        val build = OptionsPickerBuilder(mContext
        ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
            jb = mutableListOf.get(options1).signName
            tvJb.text = mutableListOf.get(options1).signName
        }
            .setTitleText("国家等级")
            .setContentTextSize(20) //设置滚轮文字大小
            .setDividerColor(Color.LTGRAY) //设置分割线的颜色
            .setSelectOptions(0, 1) //默认选中项
            .setTitleColor(Color.BLACK)
            .setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
            .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
            .setTitleBgColor(Color.parseColor("#FFFFFF"))
            .setBgColor(Color.parseColor("#F5F5F5"))
            .setTextColorCenter(Color.LTGRAY)
            .isRestoreItem(true) //切换时是否还原，设置默认选中第一项。
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setLabels("", "", "")
//            .setOutSideColor(0x00000000) //设置外部遮罩颜色
            .setOptionsSelectChangeListener { options1, options2, options3 ->
                val str =
                    "options1: $options1\noptions2: $options2\noptions3: $options3"
//                Toast.makeText(this@MainActivity, str, Toast.LENGTH_SHORT).show()
            }
            .build<CompanyBean>()
        mutableListOf.add(CompanyBean("2A"))
        mutableListOf.add(CompanyBean("3A"))
        mutableListOf.add(CompanyBean("4A"))
        mutableListOf.add(CompanyBean("5A"))
        mutableListOf.add(CompanyBean("其他"))



        build.setPicker(mutableListOf)

        build.show()
    }


    fun spdw() {
        KeyboardUtils.hideSoftInput(etQymc)
        DataManager.getInstance().companyLst()
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<List<CompanyBean>>(this) {
                override fun onSuccess(t: CommonResponseBean<List<CompanyBean>>) {
                    super.onSuccess(t)
                    val data = t.data


                    val mutableListOf = mutableListOf<CompanyBean>()
                    val build = OptionsPickerBuilder(mContext
                    ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
                        curCompanyBean = mutableListOf.get(options1)
                        tvSpdw.text = mutableListOf.get(options1).signName
                    }
                        .setTitleText("审批单位")
                        .setContentTextSize(20) //设置滚轮文字大小
                        .setDividerColor(Color.LTGRAY) //设置分割线的颜色
                        .setSelectOptions(0, 1) //默认选中项
                        .setTitleColor(Color.BLACK)
                        .setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
                        .setTitleBgColor(Color.parseColor("#FFFFFF"))
                        .setBgColor(Color.parseColor("#F5F5F5"))
                        .setTextColorCenter(Color.LTGRAY)
                        .isRestoreItem(true) //切换时是否还原，设置默认选中第一项。
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .setLabels("", "", "")
//            .setOutSideColor(0x00000000) //设置外部遮罩颜色
                        .setOptionsSelectChangeListener { options1, options2, options3 ->
                            val str =
                                "options1: $options1\noptions2: $options2\noptions3: $options3"
//                Toast.makeText(this@MainActivity, str, Toast.LENGTH_SHORT).show()
                        }
                        .build<CompanyBean>()

                    data.forEach {
                        mutableListOf.add(it)
                    }



                    build.setPicker(mutableListOf)

                    build.show()

                }
            }))


    }

    fun qymc() {
        KeyboardUtils.hideSoftInput(etQymc)
        if (!::curCompanyBean.isInitialized) {
            showToast("请选择审批单位")
            return
        }
        DataManager.getInstance().typeLst(curCompanyBean.sign)
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<List<CompanyTypeBean>>(this) {
                override fun onSuccess(t: CommonResponseBean<List<CompanyTypeBean>>) {
                    super.onSuccess(t)
                    val data = t.data


                    val mutableListOf = mutableListOf<CompanyTypeBean>()
                    val build = OptionsPickerBuilder(mContext
                    ) { options1, options2, options3, v -> //返回的分别是三个级别的选中位置
                        if (options1 >= mutableListOf.size)
                            return@OptionsPickerBuilder
                        curCompanyType = mutableListOf.get(options1)
                        tvQylx.text = mutableListOf.get(options1).enterpriseTypeName
                    }
                        .setTitleText("企业类型")
                        .setContentTextSize(20) //设置滚轮文字大小
                        .setDividerColor(Color.LTGRAY) //设置分割线的颜色
                        .setSelectOptions(0, 1) //默认选中项
                        .setTitleColor(Color.BLACK)
                        .setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
                        .setTitleBgColor(Color.parseColor("#FFFFFF"))
                        .setBgColor(Color.parseColor("#F5F5F5"))
                        .setTextColorCenter(Color.LTGRAY)
                        .isRestoreItem(true) //切换时是否还原，设置默认选中第一项。
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .setLabels("", "", "")
//            .setOutSideColor(0x00000000) //设置外部遮罩颜色
                        .setOptionsSelectChangeListener { options1, options2, options3 ->
                            val str =
                                "options1: $options1\noptions2: $options2\noptions3: $options3"
//                Toast.makeText(this@MainActivity, str, Toast.LENGTH_SHORT).show()
                        }
                        .build<CompanyTypeBean>()

                    data.forEach {
                        mutableListOf.add(it)
                    }



                    build.setPicker(mutableListOf)

                    build.show()

                }
            }))
    }

    fun sub() {

        if (!::curCompanyBean.isInitialized || !::jb.isInitialized ||
            !::shi.isInitialized || etQymc.text.toString().isNullOrEmpty() ||
            etLxr.text.toString().isNullOrEmpty() || etPhone.text.toString().isNullOrEmpty() ||
            etCl.text.toString().isNullOrEmpty() || etTxz.text.toString().isNullOrEmpty()
        ) {
            showToast("请完善信息")
            return
        }

        val applySendBean = ApplySendBean()
        applySendBean.sign = curCompanyBean.sign
        applySendBean.enterpriseName = etQymc.text.toString()
//        applySendBean.typeId = curCompanyType.typeId
        applySendBean.provinceName = sheng
        applySendBean.cityName = shi
        applySendBean.countyName = xian
        applySendBean.nationalClassA = jb
        applySendBean.enterpriseContact = etLxr.text.toString()
        applySendBean.enterpriseContactPhone = etPhone.text.toString()
        applySendBean.vehiclesNumber = etCl.text.toString()
        applySendBean.numberOfPassesRequired = etTxz.text.toString()
//        applySendBean.chargeType = tvSflx.text.toString()

        DataManager.getInstance().applySend(applySendBean)
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<Any>() {
                override fun onSuccess(t: CommonResponseBean<Any>?) {
                    super.onSuccess(t)
                    showToast("申请成功")
                    finish()
                }
            }))
    }


    private var options1Items = ArrayList<JsonBean>()
    private val options2Items = ArrayList<ArrayList<String>>()
    private val options3Items = ArrayList<ArrayList<ArrayList<String>>>()
    private val MSG_LOAD_DATA = 0x0001
    private val MSG_LOAD_SUCCESS = 0x0002
    private val MSG_LOAD_FAILED = 0x0003
    private var thread: Thread? = null
    private var isLoaded = false


    private fun setProText() {
        val pvOptions: OptionsPickerView<*> = OptionsPickerBuilder(this@ApplyActivity
        ) { options1, options2, options3, v ->
            //返回的分别是三个级别的选中位置
            val opt1tx =
                if (options1Items.size > 0) options1Items.get(options1).getPickerViewText() else ""
            val opt2tx = if (options2Items.size > 0
                && options2Items.get(options1).size > 0
            ) options2Items.get(options1).get(options2) else ""
            val opt3tx =
                if (options2Items.size > 0 && options3Items.get(options1).size > 0 && options3Items.get(
                        options1).get(options2).size > 0
                ) options3Items.get(options1).get(options2).get(options3) else ""
            sheng = opt1tx
            shi = opt2tx
            xian = opt3tx
            val tx = "$opt1tx-$opt2tx-$opt3tx"
            tvDz.text = tx
//            val userBean = UserBean()
//            userBean.setAddress(tx)
//            DataManager.getInstance().editObj(userBean)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(BaseObserver(mContext, object : RxHttpCallBack() {
//                    fun onSuccess(t: CommonResponseBean?) {
//                        super.onSuccess(t)
//                        userInfo.setAddress(tx)
//                        SPUtils.setUserInfo(this@MyInfoActivity,
//                            JsonUtils.getInstance().getGson().toJson(userInfo))
//                    }
//                }))


            //                            Toast.makeText(MyInfoActivity.this, tx, Toast.LENGTH_SHORT).show();
        }
            .setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
            .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
            .setTitleBgColor(Color.parseColor("#FFFFFF"))
            .setBgColor(Color.parseColor("#F5F5F5"))
            .setSelectOptions(15, 0, 0)
            .setContentTextSize(20)
            .build<Any>()
        pvOptions.setPicker(options1Items as List<Nothing>?,
            options2Items as List<Nothing>?, options3Items as List<Nothing>?) //三级选择器
        pvOptions.show()
    }

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

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

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

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MSG_LOAD_DATA -> if (thread == null) { //如果已创建就不再重新创建子线程了
                    thread = Thread { // 子线程中解析省市区数据
                        initJsonData()
                    }
                    thread?.start()
                }
                MSG_LOAD_SUCCESS -> {
                    //                    Toast.makeText(MyInfoActivity.this, "Parse Succeed", Toast.LENGTH_SHORT).show();
                    setProText()
                    isLoaded = true
                }
                MSG_LOAD_FAILED -> Toast.makeText(this@ApplyActivity,
                    "地区解析失败",
                    Toast.LENGTH_SHORT).show()
            }
        }
    }
}