package com.lukouguoji.gjc.activity

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.*
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.JSONObject
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.model.GjcStartReceiveWaybill
import com.lukouguoji.gjc.viewModel.GjcStartReceiveViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.MyApplication
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 java.text.SimpleDateFormat
import kotlin.math.abs

@Route(path = ARouterConstants.ACTIVITY_URL_GJC_START_RECEIVE)
class GjcStartReceiveActivity : BaseActivity(), View.OnClickListener {
    private lateinit var finishCollect: TextView
    private lateinit var viewModel: GjcStartReceiveViewModel

    private lateinit var wbNo: EditText
    private lateinit var wbNoScan: ImageView
    private lateinit var diBangWeight: EditText


    private lateinit var tuoPanCode: EditText
    private lateinit var tuoPanScan: ImageView
    private lateinit var tuoPanWeight: EditText

    private lateinit var spCode: Button
    private lateinit var jiZhuangCode: EditText
    private lateinit var jiZhuangScan: ImageView
    private lateinit var jiZhuangWeight: EditText

    private lateinit var pc: EditText
    private lateinit var weight: EditText
    private lateinit var volume: EditText

    private lateinit var arrivePc: EditText
    private lateinit var arriveWeight: EditText
    private lateinit var arriveVolume: EditText

    private lateinit var tuoPanWeightCheck: TextView
    private lateinit var jiZhuangCheck: TextView

