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.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.GjcFuBang
import com.lukouguoji.gjc.viewModel.GjcFuBangViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.ktx.noNull
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.util.Common
import java.text.SimpleDateFormat
import java.util.*

@Deprecated("旧版板箱过磅，使用 GjcBoxWeighingActivity 替代")
@Route(path = ARouterConstants.ACTIVITY_URL_GJC_FU_BANG)
class GjcFuBangActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GjcFuBangViewModel

    private lateinit var carId: EditText
    private lateinit var carIdScan: ImageView
    private lateinit var uld: EditText
    private lateinit var uldScan: ImageView
    private lateinit var dibangWeight: EditText
    private lateinit var dibangWeightScan: ImageView

    //第一行
    private lateinit var carWeight: EditText
    private lateinit var uldWeight: EditText
    private lateinit var netWeight: EditText

    //第二行
    private lateinit var dgrCode: EditText
    private lateinit var boardType: EditText
    private lateinit var cargoWeight: EditText

    //第三行
    private lateinit var plClose: Button
    private lateinit var plCloseSize: EditText
    private lateinit var plCloseSizeMust: TextView
    private lateinit var totalWeight: EditText

    //第四行
    private lateinit var height: EditText
    private lateinit var fdate: Button
    private lateinit var fno: EditText

    //第5行
    private lateinit var fdest: EditText
    private lateinit var cargoType: Button

    private lateinit var remark: EditText

    private lateinit var submit: TextView

    private val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
    private val calendar = Calendar.getInstance()

    @JvmField
    @Autowired
    var carNoParam: String? = null

    @JvmField
    @Autowired
    var userIdParam: String? = null

    private fun initView() {
        carId = findViewById(R.id.carId)
        carIdScan = findViewById(R.id.carIdScan)
        uld = findViewById(R.id.uld)
        uldScan = findViewById(R.id.uldScan)
        dibangWeight = findViewById(R.id.dibangWeight)
        dibangWeightScan = findViewById(R.id.dibangWeightScan)

        //第一行
        carWeight = findViewById(R.id.carWeight)
        uldWeight = findViewById(R.id.uldWeight)
        netWeight = findViewById(R.id.netWeight)

        //第二行
        dgrCode = findViewById(R.id.dgrCode)
        boardType = findViewById(R.id.boardType)
        cargoWeight = findViewById(R.id.cargoWeight)

        //第三行
        plClose = findViewById(R.id.plClose)
        plCloseSizeMust = findViewById(R.id.plCloseSizeMust)
        plCloseSize = findViewById(R.id.plCloseSize)
        totalWeight = findViewById(R.id.totalWeight)

        //第四行
        height = findViewById(R.id.height)
        fdate = findViewById(R.id.fdate)
        fno = findViewById(R.id.fno)

        //第五行
        fdest = findViewById(R.id.fdest)
        cargoType = findViewById(R.id.cargoType)

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

        carIdScan.setOnClickListener(this)
        uldScan.setOnClickListener(this)
        dibangWeightScan.setOnClickListener(this)
        plClose.setOnClickListener(this)
        fdate.setOnClickListener(this)
        cargoType.setOnClickListener(this)
        submit.setOnClickListener(this)

        fdate.text = ymdSdf.format(calendar.time)

        /////////////    监听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 != null && s.toString().trim() != "") {
                    val tempWeight = s.toString().toDouble()
                    //架子车自重
                    var carWeightDouble = 0.0
                    if (carWeight.text.toString().trim() != "") {
                        carWeightDouble = carWeight.text.toString().trim().toDouble()
                    }
                    //集装器自重
                    var uldWeightDouble = 0.0
                    if (uldWeight.text.toString().trim() != "") {
                        uldWeightDouble = uldWeight.text.toString().trim().toDouble()
                    }

                    //赋值
                    //装机重
                    netWeight.setText("${tempWeight - carWeightDouble}")
                    //货重
                    cargoWeight.setText("${tempWeight - carWeightDouble - uldWeightDouble}")
                    //总重
                    totalWeight.setText("$tempWeight")

                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        carWeight.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().toDouble()
                    //地磅
                    var dibangWeightDouble = 0.0
                    if (dibangWeight.text.toString().trim() != "") {
                        dibangWeightDouble = dibangWeight.text.toString().trim().toDouble()
                    }
                    //集装器自重
                    var uldWeightDouble = 0.0
                    if (uldWeight.text.toString().trim() != "") {
                        uldWeightDouble = uldWeight.text.toString().trim().toDouble()
                    }

                    //赋值
                    //装机重
                    netWeight.setText("${dibangWeightDouble - tempWeight}")
                    //货重
                    cargoWeight.setText("${dibangWeightDouble - tempWeight - uldWeightDouble}")

                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        uldWeight.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().toDouble()
                    //地磅
                    var dibangWeightDouble = 0.0
                    if (dibangWeight.text.toString().trim() != "") {
                        dibangWeightDouble = dibangWeight.text.toString().trim().toDouble()
                    }
                    //架子车自重
                    var carWeightDouble = 0.0
                    if (carWeight.text.toString().trim() != "") {
                        carWeightDouble = carWeight.text.toString().trim().toDouble()
                    }

                    //赋值
                    //货重
                    cargoWeight.setText("${dibangWeightDouble - carWeightDouble - tempWeight}")

                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        //失去焦点
        carId.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {

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

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

            } else {
                if (fdate.text.toString() != "" && fno.text.toString() != "") {
                    viewModel.queryFlight(fdate.text.toString(), fno.text.toString())
                }
            }
        }
        fno.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) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val originText = editable.toString()
                if (originText != null && originText != "") {
                    val regularExpression = "(^([A-Z0-9]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if (!matches) {
                        val regularExpression2 = "([^A-Za-z0-9]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(), "")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        fno.setText(replaceStrToUpper)
                        fno.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })

        //赋值
        viewModel.fuBangInfo.cargoType = "0"//货物类型初始化 默认 0-> 计重货
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gjc_fu_bang)
        setBackArrow("国际出港板箱过磅")
        viewModel = ViewModelProvider(this).get(GjcFuBangViewModel::class.java)
        initView()


        //监听完成过磅
        viewModel.completedObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            if (Constant.Result.succ == status) {
                if (data == "1") {
                    carId.setText("")
                    Common.alertDialog(this, "完成过磅！") { dialog ->
                        resetData()
                        dialog.dismiss()
                    }
                } else if (data == "3") {
                    Common.alertDialog(this, "航班不存在！") { dialog ->
                        dialog.dismiss()
                    }

                } else if (data == "4") {
                    Common.alertDialog(this, "航班已关闭！") { dialog ->
                        dialog.dismiss()
                    }

                } else if (data == "5") {
                    Common.alertDialog(this, "航班已截载！") { dialog ->
                        dialog.dismiss()
                    }

                } else {
                    Common.alertDialog(this, "过磅失败！") { dialog ->
                        dialog.dismiss()
                    }
                }
            } else {
//                Common.showToastLong(this, "收运失败！ ")
                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) {
                val uldWeightTemp = data.getIntValue("uldWeight")
                uldWeight.setText("$uldWeightTemp")
            }
        }

        //托盘编号，查询集装器自重
        viewModel.queryFlatcarGjcReceiveObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getJSONObject("data")
            if (Constant.Result.succ == status && data != null) {
                val carWeightTemp = data.getIntValue("carWeight")
                carWeight.setText("$carWeightTemp")
            }
        }

        //航班返回结果
        viewModel.queryFlightObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                var jsonObject = it.getJSONObject("data")
                val countryName = jsonObject.getString("countryName")
                val countryType = jsonObject.getString("countryType")
                val dep = jsonObject.getString("fdep")
                val dest = jsonObject.getString("fdest")

                fdest.setText(dest)
            } else {
                fdest.setText("")
            }
        }

        //下拉框赋值
        val plClose = JSONObject()
        plClose["code"] = ""
        plClose["name"] = "请选择"
        val plClose1 = JSONObject()
        plClose1["code"] = "探板"
        plClose1["name"] = "探板"
        val plClose2 = JSONObject()
        plClose2["code"] = "收口"
        plClose2["name"] = "收口"
        viewModel.plCloseList.add(plClose)
        viewModel.plCloseList.add(plClose1)
        viewModel.plCloseList.add(plClose2)

        viewModel.cargoSelect(System.currentTimeMillis().toString())
        viewModel.cargoObserver.observe(this) { vd ->
            viewModel.cargoList = vd.getJSONArray("data")
            for ((index, obj) in viewModel.cargoList.withIndex()) {
                val tempObj = obj as JSONObject
                val name = tempObj.getString("name")
                val code = tempObj.getString("code")
                if (viewModel.fuBangInfo.cargoType == code) {
                    cargoType.text = name
                }
            }
        }

        viewModel.boxDetails.observe(this) {
            it.gjcLoading?.firstOrNull()?.let { bean ->
                uld.setText(bean.uld.noNull())
                carWeight.setText(it.carweight.noNull())
                uldWeight.setText(bean.uldweight.noNull())

                fdate.text = bean.fdate.noNull()
                fno.setText(bean.fno.noNull())
                fdest.setText(bean.dest.noNull())

                bean.cargotype?.let { cargoType ->
                    viewModel.cargoList.forEach { cargo ->
                        val cargoObj = cargo as JSONObject
                        if (cargoObj.getString("code") == cargoType) {
                            this.cargoType.text = cargoObj.getString("name")
                            viewModel.fuBangInfo.cargoType = cargoObj.getString("code")
                        }
                    }
                }
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.carIdScan -> {
                    scanCode(Constant.RequestCode.gjc_fubang_car_id)
                }

                R.id.uldScan -> {
                    scanCode(Constant.RequestCode.gjc_fubang_uld_id)
                }

                R.id.dibangWeightScan -> {
                    dibangWeight.setText("")
                }

                R.id.plClose -> {
                    Common.singleSelect(
                        this,
                        "探板收口",
                        viewModel.plCloseList,
                        viewModel.fuBangInfo.plClose
                    ) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        plClose.text = name
                        viewModel.fuBangInfo.plClose = code

                        if (code != "") {
                            plCloseSizeMust.visibility = View.VISIBLE
                            plCloseSize.isEnabled = true
                        } else {
                            plCloseSizeMust.visibility = View.GONE
                            plCloseSize.isEnabled = false
                        }

                    }
                }

                R.id.cargoType -> {
                    Common.singleSelect(
                        this,
                        "货物类型",
                        viewModel.cargoList,
                        viewModel.fuBangInfo.cargoType
                    ) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        cargoType.text = name
                        viewModel.fuBangInfo.cargoType = code
                    }
                }

                R.id.fdate -> {
                    Common.onYearMonthDay(this, fdate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        val selDate = ymdSdf.format(calendar.time)
                        fdate.text = selDate
                        if (selDate != "" && fno.text.toString() != "") {
                            viewModel.queryFlight(selDate, fno.text.toString())
                        }
                    }
                }

                R.id.submit -> {
                    if (getAllEditData()) {
                        Common.secondConfirmDialog(this, "确认过磅") { dialog ->
//                            viewModel.completed(viewModel.fuBangInfo)
                            viewModel.onConfirmClick(this, viewModel.fuBangInfo) {
                                resetData()
                            }
                            dialog.dismiss()
                        }
                    }
                }

                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_fubang_car_id -> {
                    carId.setText(content)
//                    viewModel.queryFlatcarGjcReceive(content)
                    viewModel.getBoxDetailsByCarId(content)
                }

                Constant.RequestCode.gjc_fubang_uld_id -> {
                    uld.setText(content)
                    viewModel.queryUldGjcReceive(content)
                }
            }
        }
    }

    /**
     * 同步viewModel的实体类数据
     */
    private fun getAllEditData(): Boolean {
        if (carId.text.toString() == "") {
            Common.showToast(this, "请填写平板车号！")
            return false
        }
        if (uld.text.toString() == "") {
            //默认值 BULK
            Common.secondConfirmDialog(this, "集装器编号未填写，是否填入默认值！") { dialog ->
                uld.setText("BULK")
                dialog.dismiss()
            }
            return false
        }
        if (netWeight.text.toString() == "" || netWeight.text.toString().toDouble() == 0.0) {
            Common.showToast(this, "请填写装机重！")
            return false
        }
        if (cargoWeight.text.toString() == "" || cargoWeight.text.toString().toDouble() == 0.0) {
            Common.showToast(this, "请填写货物重量！")
            return false
        }
        if (totalWeight.text.toString() == "" || totalWeight.text.toString().toDouble() == 0.0) {
            Common.showToast(this, "请填写总重量！")
            return false
        }
        if (plClose.text.toString() != "") {
            if (plCloseSize.text.toString() == null || plCloseSize.text.toString() == "") {
                Common.showToast(this, "探板收口大小不能为空！")
                return false
            }
        }
//        if (fdate.text.toString() == "") {
//            Common.showToast(this, "航班日期不能为空！")
//            return false
//        }
//        if (fno.text.toString() == "") {
//            Common.showToast(this, "航班号不能为空！")
//            return false
//        }
        if (fdest.text.toString() == "") {
            Common.showToast(this, "请填写目的港！")
            return false
        }
        if (cargoType.text.toString() == "") {
            Common.showToast(this, "请填写货物类型！")
            return false
        }
        if (height.text.toString() == "") {
            height.setText("0.0")
        }

        viewModel.fuBangInfo.carId = carId.text.toString()
        viewModel.fuBangInfo.uld = uld.text.toString()

        viewModel.fuBangInfo.carWeight = carWeight.text.toString().toDouble()
        viewModel.fuBangInfo.uldWeight = uldWeight.text.toString().toDouble()
        viewModel.fuBangInfo.netWeight = netWeight.text.toString().toDouble()

        viewModel.fuBangInfo.dgrCode = dgrCode.text.toString()
        viewModel.fuBangInfo.boardType = boardType.text.toString()
        viewModel.fuBangInfo.cargoWeight = cargoWeight.text.toString().toDouble()

        viewModel.fuBangInfo.plClose = plClose.text.toString()
        viewModel.fuBangInfo.plCloseSize = plCloseSize.text.toString()
        viewModel.fuBangInfo.totalWeight = totalWeight.text.toString().toDouble()

        viewModel.fuBangInfo.height = height.text.toString().toDouble()
        viewModel.fuBangInfo.fdate = fdate.text.toString()
        viewModel.fuBangInfo.fno = fno.text.toString()

        viewModel.fuBangInfo.fdest = fdest.text.toString()

        viewModel.fuBangInfo.remark = remark.text.toString()

        return true
    }

    /**
     * 清空数据
     */
    private fun resetData() {
        carId.setText("")
        uld.setText("")
        dibangWeight.setText("")

        carWeight.setText("")
        uldWeight.setText("")
        netWeight.setText("")

        dgrCode.setText("")
        boardType.setText("")
        cargoWeight.setText("")

        plClose.text = ""
        plCloseSize.setText("")
        totalWeight.setText("")

        height.setText("")
        calendar.time = Date()
        fdate.text = ymdSdf.format(calendar.time)
        fno.setText("")

        fdest.setText("")
        cargoType.text = ""

        remark.setText("")

        viewModel.fuBangInfo = GjcFuBang()
    }
}