package com.lukouguoji.gnc.activity

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.*
import android.widget.AdapterView.OnItemSelectedListener
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.viewModel.GoutStartViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.MyApplication
import com.lukouguoji.module_base.adapter.bindAdapter
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.util.Arith
import com.lukouguoji.module_base.util.Common
import dev.utils.app.info.KeyValue
import dev.utils.common.StringUtils
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.abs


@Route(path = ARouterConstants.ACTIVITY_URL_GOUT_START_COT_ACTIVITY)
class GoutStartCotActivity : BaseActivity(), View.OnClickListener ,OnItemSelectedListener{
    private lateinit var checkintongdao:Spinner
    private lateinit var check: TextView
    private lateinit var fenDou: TextView
    private lateinit var finishCollect: TextView
//    private lateinit var reset: TextView
    private lateinit var labelPrint: CheckBox
    private lateinit var viewModel: GoutStartViewModel

    private lateinit var wbNo: EditText
    private lateinit var wbNoScan: ImageView
    private lateinit var uldScan: ImageView
    private lateinit var uld: EditText
//    private lateinit var uldScan: ImageView
    private lateinit var uldWeight: EditText
    private lateinit var carrier: EditText
    private lateinit var fno: EditText
    private lateinit var fdate: Button
    private lateinit var flight1: EditText
    private lateinit var flight2: EditText
    private lateinit var flight3: EditText
    private lateinit var dgrDetail: Spinner
    private lateinit var dgr: Spinner
//    private lateinit var dgrDetailNotNull: TextView
    private lateinit var agentCode: Spinner
    private lateinit var spCode: Spinner
    private lateinit var goods: EditText
    private lateinit var pc: EditText
    private lateinit var weight: EditText
    private lateinit var volume: EditText
    private lateinit var remark: EditText
    private lateinit var dibangWeight: TextView
    private lateinit var dibangWeightScan: ImageView
    private lateinit var volumeInfo: EditText
//    private lateinit var uldStr: EditText
    private lateinit var uldSelfWeight: EditText
   // private lateinit var tongdaoName:String
  //  private lateinit var weightThread:Thread
    /*
    tw:2022年4月27日15:23:52 下拉框改用 singleSelect 所以注释掉 6个月后可删除
    private val agentCodeList = arrayListOf<String>()
    private val businessList = arrayListOf<String>()
    private val specialCodeList = JSONArray()
    private val dgrDetailList = JSONArray()*/

    //    var simpleDateYMDFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
    var simpleDateFormat = SimpleDateFormat("yyyy-MM-dd")

    @JvmField
    @Autowired
    var wbId: Int = -9999

