package com.dahe.pass.ui.account.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.mylibrary.utils.ActivityUtils
import com.dahe.pass.R
import com.dahe.pass.base.AppConfig
import com.dahe.pass.bean.BusInfoBean
import com.dahe.pass.bean.CompanyBean
import com.dahe.pass.bean.JsonBean
import com.dahe.pass.net.BaseObserver
import com.dahe.pass.net.DataManager
import com.dahe.pass.net.RxHttpCallBack
import com.dahe.pass.ui.account.LoginActivity
import com.dahe.pass.utils.AppActivityUtils
import com.dahe.pass.utils.GetJsonDataUtil
import com.google.gson.Gson
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.util.KeyboardUtils
import kotlinx.android.synthetic.main.activity_add_go.*
import kotlinx.android.synthetic.main.activity_apply.*
import kotlinx.android.synthetic.main.activity_apply.etPhone
import kotlinx.android.synthetic.main.activity_business_info.*
import kotlinx.android.synthetic.main.activity_business_info.etQymc
import org.json.JSONArray
import java.util.ArrayList

/**
 * @ClassName BusinessInfoActivity
 * @Author 用户
 * @Date 2022/1/14 14:58
 * @Description TODO
 */
class BusinessInfoActivity : BaseActivity(), View.OnClickListener {
    lateinit var curCompanyBean: CompanyBean

    override fun getLayout() = R.layout.activity_business_info

    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarColor(R.color.white)
        btnGo.setOnClickListener(this)
        tv_yhxy.setOnClickListener(this)
        tv_yszc.setOnClickListener(this)
        etDj.setOnClickListener(this)
        etDz.setOnClickListener(this)
        etSpdw.setOnClickListener(this)
    }

    override fun initDate() {
    }

    override fun onClick(view: View) {
        super.onClick(view)
        when (view.id) {
            R.id.btnGo -> go()
            R.id.etDz -> {
                KeyboardUtils.hideSoftInput(etQymc)
                if (isLoaded) {
                    setProText()
                } else {
                    mHandler.sendEmptyMessage(MSG_LOAD_DATA)
                }
            }

            R.id.tv_yhxy -> AppActivityUtils.openWebViewActivity(this,
                "用户服务协议",
                "https://downtest.dahehuodongbao.com/passcheck/user-agreement.html");
            R.id.tv_yszc -> AppActivityUtils.openWebViewActivity(this, "隐私政策",
                "https://downtest.dahehuodongbao.com/passcheck/user-privacy.html")
            R.id.etDj -> {
                XPopup.Builder(this).hasShadowBg(false).offsetY(50).atView(etDj)
                    .popupWidth(500)
                    .asAttachList(arrayOf("2A", "3A", "4A", "5A", "其他"),
                        null,
                        { position, text -> etDj.text = text }).show()
            }

            R.id.etSpdw -> spdw()
        }
    }

    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)
                        etSpdw.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 go() {
        val qymc = etQymc.text.toString()
//        val ywlx = etYwlx.text.toString()
        val etDz = etDz.text.toString()
        val etTbr = etTbr.text.toString()

        if (qymc.isNullOrEmpty()) {
            showToast("请输入企业名称")
            return
        }

        if (etDz.isNullOrEmpty()) {
            showToast("请输入注册地址")
            return
        }

        if (!::curCompanyBean.isInitialized) {
            showToast("请完善审批单位")
            return
        }

        if (etNsr.text.toString().isNullOrEmpty() || etFzr.text.toString().isNullOrEmpty() ||
            etFzrPhone.text.toString().isNullOrEmpty() || etDj.text.toString().isNullOrEmpty() ||
            etGsdz.text.toString().isNullOrEmpty()
        ) {
            showToast("请完善信息")
            return
        }

        val extras = intent.extras
        val bean: BusInfoBean = extras?.getSerializable(AppConfig.BEAN) as BusInfoBean

        val busInfoBean = BusInfoBean()
        val paramsDao = BusInfoBean.ParamsDao()
        paramsDao.code = bean.params.code
        busInfoBean.phone = bean.phone
        busInfoBean.params = paramsDao
        busInfoBean.pwd = bean.pwd
        busInfoBean.unifiedSocialCreditCode = etNsr.text.toString()
        busInfoBean.enterpriseName = qymc
        busInfoBean.nationalClassA = etDj.text.toString()
        busInfoBean.approvedBy = curCompanyBean.sign
//        busInfoBean.businessType = ywlx
        busInfoBean.placeOfRegistration = etDz
        busInfoBean.companyAddress = etGsdz.text.toString()
//        busInfoBean.plantAddress = etCqdz.text.toString()
        busInfoBean.contacts = etFzr.text.toString()
        busInfoBean.contactsPhone = etFzrPhone.text.toString()
        busInfoBean.name = etTbr



        DataManager.getInstance().register(busInfoBean)
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<Any>() {
                override fun onSuccess(t: CommonResponseBean<Any>?) {
                    super.onSuccess(t)
                    ActivityUtils.finishOtherActivities(LoginActivity::class.java)
                }
            }))
    }


    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
        ) { 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 ""
            val tx = "$opt1tx-$opt2tx-$opt3tx"
            etDz.text = tx
        }
            .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@BusinessInfoActivity,
                    "地区解析失败",
                    Toast.LENGTH_SHORT).show()
            }
        }
    }
}