package com.lukouguoji.gjj.activity

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
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.gjj.R
import com.lukouguoji.gjj.adapt.GjjCangDanInfoAdapter
import com.lukouguoji.gjj.common.GjjCommon
import com.lukouguoji.gjj.model.GjjCangDanInfoItemModel
import com.lukouguoji.gjj.viewModel.GjjCangDanInfoViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.String.isValidInt
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.util.Common

@Route(path = ARouterConstants.ACTIVITY_URL_GJJ_CANG_DAN_INFO)
class GjjCangDanInfoActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GjjCangDanInfoViewModel
    private lateinit var adapter: GjjCangDanInfoAdapter
    private val collectList = ArrayList<GjjCangDanInfoItemModel>()

    private lateinit var receive: EditText
    private lateinit var cardNo: EditText
    private lateinit var telPhone: EditText

    private lateinit var cancel: TextView
    private lateinit var submit: TextView


    @JvmField
    @Autowired
    var id: String? = null

    @JvmField
    @Autowired
    var ref: String? = null

    @JvmField
    @Autowired
    var fid: Int = -9999

    @JvmField
    @Autowired
    var prefix: String? = null

    private fun initView() {
        viewModel = ViewModelProvider(this).get(GjjCangDanInfoViewModel::class.java)
        viewModel.waybillFormNetWork["prefix"] = prefix

        val layoutManager = GridLayoutManager(this, 2)
        adapter = GjjCangDanInfoAdapter(this, collectList)
        var recyclerView: RecyclerView = findViewById(R.id.collectList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        receive = findViewById(R.id.receive)
        cardNo = findViewById(R.id.cardNo)
        telPhone = findViewById(R.id.telPhone)
        cancel = findViewById(R.id.cancel)
        submit = findViewById(R.id.submit)

        cancel.setOnClickListener(this)
        submit.setOnClickListener(this)

        cardNo.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                //失去焦点
                var cardNoStr = cardNo.text.toString()
                if (cardNoStr != "" && !Common.isIDNumber(cardNoStr)) {
                    Common.showToast(this, "请输入正确的身份证号！")
                }
            }
        }

        telPhone.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                //失去焦点
                var telPhoneStr = telPhone.text.toString()
                if (telPhoneStr != "" && !Common.isPhoneNum(telPhoneStr)) {
                    Common.showToast(this, "请输入正确的电话号码！")
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gjj_cang_dan_info)
        initView()


        //1.新增
        if (id == null) {
//        if (true) {
            setBackArrow("新增国际进港舱单")

            selObserve()
            initData(GjjCommon.CangDan.Info.add)

            viewModel.saveFestGjjCangDanObserver.observe(this) {
                loadingCancel()
                val status = it.getString("status")
                val msg = it.getString("msg")
                if (Constant.Result.succ == status) {
                    val dataStatus = it.getString("data")
                    if (Constant.Result.succ == dataStatus) {
                        Common.showToast(this, "新增成功！")
                        reset()
                    } else if (Constant.Result.code2 == dataStatus) {
                        Common.showToast(this, "没有选择航班，请选择航班！")
                    } else {
                        Common.showToast(this, "新增失败！")
                    }
                } else {
                    Common.showToast(this, "新增失败！")
                }
            }
            return
        }
        //2.查看
        if (id != null && id != "" && ref != null && ref == GjjCommon.CangDan.Ref.read) {
//        if (true) {
            setBackArrow("国际进港舱单详情")

            initNetWork(id, null, GjjCommon.CangDan.Info.read)
            receive.isEnabled = false
            receive.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_disable_shape)
            cardNo.isEnabled = false
            cardNo.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_disable_shape)
            telPhone.isEnabled = false
            telPhone.setBackgroundResource(R.drawable.gjj_cang_dan_info_edit_disable_shape)

            cancel.visibility = View.GONE
            submit.visibility = View.GONE
            return
        }
        //3.编辑
        if (id != null && id != "" && ref != null && ref != GjjCommon.CangDan.Ref.read) {
            setBackArrow("国际进港舱单详情")

            initNetWork(id, null, GjjCommon.CangDan.Info.update)

            viewModel.updateFestGjjCangDanObserver.observe(this) {
                loadingCancel()
                val status = it.getString("status")
                val msg = it.getString("msg")
                if (Constant.Result.succ == status) {
                    var dataStatus = it.getString("data")
                    if (Constant.Result.succ == dataStatus) {
                        Common.showToast(this, "修改成功！")
                    } else if (Constant.Result.code2 == dataStatus) {
                        Common.showToast(this, "没有选择航班，请选择航班！")
                    } else {
                        Common.showToast(this, "修改失败！")
                    }
                } else {
                    Common.showToast(this, "修改失败！")
                }
            }
            return
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.cancel -> {
                    finish()
                }
                R.id.submit -> {
                    submit()
                }
                else -> {
                    Toast.makeText(this, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 监听运单详情返回数据
     *
     * write = false 只读 true 可写
     */
    private fun waybillObserve(status: String) {
        viewModel.waybillLiveData.observe(this) {
            val resStatus = it.getString("status")
            if (Constant.Result.succ == resStatus) {
                viewModel.waybillFormNetWork = it.getJSONObject("data")

                val consignee = viewModel.waybillFormNetWork.getString("consignee") ?: ""//收货人
                val cneeId = viewModel.waybillFormNetWork.getString("cneeId") ?: ""//收货人身份证号
                val cneeTel = viewModel.waybillFormNetWork.getString("cneeTel") ?: ""//收货人电话

                initData(status)

                ////收获 信息
                receive.setText(consignee)
                cardNo.setText(cneeId)
                telPhone.setText(cneeTel)

            } else {
                //无数据
            }
        }
    }

    /**
     * 下拉框赋值
     */
    private fun selObserve() {
        ///////////////    下拉框   start
        viewModel.agentCode(System.currentTimeMillis().toString())
        viewModel.agentCodeObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择代理人"
            noneObj["code"] = ""
            viewModel.agentCodeList.add(noneObj)
            viewModel.agentCodeList.addAll(vd.getJSONArray("data"))

            totalRequestNotifyAdapter()
        }

        viewModel.business(Constant.businessType.II)
        viewModel.businessObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择业务类型"
            noneObj["code"] = ""
            viewModel.businessList.add(noneObj)
            viewModel.businessList.addAll(vd.getJSONArray("data"))

            totalRequestNotifyAdapter()
        }

        viewModel.specialCode(System.currentTimeMillis().toString())
        viewModel.specialCodeObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择特码"
            noneObj["code"] = ""
            viewModel.specialCodeList.add(noneObj)
            viewModel.specialCodeList.addAll(vd.getJSONArray("data"))

            totalRequestNotifyAdapter()
        }

        val noneObj = JSONObject()
        noneObj["name"] = "请选择运单类型"
        noneObj["code"] = ""
        val noneObj2 = JSONObject()
        noneObj2["name"] = "国际进港（国内中转）"
        noneObj2["code"] = "CIII1"
        val noneObj3 = JSONObject()
        noneObj3["name"] = "国际进港（国际直航）"
        noneObj3["code"] = "IIII1"
        val noneObj4 = JSONObject()
        noneObj4["name"] = "国际进港（直航中转）"
        noneObj4["code"] = "IIIO1"
        viewModel.awbList.add(noneObj)
        viewModel.awbList.add(noneObj2)
        viewModel.awbList.add(noneObj3)
        viewModel.awbList.add(noneObj4)
        /* viewModel.awb(System.currentTimeMillis().toString())
         viewModel.awbObserver.observe(this) { vd ->
             val noneObj = JSONObject()
             noneObj["name"] = "请选择运单类型"
             noneObj["code"] = ""
             viewModel.awbList.add(noneObj)
             viewModel.awbList.addAll(vd.getJSONArray("data"))

             totalRequestNotifyAdapter()
         }*/
        ///////////////    下拉框   end
    }

    /**
     * 所有请求结束，更细adpter 只适用于刚开始加载
     */
    private fun totalRequestNotifyAdapter() {
        adapter.notifyDataSetChanged()
    }

    /**
     * 初始化网络请求
     */
    private fun initNetWork(id: String?, wbNo: String?, status: String) {
        selObserve()
        viewModel.queryWaybillById(id!!.toInt(), wbNo)
        waybillObserve(status)
    }

    /**
     * 提交
     */
    private fun submit() {
        for ((index, c) in collectList.withIndex()) {
            val titleName = c.titleName//标题
            val inputContent = c.inputContent//输入内容
            val selContentCode = c.selContentCode//选择内容
            val must = c.isMust//是否必填
            val sel = c.isSel//是否下拉框
            val titleCodePre = c.titleCodePre//前缀
            val inputContentPre = c.inputContentPre//前缀
            //下拉框
            if (sel) {
                if (must && selContentCode == "") {
                    Common.showToast(this, "请选择$titleName")
                    return
                }
                viewModel.waybillFormNetWork[c.titleCode] = selContentCode
            }
            //输入框
            else {
                if (must && inputContent == "") {
                    Common.showToast(this, "请输入$titleName")
                    return
                }
                viewModel.waybillFormNetWork[c.titleCode] = inputContent
                //前缀不为空时，赋值
                if (titleCodePre != null && titleCodePre != "" && inputContentPre != null && inputContentPre != "") {
                    viewModel.waybillFormNetWork[titleCodePre] = inputContentPre
                }
            }
        }

        //1.新增
        if (id == null) {
            //身份证、电话号码校验
            val cardNoStr = cardNo.text.toString()
            val telPhoneStr = telPhone.text.toString()
            if (cardNoStr != "" && !Common.isIDNumber(cardNoStr)) {
                Common.showToast(this, "请输入正确的身份证号！")
                return
            }
            if (telPhoneStr != "" && !Common.isPhoneNum(telPhoneStr)) {
                Common.showToast(this, "请输入正确的电话号码！")
                return
            }
            //输入运单号，需要校验规则，判断前7位除以7得到的余数是否等于第8位，是即符合规则，否则提示
            val prefixStr = viewModel.waybillFormNetWork.getString("prefix")
            if (prefixStr.length != 3 || !prefixStr.isValidInt()) {
                Common.showToast(this, "请输入正确的运单号前缀格式！")
                return
            }
            val checkWaybill = viewModel.waybillFormNetWork.getString("no")
            if (checkWaybill.length != 8 || !checkWaybill.isValidInt()) {
                Common.showToast(this, "请输入正确的运单号格式！")
                return
            }
            var subSequence = checkWaybill.subSequence(0, 7).toString().toInt()
            var subSequence2 = checkWaybill[7].toString().toInt()
            if (subSequence % 7 != subSequence2) {
                Common.showToast(this, "请输入正确的运单号格式！")
                return
            }

            loading()
            viewModel.saveFestGjjCangDan(
                fid, viewModel.waybillFormNetWork.getString("prefix"), viewModel.waybillFormNetWork.getString("no"),
                viewModel.waybillFormNetWork.getString("agentCode"), viewModel.waybillFormNetWork.getString("spCode"),
                viewModel.waybillFormNetWork.getString("location"), viewModel.waybillFormNetWork.getIntValue("totalPc"),
                viewModel.waybillFormNetWork.getIntValue("pc"), viewModel.waybillFormNetWork.getDoubleValue("weight"),
                viewModel.waybillFormNetWork.getString("goods"), viewModel.waybillFormNetWork.getString("origin"),
                viewModel.waybillFormNetWork.getString("dest"), viewModel.waybillFormNetWork.getString("businessType"),
                viewModel.waybillFormNetWork.getString("remark"), viewModel.waybillFormNetWork.getString("awbType"),
                viewModel.waybillFormNetWork.getDoubleValue("cashWeight"), receive.text.toString(), cardNoStr, telPhoneStr
            )
            return
        }
        //2.查看
        if (id != null && id != "" && ref != null && ref == GjjCommon.CangDan.Ref.read) {
            finish()
            return
        }
        //3.编辑
        if (id != null && id != "" && ref != null && ref != GjjCommon.CangDan.Ref.read) {

            //身份证、电话号码校验
            val cardNoStr = cardNo.text.toString()
            val telPhoneStr = telPhone.text.toString()
            if (cardNoStr != "" && !Common.isIDNumber(cardNoStr)) {
                Common.showToast(this, "请输入正确的身份证号！")
                return
            }
            if (telPhoneStr != "" && !Common.isPhoneNum(telPhoneStr)) {
                Common.showToast(this, "请输入正确的电话号码！")
                return
            }
            loading()
            viewModel.updateFestGjjCangDan(
                id!!.toInt(),
                fid, viewModel.waybillFormNetWork.getString("prefix"), viewModel.waybillFormNetWork.getString("no"),
                viewModel.waybillFormNetWork.getString("agentCode"), viewModel.waybillFormNetWork.getString("spCode"),
                viewModel.waybillFormNetWork.getString("location"), viewModel.waybillFormNetWork.getIntValue("totalPc"),
                viewModel.waybillFormNetWork.getIntValue("pc"), viewModel.waybillFormNetWork.getDoubleValue("weight"),
                viewModel.waybillFormNetWork.getString("goods"), viewModel.waybillFormNetWork.getString("origin"),
                viewModel.waybillFormNetWork.getString("dest"), viewModel.waybillFormNetWork.getString("businessType"),
                viewModel.waybillFormNetWork.getString("remark"), viewModel.waybillFormNetWork.getString("awbType"),
                viewModel.waybillFormNetWork.getDoubleValue("cashWeight"), receive.text.toString(), cardNoStr, telPhoneStr
            )
            return
        }
    }

    /**
     * 初始化列表数据
     */
    private fun initData(status: String) {
        var write = false
        var waybillOperator = false
        when (status) {
            GjjCommon.CangDan.Info.read -> {
                write = false
                waybillOperator = false
            }
            GjjCommon.CangDan.Info.add -> {
                write = true
                waybillOperator = true
            }
            GjjCommon.CangDan.Info.update -> {
                write = true
                waybillOperator = false
            }
        }

        collectList.clear()
        collectList.add(
            GjjCangDanInfoItemModel(
                true, waybillOperator, "运单号", "no", viewModel.waybillFormNetWork.getString("no") ?: "",
                "prefix", viewModel.waybillFormNetWork.getString("prefix") ?: ""
            )
        )
        collectList.add(
            GjjCangDanInfoItemModel(
                true,
                write,
                "代理",
                "agentCode",
                viewModel.agentCodeList,
                viewModel.waybillFormNetWork.getString("agentCode") ?: "", viewModel.waybillFormNetWork.getString("agentName") ?: ""
            )
        )
        collectList.add(
            GjjCangDanInfoItemModel(
                true,
                write,
                "业务类型",
                "businessType",
                viewModel.businessList,
                viewModel.waybillFormNetWork.getString("businessType") ?: "", ""
            )
        )
        collectList.add(
            GjjCangDanInfoItemModel(
                true,
                write,
                "总件数",
                "totalPc",
                viewModel.waybillFormNetWork.getString("totalPc") ?: ""
            )
        )
        collectList.add(GjjCangDanInfoItemModel(true, write, "实到件数", "pc", viewModel.waybillFormNetWork.getString("pc") ?: ""))
        collectList.add(
            GjjCangDanInfoItemModel(
                true,
                write,
                "实到重量",
                "weight",
                viewModel.waybillFormNetWork.getString("weight") ?: ""
            )
        )
        collectList.add(GjjCangDanInfoItemModel(true, write, "品名", "goods", viewModel.waybillFormNetWork.getString("goods") ?: ""))
        collectList.add(
            GjjCangDanInfoItemModel(
                false,
                write,
                "计费重量",
                "cashWeight",
                viewModel.waybillFormNetWork.getString("cashWeight") ?: ""
            )
        )
        collectList.add(
            GjjCangDanInfoItemModel(
                false,
                write,
                "特码",
                "spCode",
                viewModel.specialCodeList,
                viewModel.waybillFormNetWork.getString("spCode") ?: "", ""
            )
        )
        collectList.add(GjjCangDanInfoItemModel(true, write, "始发港", "origin", viewModel.waybillFormNetWork.getString("origin") ?: ""))
        collectList.add(GjjCangDanInfoItemModel(true, write, "目的港", "dest", viewModel.waybillFormNetWork.getString("dest") ?: ""))
        collectList.add(
            GjjCangDanInfoItemModel(
                true,
                write,
                "运单类型",
                "awbType",
                viewModel.awbList,
                viewModel.waybillFormNetWork.getString("awbType") ?: "", ""
            )
        )
        collectList.add(GjjCangDanInfoItemModel(false, write, "库位", "location", viewModel.waybillFormNetWork.getString("location") ?: ""))
        collectList.add(GjjCangDanInfoItemModel(false, write, "备注", "remark", viewModel.waybillFormNetWork.getString("remark") ?: ""))

        totalRequestNotifyAdapter()
    }

    /**
     * 清空数据
     */
    private fun reset() {
        //1.清空数据
        viewModel.waybillFormNetWork.clear()
        receive.setText("")
        cardNo.setText("")
        telPhone.setText("")
        initData(GjjCommon.CangDan.Info.add)
    }
}