package com.lukouguoji.gnc.activity

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.adapt.GncTransferRefListAdapter
import com.lukouguoji.gnc.model.GncTransferRef
import com.lukouguoji.gnc.viewModel.GoutTransferInfoViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.util.Common

@Route(path = ARouterConstants.ACTIVITY_URL_GOUT_TRANSFER_INFO_ACTIVITY)
class GoutTransferInfoActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GoutTransferInfoViewModel

    private lateinit var carNo: TextView
    private lateinit var scrollView: ScrollView
    private lateinit var bottomLayout: LinearLayout

    //第一列
    private lateinit var guobangWeight: EditText
    private lateinit var volume: EditText
    private lateinit var level: EditText
    private lateinit var fdate: Button
    private lateinit var fubangStatus: EditText

    //第二列
    private lateinit var currentWeight: EditText
    private lateinit var pc: EditText
    private lateinit var carrier: EditText
    private lateinit var mudiGang: EditText

    //第三列
    private lateinit var cargoWeight: EditText
    private lateinit var cargoType: TextView
    private lateinit var hangban: EditText
    private lateinit var cangwei: EditText

    //备注
    private lateinit var remark: EditText

    //关联运单号
    private lateinit var refWaybill: LinearLayout
    private lateinit var adapter: GncTransferRefListAdapter
    private lateinit var recyclerView: RecyclerView
    private lateinit var recyclerViewLayout: LinearLayout

    //确认
    private lateinit var submit: TextView

    @JvmField
    @Autowired
    var id: Int = -9999

    @JvmField
    @Autowired
    var carId: String? = null

    private fun initView() {
        scrollView = findViewById(R.id.scrollView)
        bottomLayout = findViewById(R.id.bottomLayout)
        carNo = findViewById(R.id.carNo)
        guobangWeight = findViewById(R.id.guobangWeight)
        volume = findViewById(R.id.volume)
        level = findViewById(R.id.level)
        fdate = findViewById(R.id.fdate)
        fubangStatus = findViewById(R.id.fubangStatus)
        currentWeight = findViewById(R.id.currentWeight)
        pc = findViewById(R.id.pc)
        carrier = findViewById(R.id.carrier)
        mudiGang = findViewById(R.id.mudiGang)
        cargoWeight = findViewById(R.id.cargoWeight)
        cargoType = findViewById(R.id.cargoType)
        hangban = findViewById(R.id.hangban)
        cangwei = findViewById(R.id.cangwei)
        remark = findViewById(R.id.remark)
        refWaybill = findViewById(R.id.refWaybill)
        submit = findViewById(R.id.submit)
        //加载列表
        recyclerViewLayout = findViewById(R.id.gnc_transfer_list_layout)
        val layoutManager = LinearLayoutManager(this)
        adapter = GncTransferRefListAdapter(this, viewModel.gncTransferRefList)
        recyclerView = findViewById(R.id.gnc_transfer_waybill_list)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        refWaybill.setOnClickListener(this)

        submit.setOnClickListener(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gout_transfer_info)
        setBackArrow("国内出港转运确认")
        viewModel = ViewModelProvider(this).get(GoutTransferInfoViewModel::class.java)
        initView()

        viewModel.queryFlatByNo(id, carId)
        viewModel.queryFlatByNoObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getJSONObject("data")
            if (Constant.Result.succ == status && data != null) {
                viewModel.wbListArrFromNet = data.getJSONArray("wbList")
                viewModel.flatcarObjFromNet = data.getJSONObject("flatcar")

                //确认人
                val transId = viewModel.flatcarObjFromNet.getString("transId")
                //确认人（如果此值不空，只能查看，也就是转运确定按钮隐藏）
                if (transId != null && transId != "") {
                    bottomLayout.visibility = View.GONE
                } else {
                    bottomLayout.visibility = View.VISIBLE
                }

                //板车号
                carNo.text = viewModel.flatcarObjFromNet.getString("carId") ?: ""
                //过磅重量
                guobangWeight.setText(viewModel.flatcarObjFromNet.getDoubleValue("totalWeight").toString())
                //净重
                currentWeight.setText(viewModel.flatcarObjFromNet.getDoubleValue("netWeight").toString())

                // 货重
                cargoWeight.setText(viewModel.flatcarObjFromNet.getDoubleValue("cargoWeight").toString())
                // 体积
                volume.setText(viewModel.flatcarObjFromNet.getDoubleValue("volume").toString())
                // 件数
                pc.setText(viewModel.flatcarObjFromNet.getIntValue("pc").toString())
                // 货物类型
                cargoType.text = viewModel.flatcarObjFromNet.getString("cargoType").toString()
                // 优先级
                level.setText(viewModel.flatcarObjFromNet.getString("priority") ?: "")
                // 承运人
                carrier.setText(viewModel.flatcarObjFromNet.getString("carrier") ?: "")
                // 航班号
                hangban.setText(viewModel.flatcarObjFromNet.getString("fno") ?: "")
                // 航班日期
                fdate.text = viewModel.flatcarObjFromNet.getString("fdate") ?: ""
                // 目的港
                mudiGang.setText(viewModel.flatcarObjFromNet.getString("fdest") ?: "")
                // 舱位
                cangwei.setText(viewModel.flatcarObjFromNet.getString("location") ?: "")
                // 复磅状态
                fubangStatus.setText(viewModel.flatcarObjFromNet.getString("checkFlag") ?: "")
                // 备注
                remark.setText(viewModel.flatcarObjFromNet.getString("remark") ?: "")

                //加载关联运单列表
                viewModel.gncTransferRefList.clear()
                viewModel.wbListArrFromNet.forEach { waybill ->
                    var waybillObj = waybill as JSONObject
                    val gncTransferRef = GncTransferRef(
                        waybillObj.getIntValue("whId"), waybillObj.getString("wbNo") ?: "",
                        waybillObj.getString("agentCode") ?: "", waybillObj.getString("spCode") ?: "",
                        waybillObj.getString("goods") ?: "", waybillObj.getString("flight") ?: "", waybillObj.getString("range") ?: ""
                    )
                    viewModel.gncTransferRefList.add(gncTransferRef)
                }
                adapter.notifyDataSetChanged()
            }
        }

        viewModel.completedTransferObserver.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) {
                Common.alertDialog(this, "转运成功！") { dialog ->
                    dialog.dismiss()
                }
            } else {
                if (msg != null && msg != "") {
                    Common.alertDialog(this, msg) { dialog ->
                        dialog.dismiss()
                    }
                } else {
                    Common.alertDialog(this, "转运失败！") { dialog ->
                        dialog.dismiss()
                    }
                }
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.refWaybill -> {
                    //开关关联列表
                    if (recyclerViewLayout.visibility == View.GONE) {
                        recyclerViewLayout.visibility = View.VISIBLE
                    } else {
                        recyclerViewLayout.visibility = View.GONE
                    }
                    scrollView.post(Runnable { scrollView.scrollTo(0, scrollView.bottom) })
//                    Common.showToast(this, "关联运单号")
                }
                R.id.submit -> {
                    if(getAllEditData()){
                        loading()
                        viewModel.completedTransfer(viewModel.flatcarObjFromNet)
                    }else{

                    }
                }
                else -> {
                    Toast.makeText(this, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }

    }

    /**
     * 同步viewModel的实体类数据
     */
    private fun getAllEditData(): Boolean {
        /*if (carNo.text.toString() == "") {
            Common.showToast(this, getAllEditDataAlterStr("平板车编号"))
            return false
        }
        if (guobangWeight.text.toString().toDouble() <= 0.0) {
            Common.showToast(this, getAllEditDataAlterStr("过磅重量"))
            return false
        }
        if (currentWeight.text.toString().toDouble() <= 0.0) {
            Common.showToast(this, getAllEditDataAlterStr("净重"))
            return false
        }
        if (cargoWeight.text.toString().toDouble() <= 0.0) {
            Common.showToast(this, getAllEditDataAlterStr("货重"))
            return false
        }
        if (volume.text.toString().toDouble() <= 0.0) {
            Common.showToast(this, getAllEditDataAlterStr("体积"))
            return false
        }
        if (pc.text.toString().toInt() < 1) {
            Common.showToast(this, getAllEditDataAlterStr("件数"))
            return false
        }
        if (cargoType.text.toString() == "") {
            Common.showToast(this, getAllEditDataAlterStr("货物类型"))
            return false
        }*/
        /* if (level.text.toString() == "") {
             Common.showToast(this, "请填写优先级！")
             return false
         }*/
        /*if (carrier.text.toString() == "") {
            Common.showToast(this, getAllEditDataAlterStr("承运人"))
            return false
        }
        if (hangban.text.toString() == "") {
            Common.showToast(this, getAllEditDataAlterStr("航班号"))
            return false
        }
        if (fdate.text.toString() == "") {
            Common.showToast(this, getAllEditDataAlterStr("航班日期"))
            return false
        }
        if (mudiGang.text.toString() == "") {
            Common.showToast(this, getAllEditDataAlterStr("目的港"))
            return false
        }*/
//        if (cangwei.text.toString() == "") {
//            Common.showToast(this, getAllEditDataAlterStr("舱位"))
//            return false
//        }
        if (fubangStatus.text.toString() == "未复磅") {
            Common.showToast(this, "未复磅，不可转运！")
            return false
        }
        /* viewModel.flatcarObjFromNet["carId"] = carNo.text.toString()//板车号
         viewModel.flatcarObjFromNet["totalWeight"] = guobangWeight.text.toString().toDouble()//过磅重量
         viewModel.flatcarObjFromNet["netWeight"] = currentWeight.text.toString().toDouble()//净重
         viewModel.flatcarObjFromNet["cargoWeight"] = cargoWeight.text.toString().toDouble()//货重
         viewModel.flatcarObjFromNet["volume"] = volume.text.toString().toDouble()//体积
         viewModel.flatcarObjFromNet["pc"] = pc.text.toString().toInt()//件数
         viewModel.flatcarObjFromNet["cargoType"] = cargoType.text.toString()//货物类型*/

        viewModel.flatcarObjFromNet["remark"] = remark.text.toString()//货物类型


        return true
    }

    private fun getAllEditDataAlterStr(title: String) = "${title}为空，不可转运！"
}