    private lateinit var businessType: Button
    private lateinit var remark: EditText

    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_gjc_start_receive)
        setBackArrow("国际出港开始收运")
        initView()
        viewModel = ViewModelProvider(this).get(GjcStartReceiveViewModel::class.java)
        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.receiveWaybill.maWbId = jsonObject.getIntValue("maWbId")
                viewModel.receiveWaybill.prefix = jsonObject.getString("prefix") ?: ""
                viewModel.receiveWaybill.no = jsonObject.getString("no") ?: ""
                viewModel.receiveWaybill.wbNo = jsonObject.getString("wbNo") ?: ""
                viewModel.receiveWaybill.agentCode = jsonObject.getString("agentCode") ?: ""
                viewModel.receiveWaybill.goods = jsonObject.getString("goods") ?: ""
                viewModel.receiveWaybill.spCode = jsonObject.getString("spCode") ?: ""
                viewModel.receiveWaybill.businessType = jsonObject.getString("businessType") ?: ""
                viewModel.receiveWaybill.pc = jsonObject.getIntValue("pc")
                viewModel.receiveWaybill.weight = jsonObject.getDoubleValue("grossWeight")
                viewModel.receiveWaybill.volume = jsonObject.getDoubleValue("volume")
                viewModel.receiveWaybill.arrivePc = jsonObject.getIntValue("arrivePc")
                viewModel.receiveWaybill.arriveWeight = jsonObject.getDoubleValue("arriveWeight")
                viewModel.receiveWaybill.arriveVolume = jsonObject.getDoubleValue("arriveVolume")

                viewModel.receiveWaybill.remark = jsonObject.getString("remark") ?: ""
                viewModel.receiveWaybill.activeId = jsonObject.getIntValue("activeId")
                viewModel.receiveWaybill.awbType = jsonObject.getString("awbType")

                viewModel.receiveWaybill.dep = jsonObject.getString("dep") ?: ""
                viewModel.receiveWaybill.dest = jsonObject.getString("dest") ?: ""
                viewModel.receiveWaybill.dest1 = jsonObject.getString("dest1") ?: ""
                viewModel.receiveWaybill.by1 = jsonObject.getString("by1") ?: ""
                viewModel.receiveWaybill.checkIn = jsonObject.getString("checkIn") ?: ""


                wbNo.setText(viewModel.receiveWaybill.wbNo)

                pc.setText(viewModel.receiveWaybill.pc.toString())
                weight.setText(viewModel.receiveWaybill.weight.toString())
                volume.setText(viewModel.receiveWaybill.volume.toString())


                remark.setText(viewModel.receiveWaybill.remark)


                //下拉框赋值
                viewModel.business(Constant.businessType.IO)
                viewModel.businessObserver.observe(this) { vd ->
                    viewModel.businessList = vd.getJSONArray("data")
                    for ((index, obj) in viewModel.businessList.withIndex()) {
                        val tempObj = obj as JSONObject
                        val name = tempObj.getString("name")
                        val code = tempObj.getString("code")
                        if (viewModel.receiveWaybill.businessType == code) {
                            businessType.text = name
                        }
                    }
                }

                viewModel.specialCode(System.currentTimeMillis().toString())
                viewModel.specialCodeObserver.observe(this) { vd ->
                    viewModel.specialCodeList = vd.getJSONArray("data")
                    for ((index, obj) in viewModel.specialCodeList.withIndex()) {
                        val tempObj = obj as JSONObject
                        var code = tempObj.getString("code")
                        var name = tempObj.getString("name")
                        if (viewModel.receiveWaybill.spCode == code) {
                            spCode.text = name
                        }
                    }
                }


            } else {
                //无数据
            }
        }


        //监听完成收运
        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) {
                if (data == Constant.Result.succ) {
                    reset()
                }
                Common.alertDialog(this, msg) { dialog ->
                    dialog.dismiss()
                }
            } else {
                Common.alertDialog(this, "收运失败！") { dialog ->
                    dialog.dismiss()
                }
            }
        }

        //集装器编号，查询集装器自重
        viewModel.queryUldGjcReceiveObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getJSONObject("data")
            if (Constant.Result.succ == status && data != null) {
                var uldWeight = data.getIntValue("uldWeight")
                jiZhuangWeight.setText("$uldWeight")
                val uldWeightDb = uldWeight.toDouble()
                val diBangWeightDb = diBangWeight.text.toString().toDouble()
                if (mt3percent(uldWeightDb - diBangWeightDb, uldWeightDb)) {
                    jiZhuangCheck.isEnabled = true
                    jiZhuangCheck.background = ContextCompat.getDrawable(this, R.drawable.submit_shape)
                } else {
                    jiZhuangCheck.isEnabled = false
                    jiZhuangCheck.background = ContextCompat.getDrawable(this, R.drawable.input_shape)
                }
            }
        }
        //集装器编号，校验集装器重量
        viewModel.updateUldGjcReceiveObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            if (Constant.Result.succ == status && Constant.Result.succ == data) {
                jiZhuangWeight.setText(diBangWeight.text.toString())
            } else {
                Common.alertDialog(this, "校验失败！") { dialog ->
                    dialog.dismiss()
                }
            }
        }

        //托盘编号，查询集装器自重
        viewModel.queryFlatcarGjcReceiveObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getJSONObject("data")
            if (Constant.Result.succ == status && data != null) {
                var carWeight = data.getIntValue("carWeight")
                tuoPanWeight.setText("$carWeight")
                val carWeightDb = carWeight.toDouble()
                val diBangWeightDb = diBangWeight.text.toString().toDouble()
                if (mt3percent(carWeightDb - diBangWeightDb, carWeightDb)) {
                    tuoPanWeightCheck.isEnabled = true
                    tuoPanWeightCheck.background = ContextCompat.getDrawable(this, R.drawable.submit_shape)
                } else {
                    tuoPanWeightCheck.isEnabled = false
                    tuoPanWeightCheck.background = ContextCompat.getDrawable(this, R.drawable.input_shape)
                }
            }
        }
        //托盘编号，校验平板车重量
        viewModel.updateFlatcarGjcReceiveObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            if (Constant.Result.succ == status && Constant.Result.succ == data) {
                tuoPanWeight.setText(diBangWeight.text.toString())
            } else {
                Common.alertDialog(this, "校验失败！") { dialog ->
                    dialog.dismiss()
                }
            }
        }
    }
