package com.lukouguoji.gnc.activity

import android.content.Intent
import android.os.Bundle
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.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.bluetooth.bean.LabelBean
import com.lukouguoji.gnc.viewModel.GoutFuBangViewModel
import com.lukouguoji.module_base.BaseActivity
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.Common
import com.lukouguoji.module_base.util.NumberUtil
import dev.utils.app.JSONObjectUtils.getJSONObject
import dev.utils.app.info.KeyValue
import dev.utils.common.StringUtils
import java.text.SimpleDateFormat
import java.util.*

@Route(path = ARouterConstants.ACTIVITY_URL_GOUT_FU_BANG_ACTIVITY)
class GoutFuBangActivity : BaseActivity(), View.OnClickListener {
    private lateinit var checkintongdao:Spinner
    private lateinit var viewModel: GoutFuBangViewModel

    private lateinit var carNo: EditText
    private lateinit var carNoScan: ImageView
    private lateinit var dibangWeight: TextView
    private lateinit var dibangWeightScan: ImageView

    //第一列
    private lateinit var cankaozhi: EditText
    private lateinit var volume: EditText
    private lateinit var pingbanWeight: EditText
    private lateinit var level: EditText
    private lateinit var uld: EditText

    private lateinit var boardType: Spinner

    //第二列
    private lateinit var currentWeight: EditText
    private lateinit var hangban: EditText
    private lateinit var cangwei: EditText
    private lateinit var uldWeight: EditText

    //第三列
    private lateinit var offset: EditText
    private lateinit var mudiGang: EditText
    private lateinit var number: EditText
    private lateinit var youjian: EditText
    private lateinit var fdate: EditText

    private lateinit var cargoType: Spinner


    private lateinit var remark: EditText
    private lateinit var submit: TextView
    private lateinit var labelPrint: CheckBox
    @JvmField
    @Autowired
    var carNoParam: String? = null

    @JvmField
    @Autowired
    var userIdParam: String? = null

    private fun initView() {
        checkintongdao=findViewById(R.id.checkin_tong_dao)
        carNo = findViewById(R.id.carNo)
        carNoScan = findViewById(R.id.carNoScan)
        dibangWeight = findViewById(R.id.dibangWeight)
        dibangWeightScan = findViewById(R.id.dibang_weight_scan)
        cankaozhi = findViewById(R.id.cankaozhi)
        volume = findViewById(R.id.volume)
        pingbanWeight = findViewById(R.id.pingbanWeight)
        level = findViewById(R.id.level)
        uld = findViewById(R.id.uld)
        currentWeight = findViewById(R.id.currentWeight)
        hangban = findViewById(R.id.hangban)
        cangwei = findViewById(R.id.cangwei)
        cargoType = findViewById(R.id.cargoType)
        boardType = findViewById(R.id.boardType)
        uldWeight = findViewById(R.id.uldWeight)
        offset = findViewById(R.id.offset)
        mudiGang = findViewById(R.id.mudiGang)
        number = findViewById(R.id.number)
        youjian = findViewById(R.id.youjian)
        fdate = findViewById(R.id.fdate)
        remark = findViewById(R.id.remark)
        submit = findViewById(R.id.submit)
        labelPrint=findViewById(R.id.label_print)
        carNoScan.setOnClickListener(this)
        dibangWeightScan.setOnClickListener(this)
        submit.setOnClickListener(this)
        labelPrint.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) {
                currentWeight.setText(s.toString())
                if (s != null && s.toString().trim() != "") {
                    //当前净重  地磅称重 – 平板自重 或者 当前净重 = 地磅称重 – ULD自重 （平板车和ULD只会存在一种）
                    var realWeight = s.toString().toDouble()
                    if (pingbanWeight.text != null && pingbanWeight.text.toString() != "") {
                        realWeight -= pingbanWeight.text.toString().toDouble()
                    }
                    if (uldWeight.text != null && uldWeight.text.toString() != "") {
                        realWeight -= uldWeight.text.toString().toDouble()
                    }
                    currentWeight.setText(realWeight.toString())
                    if(Math.abs(cankaozhi.text.toString().toDouble() - realWeight)<=6)
                    {
                        offset.setText(0.toString())
                        return
                    }
                    //偏差   (参考净值-当前净重) / 当前净重 * 100
                    var offsetValue = 0.0
                    if (cankaozhi.text != null && cankaozhi.text.toString() != "" && realWeight != 0.0) {
                        offsetValue = Arith.mul(Arith.div((cankaozhi.text.toString().toDouble() - realWeight), realWeight, 3), 100.0)
                    }
                    offset.setText(offsetValue.toString())
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })
*/