    @JvmField
    @Autowired
    var wbNoParam: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_check_in)
        setBackArrow("国内出港开始收运")
        viewModel = ViewModelProvider(this).get(GoutStartViewModel::class.java)
        initView()
        val dgrObj = JSONObject()
        dgrObj["name"] = "请选择"
        dgrObj["code"] = ""
        viewModel.dgrDetailList.add(dgrObj)

        viewModel.queryWaybillById(wbId, wbNoParam)
        viewModel.waybillLiveData.observe(this) {
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                var jsonObject = it.getJSONObject("data")
                viewModel.waybillFormNetWork = jsonObject

                val checkIn = jsonObject.getString("checkIn")
                if (checkIn == "1") {
                    Common.showToast(this, "该订单收运已完成，不可再收运！")
                    return@observe
                }
                viewModel.guoneiOutWaybill.activeId = jsonObject.getIntValue("activeId")
                viewModel.guoneiOutWaybill.awbType = jsonObject.getString("awbType")
                viewModel.guoneiOutWaybill.mawbId = jsonObject.getIntValue("mawbId")
                viewModel.guoneiOutWaybill.wbNo = jsonObject.getString("wbNo") ?: ""
                viewModel.guoneiOutWaybill.uld = jsonObject.getString("uld") ?: ""
                viewModel.guoneiOutWaybill.carrier = jsonObject.getString("carrier") ?: ""
                viewModel.guoneiOutWaybill.fno = jsonObject.getString("fno") ?: ""
                viewModel.guoneiOutWaybill.fdate = jsonObject.getString("fdate") ?: ""
                viewModel.guoneiOutWaybill.range = jsonObject.getString("range") ?: ""
                viewModel.guoneiOutWaybill.dgrDetail = jsonObject.getString("dgrDetail") ?: ""
                viewModel.guoneiOutWaybill.dgr = jsonObject.getString("dgr") ?: ""
                viewModel.guoneiOutWaybill.agentCode = jsonObject.getString("agentCode") ?: ""
                viewModel.guoneiOutWaybill.spCode = jsonObject.getString("spCode") ?: ""
                viewModel.guoneiOutWaybill.goods = jsonObject.getString("goods") ?: ""
                viewModel.guoneiOutWaybill.pc = jsonObject.getIntValue("pc")
                viewModel.guoneiOutWaybill.weight = jsonObject.getDouble("weight")
                viewModel.guoneiOutWaybill.volume = jsonObject.getDouble("volume")
                viewModel.guoneiOutWaybill.remark = jsonObject.getString("remark") ?: ""

                wbNo.setText(viewModel.guoneiOutWaybill.wbNo)
                uld.setText(viewModel.guoneiOutWaybill.uld)
                carrier.setText(viewModel.guoneiOutWaybill.carrier)
                fno.setText(viewModel.guoneiOutWaybill.fno)
                if (viewModel.guoneiOutWaybill.fdate != "") {
                    var parse = simpleDateFormat.parse(viewModel.guoneiOutWaybill.fdate)
                    fdate.text = simpleDateFormat.format(parse)
                }
                if (viewModel.guoneiOutWaybill.range != "") {
                    var split = viewModel.guoneiOutWaybill.range.split("-")
                    for ((i, item) in split.withIndex()) {
                        if (i == 0) {
                            flight1.setText(item)
                        } else if (i == 1) {
                            flight2.setText(item)
                        } else {
                            flight3.setText(item)
                        }
                    }
                }

//                dgrDetail.setText(viewModel.guoneiOutWaybill.dgrDetail)
//                agentCode.setText(viewModel.guoneiOutWaybill.agentCode)
//                spCode.setsetText(viewModel.guoneiOutWaybill.spCode)
                goods.setText(viewModel.guoneiOutWaybill.goods)
                pc.setText(viewModel.guoneiOutWaybill.pc.toString())
//                dibangWeight.setText(viewModel.guoneiOutWaybill.weight.toString())
                volume.setText(viewModel.guoneiOutWaybill.volume.toString())
                remark.setText(viewModel.guoneiOutWaybill.remark)

                viewModel.weightDataObserver.observe(this){ vd->
                    if(!dibangWeight.text.toString().equals(vd))
                    {
                        dibangWeight.setText(vd)
                    }
                }
                //下拉框赋值
                viewModel.agentCode(System.currentTimeMillis().toString())
                viewModel.agentCodeObserver.observe(this) { vd ->
                    viewModel.agentCodeList = vd.getJSONArray("data")
                    var postion = 0
                    for ((index, obj) in viewModel.agentCodeList.withIndex()) {
                        val tempObj = obj as JSONObject
                        var name = tempObj.getString("name")
                        var code = tempObj.getString("code")
//                        agentCodeList.add(code)
                        if (viewModel.guoneiOutWaybill.agentCode == code) {
                            postion = index
                        }
                    }
                    initSpinner(agentCode, viewModel.agentCodeList, postion,null)
                }

                viewModel.specialCode(System.currentTimeMillis().toString())
                viewModel.specialCodeObserver.observe(this) { vd ->
                    viewModel.specialCodeList = vd.getJSONArray("data")
                    var postion = 0
//                    val specialCodeStrList = arrayListOf<String>()
                    for ((index, obj) in viewModel.specialCodeList.withIndex()) {
                        val tempObj = obj as JSONObject
                        var code = tempObj.getString("code")
                        var name = tempObj.getString("name")
//                        specialCodeList.add(tempObj)
//                        specialCodeStrList.add(name)
                        if (viewModel.guoneiOutWaybill.spCode == code) {
                            postion = index
                        }
                    }
                    /*if (viewModel.guoneiOutWaybill.spCode == Constant.Other.DGR) {
                        dgrDetailNotNull.visibility = View.VISIBLE
                    } else {
                        dgrDetailNotNull.visibility = View.GONE
                    }*/

                    initSpinner(spCode, viewModel.specialCodeList, postion,null)

                }

                viewModel.danger(System.currentTimeMillis().toString())
                viewModel.dangerObserver.observe(this) { vd ->
                    viewModel.dgrList.addAll(vd.getJSONArray("data"))
                    var postion = 0
                    for ((index, obj) in viewModel.dgrList.withIndex()) {
                        val tempObj = obj as JSONObject
                        var code = tempObj.getString("code")
                        var name = tempObj.getString("name")
                        if (viewModel.guoneiOutWaybill.dgr == code) {
                            postion = index
                        }
                    }
                    initSpinner(dgr, viewModel.dgrList, postion,null)
                }

                viewModel.danger(System.currentTimeMillis().toString())
                viewModel.dangerObserver.observe(this) { vd ->
                    viewModel.dgrDetailList.addAll(vd.getJSONArray("data"))
                    var postion = 0
//                    val dgrDetailStrList = arrayListOf<String>()
                    for ((index, obj) in viewModel.dgrDetailList.withIndex()) {
                        val tempObj = obj as JSONObject
                        var code = tempObj.getString("code")
                        var name = tempObj.getString("name")
//                        dgrDetailList.add(tempObj)
//                        dgrDetailStrList.add(name)
                        if (viewModel.guoneiOutWaybill.dgrDetail == code) {
                            postion = index
                        }
                    }
                    initSpinner(dgrDetail, viewModel.dgrDetailList, postion,null)
                }

            } else {
                //无数据
            }
        }


        //监听板车是否异常
        viewModel.queryActiveCarObserver.observe(this) {
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
//                Common.showToastLong(this, "平板车可正常使用 ")
            } else {
                uld.setText("")
                Common.showToastLong(this, "平板车未维护，请重新选择！ ")
            }
        }

        //托盘编号，查询集装器自重
        viewModel.queryFlatcarGjcReceiveObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getJSONObject("data")
            Log.i("queryFlatcarGjcReceiveObserver",it.toString())
            if (Constant.Result.succ == status && data != null) {
                val dataObj = it.getJSONObject("data")
                val dataStatus = dataObj.getString("status")
               // if (dataStatus == "0")

                    val carWeight = dataObj.getString("carWeight") ?: ""
                    uldWeight.setText(carWeight)
                    //板车上已装货物的重量
                    viewModel.netWeight=dataObj.getFloat("signWeight")?:0f
                    viewModel.carFno=dataObj.getString("remark")?:""
                    viewModel.carpc=dataObj.getIntValue("maxWeight")?:0
                    viewModel.carVolume=dataObj.getString("status").toString().toFloat()?:0f

                    if (uld.text.toString() != "") {
                        check.isEnabled = true
                        check.background = ContextCompat.getDrawable(this, R.drawable.submit_shape)
                      /*  val carWeightDb = carWeight.toDouble()
                        val weightDb = weight.text.toString().toDouble()
                       if (mt3percent(carWeightDb - weightDb, carWeightDb)) {
                            check.isEnabled = true
                            check.background = ContextCompat.getDrawable(this, R.drawable.submit_shape)
                        } else {
                            check.isEnabled = false
                            check.background = ContextCompat.getDrawable(this, R.drawable.input_edit_text_disable)
                        }*/
                    }
                    else{
                        check.isEnabled = false
                        check.background = ContextCompat.getDrawable(this, R.drawable.input_edit_text_disable)
                    }

            }
        }

        //托盘编号，校验平板车重量
        viewModel.updateFlatcarGncStartReceiveObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            if (Constant.Result.succ == status && Constant.Result.succ == data) {
                uldWeight.setText(dibangWeight.text.toString())
            } else {
                Common.alertDialog(this, "校验失败！") { dialog ->
                    dialog.dismiss()
                }
            }
        }

        //监听分斗
        viewModel.dividedObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status && Constant.Result.succ == data) {
             //   fendouSuccDataDeal()
                Common.showToastLong(this, "分斗成功！ ")
                fill0AndQueryActiveCar(uld.text.toString())
            } else {
                if (msg != null && msg != "") {
                    Common.alertDialog(this, msg) { dialog ->
                        dialog.dismiss()
                    }
                } else {
                    Common.alertDialog(this, "分斗失败！") { dialog ->
                        dialog.dismiss()
                    }
                }
            }
        }

        //监听完成收运
        viewModel.completedObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status && Constant.Result.succ == data) {
                wbNo.setText("")
                Common.alertDialog(this, "完成收运！") { dialog ->
                  //  reset()
                    fill0AndQueryActiveCar(uld.text.toString())
                    dialog.dismiss()
                }
            } else {
                if (msg != null && msg != "") {
                    Common.alertDialog(this, msg) { dialog ->
                        dialog.dismiss()
                    }
                } else {
                    Common.alertDialog(this, "收运失败！") { dialog ->
                        dialog.dismiss()
                    }
                }
            }
        }

        //设置点击事件
        checkintongdao.onItemSelectedListener= object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if(position>=0){
                    if (parent != null) {
                      //  Toast(this,"选中游戏:${parent.getItemAtPosition(position).toString()}")
                        viewModel.setWeightName(parent.getItemAtPosition(position).toString()) // weightName tongdaoName=
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

        }
        viewModel.weightThread.start()
    }

    override fun onDestroy() {
        viewModel. weightThread.interrupt();
        super.onDestroy()
    }
