package com.dahe.pass.ui.gone.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.InputFilter
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.view.OptionsPickerView
import com.dahe.mylibrary.base.BaseActivity
import com.dahe.mylibrary.net.CommonResponseBean
import com.dahe.mylibrary.utils.TimeUtil
import com.dahe.mylibrary.weight.NumRangeInputFilter
import com.dahe.pass.R
import com.dahe.pass.base.AppConfig
import com.dahe.pass.bean.JsonBean
import com.dahe.pass.bean.PassBean
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_add_go.*
import kotlinx.android.synthetic.main.activity_edit_go.*
import kotlinx.android.synthetic.main.activity_edit_go.etCarNum
import kotlinx.android.synthetic.main.activity_edit_go.etCardId
import kotlinx.android.synthetic.main.activity_edit_go.etDs
import kotlinx.android.synthetic.main.activity_edit_go.etName
import kotlinx.android.synthetic.main.activity_edit_go.etPhone
import kotlinx.android.synthetic.main.activity_edit_go.etQd
import kotlinx.android.synthetic.main.activity_edit_go.etWpzl
import kotlinx.android.synthetic.main.activity_edit_go.etZd
import kotlinx.android.synthetic.main.activity_edit_go.tvBz
import kotlinx.android.synthetic.main.activity_edit_go.tvETime
import kotlinx.android.synthetic.main.activity_edit_go.tvEndTime
import kotlinx.android.synthetic.main.activity_edit_go.tvSTime
import kotlinx.android.synthetic.main.activity_edit_go.tvSflx
import kotlinx.android.synthetic.main.activity_edit_go.tvStartTime
import kotlinx.android.synthetic.main.activity_edit_go.tvSub
import kotlinx.android.synthetic.main.activity_edit_go.tvTxbh
import kotlinx.android.synthetic.main.activity_edit_go.tvUpTime
import org.json.JSONArray
import java.text.SimpleDateFormat
import java.util.*

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

    lateinit var passBean: PassBean
    override fun getLayout() = R.layout.activity_edit_go

    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarCancelLightColor()
        setTitleBar("编辑车辆") { finish() }
        tvSub.setOnClickListener(this)
        tvUpTime.setOnClickListener(this)

        etDs.filters = arrayOf<InputFilter>(NumRangeInputFilter())
    }

    override fun initDate() {
        val extras = intent.extras
        passBean = extras?.getSerializable(AppConfig.BEAN) as PassBean
        if (null!=passBean){
            tvTxbh.setText(passBean.passNo)
            etCarNum.setText(passBean.vehicle)
            etDs.setText(passBean.transportTonnage)
            etQd.setText(passBean.startPoint)
            etZd.setText(passBean.endPoint)
            tvBz.setText(passBean.remarks)

            tvSTime.text = passBean.useStartTime
            tvETime.text = passBean.useEndTime
            etName.text = passBean.driverName
            etPhone.text = passBean.driverPhone
            etWpzl.text = passBean.itemTypeName
            tvStartTime.text = passBean.startTime
            tvEndTime.text = passBean.endTime
            tvSflx.text = passBean.chargeType
            etCardId.text = passBean.driverIdcard
        }
    }

    override fun onClick(view: View) {
        super.onClick(view)
        when (view.id) {
//            R.id.tvSpdw -> spdw()
            R.id.tvSub -> sub()
            R.id.tvUpTime -> setBir(2, tvUpTime)
        }
    }

    fun sub() {
        KeyboardUtils.hideSoftInput(tvTxbh)
        if (tvTxbh.text.toString().isNullOrEmpty() || tvSTime.text.toString().isNullOrEmpty() ||
            etCarNum.text.toString().isNullOrEmpty() || etName.text.toString().isNullOrEmpty() ||
            etPhone.text.toString().isNullOrEmpty() || etWpzl.text.toString().isNullOrEmpty() ||
            etDs.text.toString().isNullOrEmpty() || etQd.text.toString().isNullOrEmpty()
        ) {
            showToast("请完善信息")
            return
        }


        val passBean = PassBean()
        passBean.infoId = EditGoActivity@this.passBean.infoId
        passBean.passNo = tvTxbh.text.toString()
        passBean.vehicle = etCarNum.text.toString()
        passBean.transportTonnage = etDs.text.toString()
        passBean.startPoint = etQd.text.toString()
        passBean.endPoint = etZd.text.toString()
        passBean.useDate = tvUpTime.text.toString()

        DataManager.getInstance().detailEdit(passBean)
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<Any>() {
                override fun onSuccess(t: CommonResponseBean<Any>?) {
                    super.onSuccess(t)
                    showToast("修改成功")
                    finish()
                }
            }))
    }


    fun setBir(type: Int, view: TextView) {
        KeyboardUtils.hideSoftInput(tvTxbh)
        val startDate = Calendar.getInstance()
        val endtDate = Calendar.getInstance()
        val currDate = Calendar.getInstance()
        startDate[1990, 0] = 1
        endtDate[2100, 0] = 1


        if (!TextUtils.isEmpty(view.getText())) {
            val date = TimeUtil.string2Date(view.getText().toString(),
                SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
            if (date != null) currDate.time = date
        }


        val pvTime = TimePickerBuilder(
            mContext
        ) { date, v -> //选中事件回调
//            TimeUtil.date2String(date,SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
            val data =
                TimeUtil.date2String(date,
                    SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
            view.text = data
        }.setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
            .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
            .setTitleBgColor(Color.parseColor("#FFFFFF"))
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .setTitleText("选择时间")
            .setDate(currDate)
            .setRangDate(startDate, endtDate)
            .setBgColor(Color.parseColor("#F5F5F5"))
            .build()
        //                 pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show()
    }


    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@EditGoActivity
        ) { 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"
//            tvDz.text = tx
        }
            .setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
            .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
            .setTitleBgColor(Color.parseColor("#FFFFFF"))
            .setBgColor(Color.parseColor("#F5F5F5"))
            .setContentTextSize(20)
            .setSelectOptions(15, 0, 0)
            .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@EditGoActivity,
                    "地区解析失败",
                    Toast.LENGTH_SHORT).show()
            }
        }
    }
}