        carNo.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
            } else {
                if (carNo.text != null && carNo.text.toString() != "") {
                    viewModel.queryWaybillById(carNo.text.toString(), null)
                }
            }
        }
        //设置点击事件
        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.
            }

        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fu_bang)
        setBackArrow("国内出港开始复磅")
        initView()
        viewModel = ViewModelProvider(this).get(GoutFuBangViewModel::class.java)


        viewModel.queryWaybillById(carNoParam, userIdParam)
        viewModel.carDataObserver.observe(this) {
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                val jsonObject = it.getJSONObject("data")
                viewModel.fuBangInfoFormNetWork = jsonObject

                /*
                tw:2022年5月5日22:25:55 不需要对checkFlag判断，10天后可删除
                val checkFlag = jsonObject.getString("checkFlag")//Default ‘0’记录确认状态（0:未复磅;1:复磅确认;2:二次复磅;3:配载确认
                if (checkFlag == "1") {
                    Common.showToast(this, "该平板车已复磅，不可再复磅！")
                    return@observe
                }*/

                viewModel.fuBangInfo.userId = jsonObject.getIntValue("userId")
                viewModel.fuBangInfo.carId = jsonObject.getString("carId") ?: ""
                viewModel.fuBangInfo.maxWeight = jsonObject.getDoubleValue("maxWeight")
                viewModel.fuBangInfo.netWeight = jsonObject.getDoubleValue("netWeight")
                viewModel.fuBangInfo.carWeight = jsonObject.getDoubleValue("carWeight")
                viewModel.fuBangInfo.volume = jsonObject.getDoubleValue("volume")
                viewModel.fuBangInfo.mailWeight = jsonObject.getDoubleValue("mailWeight")
                viewModel.fuBangInfo.pc = jsonObject.getIntValue("pc")
                viewModel.fuBangInfo.flight = jsonObject.getString("flight") ?: ""
                viewModel.fuBangInfo.flight = jsonObject.getString("flight") ?: ""
                viewModel.fuBangInfo.priority = jsonObject.getIntValue("priority")
                viewModel.fuBangInfo.fdest = jsonObject.getString("fdest") ?: ""
                viewModel.fuBangInfo.fdate = jsonObject.getString("fdate") ?: ""
                viewModel.fuBangInfo.location = jsonObject.getString("location") ?: ""
                viewModel.fuBangInfo.cargoType = jsonObject.getString("cargoType") ?: ""
                viewModel.fuBangInfo.uld = jsonObject.getString("uld") ?: ""
                viewModel.fuBangInfo.uldWeight = jsonObject.getDoubleValue("uldWeight")
                viewModel.fuBangInfo.boardType = jsonObject.getString("boardType") ?: ""
                viewModel.fuBangInfo.remark = jsonObject.getString("remark") ?: ""

                carNo.setText(viewModel.fuBangInfo.carId)
                uld.setText(viewModel.fuBangInfo.uld)
                uldWeight.setText(viewModel.fuBangInfo.uldWeight.toString())
                cankaozhi.setText(viewModel.fuBangInfo.netWeight.toString())
//                currentWeight.setText("")
                var offsetValue = 0.0
                if (viewModel.fuBangInfo.maxWeight != null && viewModel.fuBangInfo.netWeight != null) {
                    offsetValue = viewModel.fuBangInfo.maxWeight!! - viewModel.fuBangInfo.netWeight!!
                }
                offset.setText(offsetValue.toString())
                volume.setText(viewModel.fuBangInfo.volume.toString())
                pingbanWeight.setText(viewModel.fuBangInfo.carWeight.toString())
                level.setText(viewModel.fuBangInfo.priority.toString())
                hangban.setText(viewModel.fuBangInfo.flight)
                cangwei.setText(viewModel.fuBangInfo.location)
                mudiGang.setText(viewModel.fuBangInfo.fdest)
                number.setText(viewModel.fuBangInfo.pc.toString())
                youjian.setText(viewModel.fuBangInfo.mailWeight.toString())
                fdate.setText(viewModel.fuBangInfo.fdate)

                remark.setText(viewModel.fuBangInfo.remark)

                //货物类型 下拉框赋值
                viewModel.cargoSelect(System.currentTimeMillis().toString())
                viewModel.cargoObserver.observe(this) { vd ->
                    viewModel.cargoList = vd.getJSONArray("data")
                    var position = 0
                    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) {
                            position = index
                        }
                    }
                    initSpinner(cargoType, viewModel.cargoList, position,null)
                }

                //板型类型 下拉框赋值
                viewModel.boardSelect(System.currentTimeMillis().toString())
                viewModel.boardObserver.observe(this) { vd ->
                    viewModel.boardList = vd.getJSONArray("data")
                    var position = 0
                    for ((index, obj) in viewModel.boardList.withIndex()) {
                        val tempObj = obj as JSONObject
                        val name = tempObj.getString("name")
                        val code = tempObj.getString("code")
                        if (viewModel.fuBangInfo.boardType == code) {
                            position = index
                        }
                    }
                    initSpinner(boardType, viewModel.boardList, position,null)
                }


            } else {
                //无数据
            }
        }

        viewModel.weightDataObserver.observe(this){ vd->
            dibangWeight.setText(vd)
        }
        //监听完成复磅
        viewModel.completedObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            if (Constant.Result.succ == status) {
                if (data == "1") {

                    print()
                    carNo.setText("")
                    Common.alertDialog(this, "完成复磅！") { dialog ->
                        dialog.dismiss()
                    }
                } else if (data == "2") {
                    Common.alertDialog(this, "板车不存在！") { dialog ->
                        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 == "4") {
                    Common.alertDialog(this, "航班已截载！") { dialog ->
                        dialog.dismiss()
                    }

                } else {
                    Common.alertDialog(this, "复磅失败！") { dialog ->
                        dialog.dismiss()
                    }
                }
            } else {
//                Common.showToastLong(this, "收运失败！ ")
                Common.alertDialog(this, "复磅失败！") { dialog ->
                    dialog.dismiss()
                }
            }
        }
        viewModel.weightThread.start()
    }
    fun print(){
        var date=Date()
        var format=SimpleDateFormat("yyyy年MM月dd日")
        var numberUtil= NumberUtil()
        var label=  LabelBean (
            titleName = "扬州泰州机场",
            dest = mudiGang.text.toString(),
            carId = carNo.text.toString(),
            fno = hangban.text.toString(),
            pc = number.text.toString(),
            weight = cankaozhi.text.toString(),
            volume = volume.text.toString(),
            location = cangwei.text.toString(),
            opdate =  fdate .text.toString()
        )

        ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_Printer_ACTIVITY).withObject("label",label)
            .navigation(this)
    }
    override fun onDestroy() {
        viewModel. weightThread.interrupt();
        super.onDestroy()
    }
    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.carNoScan -> {
                    scanCode(Constant.RequestCode.gnc_fubang_car_no)
                }
                R.id.dibang_weight_scan -> {
                    dibangWeight.setText("")
                }
                R.id.submit -> {
                    if (getAllEditData()) {
                        Common.secondConfirmDialog(this, "确认复磅") { dialog ->
                            viewModel.completed(viewModel.fuBangInfo)
                            dialog.dismiss()
                            loading()
                        }
                    }
                }
                R.id.label_print -> {
                    //todo 打印挂签
//                    print()
                }
                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_fubang_car_no -> {
                    carNo.setText("$content")
                    viewModel.queryWaybillById(content, null)
                }
            }
        }
    }

    /**
     * 同步viewModel的实体类数据
     */
    private fun getAllEditData(): Boolean {
        viewModel.fuBangInfo.carId = carNo.text.toString()
        viewModel.fuBangInfo.netWeight = currentWeight.text.toString().toDouble()
        viewModel.fuBangInfo.carWeight = pingbanWeight.text.toString().toDouble()
        viewModel.fuBangInfo.volume = volume.text.toString().toDouble()
        viewModel.fuBangInfo.pc = number.text.toString().toInt()
        viewModel.fuBangInfo.flight = hangban.text.toString()
        viewModel.fuBangInfo.priority = if (StringUtils.isNotEmpty(level.text.toString())) level.text.toString().toInt() else -9999
        viewModel.fuBangInfo.fdest = mudiGang.text.toString()
        viewModel.fuBangInfo.location = cangwei.text.toString()
        viewModel.fuBangInfo.mailWeight = youjian.text.toString().toDouble()
        viewModel.fuBangInfo.uld = uld.text.toString()
        viewModel.fuBangInfo.uldWeight = uldWeight.text.toString().toDouble()
        viewModel.fuBangInfo.fdate = fdate.text.toString()
        viewModel.fuBangInfo.remark = remark.text.toString()

        if (offset.text == null || offset.text.toString() == "" || offset.text.toString().toDouble() < -3 || offset.text.toString().toDouble() > 3) {
            Common.showToast(this, "偏差超出3%，不允许复磅！")
            return false
        }
        if (viewModel.fuBangInfo.carId == "") {
            Common.showToast(this, "请填写平板车编号！")
            return false
        }
        if (viewModel.fuBangInfo.netWeight == 0.0) {
            Common.showToast(this, "请填写净重！")
            return false
        }
        if (viewModel.fuBangInfo.carWeight == 0.0) {
            Common.showToast(this, "请填写平板车重量！")
            return false
        }
        if (viewModel.fuBangInfo.volume == 0.0) {
            Common.showToast(this, "请填写体积！")
            return false
        }
        if (viewModel.fuBangInfo.pc < 1) {
            Common.showToast(this, "请填写件数！")
            return false
        }
        if (viewModel.fuBangInfo.flight == "") {
            Common.showToast(this, "航班不能为空！")
            return false
        }
        if (viewModel.fuBangInfo.priority < 0) {
            Common.showToast(this, "请填写优先级！")
            return false
        }
        if (viewModel.fuBangInfo.fdest == "") {
            Common.showToast(this, "请填写目的港！")
            return false
        }
//        if (viewModel.fuBangInfo.location == "") {
//            Common.showToast(this, "请填写舱位！")
//            return false
//        }
        /*if (viewModel.fuBangInfo.mailWeight == 0.0) {
            Common.showToast(this, "邮件不能为空！")
            return false
        }
        if (viewModel.fuBangInfo.uld == "") {
            Common.showToast(this, "请填写ULD编号！")
            return false
        }
        if (viewModel.fuBangInfo.uldWeight == 0.0) {
            Common.showToast(this, "请填写ULD自重！")
            return false
        }
        if (viewModel.fuBangInfo.boardType == "") {
            Common.showToast(this, "请填写板型！")
            return false
        }
        if (viewModel.fuBangInfo.remark == "") {
            Common.showToast(this, "备注不能为空！")
            return false
        }*/

        return true
    }

    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? ) : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
            when (spinnerView) {
                R.id.cargoType -> {
                    viewModel.fuBangInfo.cargoType = if (StringUtils.isNotEmpty(hint) && i == viewModel.cargoList.size) {
                        ""
                    } else {
                        viewModel.cargoList.getJSONObject(i).getString("code")
                    }
                }
                R.id.boardType -> {
                    viewModel.fuBangInfo.boardType = if (StringUtils.isNotEmpty(hint) && i == viewModel.boardList.size) {
                        ""
                    } else {
                        viewModel.boardList.getJSONObject(i).getString("code")
                    }
                }
            }
        }

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