/////////onCreate 结束

    private fun initView() {
        checkintongdao=findViewById(R.id.checkin_tong_dao)
        check = findViewById(R.id.check)
        fenDou = findViewById(R.id.fen_dou)
        finishCollect = findViewById(R.id.finish_collect)
//        reset=findViewById(R.id.reset_collect)
        labelPrint=findViewById(R.id.label_print)
        wbNo = findViewById(R.id.wbNo)
        wbNoScan = findViewById(R.id.wbNo_scan)
        uldScan = findViewById(R.id.uldScan)
        uld = findViewById(R.id.uld)
//        uldScan = findViewById(R.id.uldScan)
        uldWeight = findViewById(R.id.uldWeight)
        carrier = findViewById(R.id.carrier)
        fno = findViewById(R.id.fno)
        fdate = findViewById(R.id.fdate)
        flight1 = findViewById(R.id.flight1)
        flight2 = findViewById(R.id.flight2)
        flight3 = findViewById(R.id.flight3)
        dgrDetail = findViewById(R.id.dgrDetail)
        dgr = findViewById(R.id.dgr)
//        dgrDetailNotNull = findViewById(R.id.dgrDetailNotNull)
        agentCode = findViewById(R.id.agentCode)
        spCode = findViewById(R.id.spCode)
        goods = findViewById(R.id.goods)
        pc = findViewById(R.id.pc)
        weight = findViewById(R.id.weight)
        volume = findViewById(R.id.volume)
        remark = findViewById(R.id.remark)
        dibangWeight = findViewById(R.id.dibang_weight)
//        dibangWeightScan = findViewById(R.id.dibang_weight_scan)
        volumeInfo = findViewById(R.id.volume_info)
//        uldStr = findViewById(R.id.uldStr)
        uldSelfWeight = findViewById(R.id.uldSelfWeight)


        ////////////////  绑定点击事件
        check.setOnClickListener(this)
        fenDou.setOnClickListener(this)
        finishCollect.setOnClickListener(this)
//        reset.setOnClickListener(this)
        labelPrint.setOnClickListener(this)
        wbNoScan.setOnClickListener(this)
        uldScan.setOnClickListener(this)
//        uldScan.setOnClickListener(this)
//        dibangWeightScan.setOnClickListener(this)

//        wbNo.setOnClickListener(this)
//        uld.setOnClickListener(this)
//        carrier.setOnClickListener(this)
//        fno.setOnClickListener(this)
        fdate.setOnClickListener(this)
//        flight.setOnClickListener(this)
//        dgrDetail.setOnClickListener(this)
//        agentCode.setOnClickListener(this)
//        spCode.setOnClickListener(this)
//        goods.setOnClickListener(this)
//        pc.setOnClickListener(this)
//        weight.setOnClickListener(this)
//        volume.setOnClickListener(this)
//        remark.setOnClickListener(this)
//        dibangWeight.setOnClickListener(this)
//        volumeInfo.setOnClickListener(this)


        /////////////    监听edittext变化
        dibangWeight.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                if (s.toString() != "") {
                    /*var volumeDouble = Arith.div(weight.text.toString().toDouble(), 220.0, 1)
                    if (volumeDouble < 0.1) {
                        volume.setText("0.1")
                    } else {
                        volume.setText(volumeDouble.toString())
                    }*/

                    val carWeightDb = uldWeight.text.toString().toDouble()
                    val diBangWeightDb = s.toString().toDouble()
                    var checkInWeight=diBangWeightDb-viewModel.netWeight-carWeightDb
                    weight.setText( checkInWeight.toString())
                   if (uld.text.toString() != "") {
                        check.isEnabled = true
                        check.background = ContextCompat.getDrawable(MyApplication.context, R.drawable.submit_shape)
                    } else {
                        check.isEnabled = false
                        check.background = ContextCompat.getDrawable(MyApplication.context, R.drawable.input_edit_text_disable)
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        //点击确认
        uld.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
//                uld.setText(fill0AndQueryActiveCar(uld.text.toString()))
            }
            false
        }
        //失去焦点
        uld.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {

            } else {
                //失去焦点
                uld.setText(fill0AndQueryActiveCar(uld.text.toString()))
            }
        }

    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.check -> {
                    Common.secondConfirmDialog(this, "是否校验平板车重量？") { dialog ->
                        viewModel.updateFlatcarGncStartReceive(uld.text.toString(), dibangWeight.text.toString().toDouble())
                        dialog.dismiss()
                        loading()
                    }
                }
                R.id.fen_dou -> {
                    if (getAllEditData()) {
                        Common.secondConfirmDialog(this, "确认分斗") { dialog ->
                            viewModel.divided(viewModel.guoneiOutWaybill)
                            dialog.dismiss()
                            loading()
                        }
                    }
                    else{

                    }
                }
                R.id.finish_collect -> {
                    if (getAllEditData()) {
                        Common.secondConfirmDialog(this, "确认收运") { dialog ->
                            viewModel.completed(viewModel.guoneiOutWaybill)
                            dialog.dismiss()
                            loading()
                        }
                    }
                    else{

                    }
                }
                R.id.label_print -> {
                    /*var date=Date()
                    var format=SimpleDateFormat("yyyy年MM月dd日")
                    var numberUtil=NumberUtil()
                    var label=  LabelBean (
                        titleName = "扬州泰州机场",
                        dest = flight2.text.toString(),
                        carId = uld.text.toString(),
                        fno = fno.text.toString(),
                        pc = viewModel.carpc.toString(),
                        weight =viewModel.netWeight.toString(),
                        volume = viewModel.carVolume.toString(),
                        location = "",
                        opdate =  fdate.text.toString()
                    )

                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_Printer_ACTIVITY).withObject("label",label)
                        .navigation(this)*/
                }
                /*R.id.reset_collect -> {
                    reset()
                }*/
                R.id.wbNo_scan -> {
                    scanCode(Constant.RequestCode.gnc_shouyun_waybill)
                }
                R.id.uldScan -> {
                    scanCode(Constant.RequestCode.gnc_shouyun_uld)
                }
                R.id.dibang_weight_scan -> {
                    dibangWeight.setText("")
                }
                R.id.fdate -> {
                    onYearMonthDayTime()
                }
                /*R.id.agentCode -> {
                    Common.singleSelect(this, "代理", viewModel.agentCodeList, viewModel.guoneiOutWaybill.agentCode) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        agentCode.text = name
                        viewModel.guoneiOutWaybill.agentCode = code
                    }
                }*/
                /*R.id.spCode -> {
                    Common.singleSelect(this, "特码", viewModel.specialCodeList, viewModel.guoneiOutWaybill.spCode) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        spCode.text = name
                        viewModel.guoneiOutWaybill.spCode = code
                        *//*if (code == Constant.Other.DGR) {
                            dgrDetailNotNull.visibility = View.VISIBLE
                        } else {
                            dgrDetailNotNull.visibility = View.GONE
                        }*//*
                    }
                }*/
                /*R.id.dgrDetail -> {
                    Common.singleSelect(this, "危险品库", viewModel.dgrDetailList, viewModel.guoneiOutWaybill.dgrDetail) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        dgrDetail.text = name
                        viewModel.guoneiOutWaybill.dgrDetail = code
                    }
                }*/
                else -> {
                    Toast.makeText(this, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }

    }

    /**
     * 扫码返回的结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 扫描二维码/条码回传
        if (resultCode == RESULT_OK && data != null) {
            val content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
            if (content == null) {
                Common.showToast(this, "条码错误！")
                return
            }
            when (requestCode) {
                Constant.RequestCode.gnc_shouyun_waybill -> {
                    wbNo.setText("$content")
                    viewModel.queryWaybillById(-9999, content)
                }
                Constant.RequestCode.gnc_shouyun_uld -> {
                    uld.setText(fill0AndQueryActiveCar(content))
                }
                Constant.RequestCode.gnc_shouyun_dibang_weight -> {

                }
            }
        }
    }

    /**
     * 时间 年月日
     */
    private fun onYearMonthDayTime() {
        val picker = DatePicker(this)
        val wheelLayout = picker.wheelLayout
        //监听
        picker.setOnDatePickedListener { year, month, day ->
            fdate.text = "$year-$month-$day"
        }
        //支持年月日、时分秒
        wheelLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
        //选择范围
        val selDate = DateEntity.target(1999, 1, 1)
        wheelLayout.setRange(selDate, DateEntity.yearOnFuture(50))
        //年月日时分秒
        wheelLayout.setDateLabel("年", "月", "日")
        //内间距，向右远离60
        wheelLayout.setPadding(0, 0, 60, 0)
        //设置打开组件的时间
        if (fdate.text.toString() != "") {
            var fdate = simpleDateFormat.parse(fdate.text.toString())
            var calendar = Calendar.getInstance()
            calendar.time = fdate
            val datimeEntity = DateEntity.target(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH))
            wheelLayout.setDefaultValue(datimeEntity)
        } else {
            wheelLayout.setDefaultValue(DateEntity.today())
        }

        //展示
        picker.show()
    }


    private fun initSpinner(sp: Spinner, dataListArr: JSONArray, selPosition: Int?, hint: String?) {
        val jsonObjectList: List<JSONObject> = (0 until dataListArr.size).map { dataListArr.getJSONObject(it) }
        val dataList: List<KeyValue> = jsonObjectList.map { KeyValue(it.getString("name"),it.getString("code")) }

        bindAdapter(sp, dataList, hint, null)
        selPosition?.let { sp.setSelection(it) }
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        sp.onItemSelectedListener = MySelectedListener(sp.id, hint)
    }

    /**
     * 下拉框监听
     */
    inner class MySelectedListener(private val spinnerView: Int, val hint: String?) : OnItemSelectedListener {
        override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
            when (spinnerView) {
                R.id.agentCode -> {
                    viewModel.guoneiOutWaybill.agentCode = if (StringUtils.isNotEmpty(hint) && i == viewModel.agentCodeList.size) {
                        ""
                    } else {
                        viewModel.agentCodeList.getJSONObject(i).getString("code")
                    }
                }
                R.id.spCode -> {
                    viewModel.guoneiOutWaybill.spCode = if (StringUtils.isNotEmpty(hint) && i == viewModel.specialCodeList.size) {
                        ""
                    } else {
                        viewModel.specialCodeList.getJSONObject(i).getString("code")
                    }
                }
                R.id.dgrDetail -> {
                    viewModel.guoneiOutWaybill.dgrDetail = if (StringUtils.isNotEmpty(hint) && i == viewModel.dgrDetailList.size) {
                        ""
                    } else {
                        viewModel.dgrDetailList.getJSONObject(i).getString("code")
                    }
                }
                R.id.dgr -> {
                    viewModel.guoneiOutWaybill.dgr = if (StringUtils.isNotEmpty(hint) && i == viewModel.dgrList.size) {
                        ""
                    } else {
                        viewModel.dgrList.getJSONObject(i).getString("code")
                    }
                }
            }
        }

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


    /**
     * 分斗后数据处理
     */
    private fun fendouSuccDataDeal() {
        uld.setText("")
        dibangWeight.setText("")
        pc.setText("")
        volume.setText("")
        volumeInfo.setText("")
    }

    /**
     * 同步viewModel的实体类数据
     */
    private fun getAllEditData(): Boolean {
        if (wbNo.text.toString() == "") {
            Common.showToast(this, "请填写运单号！")
            return false
        }
        if (uld.text.toString() == "") {
            Common.showToast(this, "请填写板车号！")
            return false
        }
        if (carrier.text.toString() == "") {
            Common.showToast(this, "承运人不能为空！")
            return false
        }
        if (viewModel.guoneiOutWaybill.agentCode == "") {
            Common.showToast(this, "代理人不能为空！")
            return false
        }
        if (pc.text.toString() == "") {
            Common.showToast(this, "请填写件数！")
            return false
        }
        if (flight1.text.toString() == "" || (flight2.text.toString() == "" && flight3.text.toString() == "")) {
            Common.showToast(this, "航程不能为空！")
            return false
        }
        if (viewModel.guoneiOutWaybill.spCode == "") {
            Common.showToast(this, "特码不能为空！")
            return false
        }
        if (weight.text.toString() == "") {
            Common.showToast(this, "请填写重量！")
            return false
        }
        if (volume.text.toString() == "") {
            Common.showToast(this, "请填写体积！")
            return false
        }
        /*if (viewModel.guoneiOutWaybill.volDetail == "") {
            Common.showToast(this, "请填写体积明细！")
            return false
        }*/
        if (fdate.text.toString() == "") {
            Common.showToast(this, "航班日期不能为空！")
            return false
        }
        if (goods.text.toString() == "") {
            Common.showToast(this, "品名不能为空！")
            return false
        }
        if (fno.text.toString() == "") {
            Common.showToast(this, "计划航班不能为空！")
            return false
        }
        /*if (viewModel.guoneiOutWaybill.spCode == Constant.Other.DGR && viewModel.guoneiOutWaybill.dgrDetail == "") {
            Common.showToast(this, "危险品不能为空！")
            return false
        }*/

        viewModel.guoneiOutWaybill.wbNo = wbNo.text.toString()
        viewModel.guoneiOutWaybill.uld = uld.text.toString()

        viewModel.guoneiOutWaybill.carrier = carrier.text.toString()
        viewModel.guoneiOutWaybill.pc = pc.text.toString().toInt()

        viewModel.guoneiOutWaybill.fno = fno.text.toString()
        viewModel.guoneiOutWaybill.weight = weight.text.toString().toDouble()

        viewModel.guoneiOutWaybill.fdate = fdate.text.toString()
        viewModel.guoneiOutWaybill.goods = goods.text.toString()
        viewModel.guoneiOutWaybill.volume = volume.text.toString().toDouble()

        viewModel.guoneiOutWaybill.range = "${flight1.text}-${flight2.text}-${flight3.text}"

        viewModel.guoneiOutWaybill.volDetail = volumeInfo.text.toString()
        viewModel.guoneiOutWaybill.remark = remark.text.toString()


        return true
    }

    override fun setBackArrow(title: String) {
        setResult(RESULT_OK)
        super.setBackArrow(title)
    }

    /**
     *  不足3位补0 并且判断车是否可用
     */
    private fun fill0AndQueryActiveCar(content: String): String {
        //不足3位补0
        var add0Str = ""
        if (content.length < 3) {
            val add0length = 3 - content.length
            for (index in 1..add0length) {
                add0Str += "0"
            }
        }
        add0Str += content
        viewModel.queryActiveCar(add0Str)
        viewModel.queryFlatcarGjcReceive(add0Str)
        return add0Str
    }

    /**
     * 重置数据
     */
    private fun reset() {
        wbNo.setText("")
        uld.setText("")
        dibangWeight.setText("")

        carrier.setText("")
        agentCode.setSelection(0)
        viewModel.guoneiOutWaybill.agentCode = ""
        pc.setText("")

        fno.setText("")
        spCode.setSelection(0)
        viewModel.guoneiOutWaybill.spCode = ""

        fdate.text = ""
        goods.setText("")
        volume.setText("")

        flight1.setText("")
        flight2.setText("")
        flight3.setText("")
        volumeInfo.setText("")

        dgrDetail.setSelection(0)
        dgr.setSelection(0)
        viewModel.guoneiOutWaybill.dgrDetail = ""
        viewModel.guoneiOutWaybill.dgr = ""
        remark.setText("")
    }

    /**
     * 是否超过百分之三
     */
    private fun mt3percent(num1: Double, num2: Double): Boolean {
        if (num2 == 0.0) {
            return false
        }
        val tempNum = abs(num1)
        val div = Arith.div(tempNum, num2, 3) * 100
        return div > 3
    }

    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {

    }

    override fun onNothingSelected(parent: AdapterView<*>?) {
        //TODO("Not yet implemented")
    }
}