/////////onCreate 结束

    private fun initView() {

        finishCollect = findViewById(R.id.finish_collect)

        wbNo = findViewById(R.id.wbNo)
        wbNoScan = findViewById(R.id.wbNo_scan)
        diBangWeight = findViewById(R.id.diBangWeight)

        tuoPanCode = findViewById(R.id.tuoPanCode)
        tuoPanScan = findViewById(R.id.tuoPanScan)
        tuoPanWeight = findViewById(R.id.tuoPanWeight)

        spCode = findViewById(R.id.spCode)
        jiZhuangCode = findViewById(R.id.jiZhuangCode)
        jiZhuangScan = findViewById(R.id.jiZhuangScan)
        jiZhuangWeight = findViewById(R.id.jiZhuangWeight)

        pc = findViewById(R.id.pc)
        weight = findViewById(R.id.weight)
        volume = findViewById(R.id.volume)
        arrivePc = findViewById(R.id.arrivePc)
        arriveWeight = findViewById(R.id.arriveWeight)
        arriveVolume = findViewById(R.id.arriveVolume)

        businessType = findViewById(R.id.businessType)
        remark = findViewById(R.id.remark)

        tuoPanWeightCheck = findViewById(R.id.tuoPanWeightCheck)
        jiZhuangCheck = findViewById(R.id.jiZhuangCheck)


        ////////////////  绑定点击事件
//        fenDou.setOnClickListener(this)
        finishCollect.setOnClickListener(this)
        wbNoScan.setOnClickListener(this)
        tuoPanScan.setOnClickListener(this)
        jiZhuangScan.setOnClickListener(this)
        businessType.setOnClickListener(this)
        spCode.setOnClickListener(this)
        tuoPanWeightCheck.setOnClickListener(this)
        jiZhuangCheck.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) {
                var tempWeight = "0.0"
                if (s != null && s.toString().trim() != "") {
                    tempWeight = s.toString()
                }

                var tuoPanWeightDouble = 0.0
                if (tuoPanWeight.text.toString() != "") {
                    tuoPanWeightDouble = tuoPanWeight.text.toString().toDouble()
                } else {
                    tuoPanWeightDouble = 0.0
                }

                var jiZhuangWeightDouble = 0.0
                if (jiZhuangWeight.text.toString() != "") {
                    jiZhuangWeightDouble = jiZhuangWeight.text.toString().toDouble()
                } else {
                    jiZhuangWeightDouble = 0.0
                }

                val arriveWeightTemp = tempWeight.toDouble() - tuoPanWeightDouble - jiZhuangWeightDouble
                arriveWeight.setText(arriveWeightTemp.toString())
                arriveVolume.setText(Arith.div(arriveWeightTemp, 220.0, 2).toString())

                //校验集装器差值
                if (mt3percent(jiZhuangWeightDouble - tempWeight.toDouble(), jiZhuangWeightDouble)) {
                    jiZhuangCheck.isEnabled = true
                    jiZhuangCheck.background = ContextCompat.getDrawable(MyApplication.context, R.drawable.submit_shape)
                } else {
                    jiZhuangCheck.isEnabled = false
                    jiZhuangCheck.background = ContextCompat.getDrawable(MyApplication.context, R.drawable.input_shape)
                }
                //校验托盘差值
                if (mt3percent(tuoPanWeightDouble - tempWeight.toDouble(), tuoPanWeightDouble)) {
                    tuoPanWeightCheck.isEnabled = true
                    tuoPanWeightCheck.background = ContextCompat.getDrawable(MyApplication.context, R.drawable.submit_shape)
                } else {
                    tuoPanWeightCheck.isEnabled = false
                    tuoPanWeightCheck.background = ContextCompat.getDrawable(MyApplication.context, R.drawable.input_shape)
                }

            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        jiZhuangWeight.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 != null && s.toString().trim() != "") {
                    val tempWeight = s.toString()
                    var diBangWeightDouble = 0.0
                    if (diBangWeight.text.toString() != "") {
                        diBangWeightDouble = diBangWeight.text.toString().toDouble()
                    } else {
                        diBangWeightDouble = 0.0
                    }

                    var tuoPanWeightDouble = 0.0
                    if (tuoPanWeight.text.toString() != "") {
                        tuoPanWeightDouble = tuoPanWeight.text.toString().toDouble()
                    } else {
                        tuoPanWeightDouble = 0.0
                    }

                    val arriveWeightTemp = diBangWeightDouble - tempWeight.toDouble() - tuoPanWeightDouble
                    arriveWeight.setText(arriveWeightTemp.toString())
                    arriveVolume.setText(Arith.div(arriveWeightTemp, 220.0, 2).toString())
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        tuoPanWeight.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 != null && s.toString().trim() != "") {
                    val tempWeight = s.toString()
                    var diBangWeightDouble = 0.0
                    if (diBangWeight.text.toString() != "") {
                        diBangWeightDouble = diBangWeight.text.toString().toDouble()
                    } else {
                        diBangWeightDouble = 0.0
                    }

                    var jiZhuangWeightDouble = 0.0
                    if (jiZhuangWeight.text.toString() != "") {
                        jiZhuangWeightDouble = jiZhuangWeight.text.toString().toDouble()
                    } else {
                        jiZhuangWeightDouble = 0.0
                    }

                    val arriveWeightTemp = diBangWeightDouble - tempWeight.toDouble() - jiZhuangWeightDouble
                    arriveWeight.setText(arriveWeightTemp.toString())
                    arriveVolume.setText(Arith.div(arriveWeightTemp, 220.0, 2).toString())
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

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

            } else {
                //失去焦点
                viewModel.queryFlatcarGjcReceive(tuoPanCode.text.toString())
            }
        }
        jiZhuangCode.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {

            } else {
                //失去焦点
                viewModel.queryUldGjcReceive(jiZhuangCode.text.toString())
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.finish_collect -> {
                    if (getAllEditData()) {
                        Common.secondConfirmDialog(this, "是否确认收运") { dialog ->
                            viewModel.completed(viewModel.receiveWaybill)
                            dialog.dismiss()
                            loading()
                        }
                    }
                }
                R.id.wbNo_scan -> {
                    scanCode(Constant.RequestCode.gjc_shouyun_waybill)
                }
                R.id.tuoPanScan -> {
                    scanCode(Constant.RequestCode.gjc_shouyun_tuopan)
                }
                R.id.jiZhuangScan -> {
                    scanCode(Constant.RequestCode.gjc_shouyun_jizhuang)
                }
                R.id.tuoPanWeightCheck -> {
                    Common.secondConfirmDialog(this, "是否校验此托盘重量？") { dialog ->
                        viewModel.updateFlatcarGjcReceive(tuoPanCode.text.toString(), diBangWeight.text.toString().toDouble())
                        dialog.dismiss()
                        loading()
                    }
                }
                R.id.jiZhuangCheck -> {
                    Common.secondConfirmDialog(this, "是否校验此集装器重量？") { dialog ->
                        viewModel.updateUldGjcReceive(jiZhuangCode.text.toString(), diBangWeight.text.toString().toDouble())
                        dialog.dismiss()
                        loading()
                    }
                }
                R.id.businessType -> {
                    Common.singleSelect(this, "业务类型", viewModel.businessList, viewModel.receiveWaybill.businessType) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        businessType.text = name
                        viewModel.receiveWaybill.businessType = code
                    }
                }
                R.id.spCode -> {
                    Common.singleSelect(this, "特码", viewModel.specialCodeList, viewModel.receiveWaybill.spCode) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        spCode.text = name
                        viewModel.receiveWaybill.spCode = 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.gjc_shouyun_waybill -> {
                    wbNo.setText("$content")
                    viewModel.queryWaybillById(-9999, content)
                }
                Constant.RequestCode.gjc_shouyun_tuopan -> {
                    tuoPanCode.setText("$content")
                    viewModel.queryFlatcarGjcReceive(content)
                }
                Constant.RequestCode.gjc_shouyun_jizhuang -> {
                    jiZhuangCode.setText("$content")
                    viewModel.queryUldGjcReceive(content)
                }
            }
        }
    }

    /**
     * 同步viewModel的实体类数据
     */
    private fun getAllEditData(): Boolean {
        viewModel.receiveWaybill.wbNo = wbNo.text.toString()
        viewModel.receiveWaybill.arrivePc = arrivePc.text.toString().toIntOrNull() ?: 0
        viewModel.receiveWaybill.arriveWeight = arriveWeight.text.toString().toDoubleOrNull() ?: 0.0
        viewModel.receiveWaybill.arriveVolume = arriveVolume.text.toString().toDoubleOrNull() ?: 0.0
        viewModel.receiveWaybill.remark = remark.text.toString()

        if (viewModel.receiveWaybill.wbNo == "") {
            Common.showToast(this, "请填写运单号！")
            return false
        }

        if (viewModel.receiveWaybill.arrivePc < 1) {
            Common.showToast(this, "请填写件数！")
            return false
        }

        if (viewModel.receiveWaybill.spCode == "") {
            Common.showToast(this, "特码不能为空！")
            return false
        }
        if (viewModel.receiveWaybill.arriveWeight == 0.0) {
            Common.showToast(this, "请填写重量！")
            return false
        }
        if (viewModel.receiveWaybill.arriveVolume == 0.0) {
            Common.showToast(this, "请填写体积！")
            return false
        }

        if (viewModel.receiveWaybill.businessType == "") {
            Common.showToast(this, "业务类型不能为空！")
            return false
        }


        return true
    }

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


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

        pc.setText("")
        weight.setText("")
        volume.setText("")
        arrivePc.setText("")
        arriveWeight.setText("")
        arriveVolume.setText("")

        jiZhuangCode.setText("")
        jiZhuangWeight.setText("")
        spCode.text = ""

        businessType.text = ""
        tuoPanCode.setText("")
        tuoPanWeight.setText("")

        remark.setText("")

        //清空
        viewModel.receiveWaybill = GjcStartReceiveWaybill()
    }

    /**
     * 是否超过百分之三
     */
    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
    }
}