package com.lukouguoji.cargo.activity

import android.content.Intent
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.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.cargo.R
import com.lukouguoji.cargo.adapt.CargoTrackingListAdapter
import com.lukouguoji.cargo.adapt.CargoTrackingToLeftListAdapter
import com.lukouguoji.cargo.model.CargoTrackingList
import com.lukouguoji.cargo.viewModel.CargoTrackingListViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.common.Constant.CargoTracking.Companion.exportStatus
import com.lukouguoji.module_base.common.Constant.CargoTracking.Companion.gjStatus
import com.lukouguoji.module_base.common.Constant.CargoTracking.Companion.gnStatus
import com.lukouguoji.module_base.common.Constant.CargoTracking.Companion.importStatus
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_CARGO_TRACKING)
class CargoTrackingActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: CargoTrackingListViewModel

    private lateinit var adapter: CargoTrackingListAdapter
    private val collectList = ArrayList<CargoTrackingList>()
    private lateinit var adapter2: CargoTrackingToLeftListAdapter
    private val collectList2 = ArrayList<CargoTrackingList>()

    //搜索条件
    private lateinit var wbNo: EditText
    private lateinit var wbNoScan: ImageView
    private lateinit var countryType: TextView
    private lateinit var ieFlag: TextView
    private lateinit var searchLayout: LinearLayout

    private val countryTypeList = JSONArray()//地区类型
    private var countryTypeCode = ""
    private val ieFlagList = JSONArray()//进出港
    private var ieFlagCode = ""

    @JvmField
    @Autowired
    var countryTypeParam: String? = null

    @JvmField
    @Autowired
    var ieFlagParam: String? = null

    @JvmField
    @Autowired
    var wbNoParam: String? = null

    private fun initView() {
        viewModel = ViewModelProvider(this).get(CargoTrackingListViewModel::class.java)
        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        adapter = CargoTrackingListAdapter(this, collectList)
        var recyclerView: RecyclerView = findViewById(R.id.recyclerList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        val layoutManager2 = LinearLayoutManager(this)
        layoutManager2.orientation = RecyclerView.HORIZONTAL
        layoutManager2.reverseLayout = true
        adapter2 = CargoTrackingToLeftListAdapter(this, collectList2)
        var recyclerView2: RecyclerView = findViewById(R.id.recyclerList2)
        recyclerView2.layoutManager = layoutManager2
        recyclerView2.adapter = adapter2

        wbNo = findViewById(R.id.wbNo)
        wbNoScan = findViewById(R.id.wbNoScan)
        countryType = findViewById(R.id.countryType)
        ieFlag = findViewById(R.id.ieFlag)
        searchLayout = findViewById(R.id.searchLayout)

        wbNoScan.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        countryType.setOnClickListener(this)
        ieFlag.setOnClickListener(this)

        countryType.text = "国内"
        countryTypeCode = gnStatus
        ieFlag.text = "进港"
        ieFlagCode = importStatus

        ///////////////    下拉框   start
        countryTypeList.clear()
        val countryType1 = JSONObject()
        countryType1["name"] = "国内"
        countryType1["code"] = gnStatus
        val countryType2 = JSONObject()
        countryType2["name"] = "国际"
        countryType2["code"] = gjStatus
        countryTypeList.add(countryType1)
        countryTypeList.add(countryType2)

        ieFlagList.clear()
        val ieFlag1 = JSONObject()
        ieFlag1["name"] = "进港"
        ieFlag1["code"] = importStatus
        val ieFlag2 = JSONObject()
        ieFlag2["name"] = "出港"
        ieFlag2["code"] = exportStatus
        ieFlagList.add(ieFlag1)
        ieFlagList.add(ieFlag2)
        ///////////////    下拉框   end
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_cargo_tracking)
        setBackArrow("货物状态查询")
        initView()

        //搜索查询
        viewModel.searchParamLive.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                val dataObject = it.getJSONObject("data")

                val countryType = dataObject.getString("countryType") ?: ""
                val ieFlag = dataObject.getString("ieFlag") ?: ""
                val status = dataObject.getString("status") ?: ""
                val businessType = dataObject.getString("businessType") ?: ""

                //赋值循环
                collectList.clear()
                collectList2.clear()
                val checkCargoList = getCheckCargoList(countryType, ieFlag, status, businessType)
                if (checkCargoList.size > 7) {
                    collectList.addAll(checkCargoList.subList(0, 7))
                    adapter.notifyDataSetChanged()

                    val subList2 = checkCargoList.subList(7, checkCargoList.size)
                    var limitNum = 7 - subList2.size
                    while (limitNum > 0) {
                        subList2.add(CargoTrackingList(""))
                        --limitNum
                    }
                    collectList2.addAll(checkCargoList.subList(7, checkCargoList.size))
                    adapter2.notifyDataSetChanged()
                } else {
                    collectList.addAll(checkCargoList)
                    adapter.notifyDataSetChanged()
                }
            }
        }

        //国内际、进出港运单流程图   ->   路由带值过来，主动查询
        if (countryTypeParam != null && ieFlagParam != null && wbNoParam != null) {
            ieFlagList.forEach { obj ->
                val temp = obj as JSONObject
                val code = temp.getString("code")
                if (ieFlagParam == code) {
                    val name = temp.getString("name")
                    ieFlag.text = name
                    ieFlagCode = code
                }
            }
            countryTypeList.forEach { obj ->
                val temp = obj as JSONObject
                val code = temp.getString("code")
                if (countryTypeParam == code) {
                    val name = temp.getString("name")
                    countryType.text = name
                    countryTypeCode = code
                }
            }
            wbNo.setText(wbNoParam)
            searchFun()
        }
    }

    /**
     * onActivityResult 回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 扫描二维码/条码回传
        if (requestCode == Constant.RequestCode.cargo_query_wbno_scan && resultCode == RESULT_OK) {
            if (data != null) {
                val content =
                    data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
                wbNo.setText(content)
            }
        }
    }

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

                R.id.countryType -> {
                    Common.singleSelect(
                        this,
                        "地区类型",
                        countryTypeList,
                        countryTypeCode
                    ) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        countryType.text = name
                        countryTypeCode = code
                    }
                }

                R.id.ieFlag -> {
                    Common.singleSelect(this, "进出港", ieFlagList, ieFlagCode) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        ieFlag.text = name
                        ieFlagCode = code
                    }
                }

                R.id.searchLayout -> {
                    searchFun()
                }

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

    /**
     * 搜索
     */
    private fun searchFun() {
        viewModel.search(
            countryTypeCode,
            ieFlagCode,
            wbNo.text.toString()
        )
    }

    /**
     * 获取货物流程列表  未选中
     *
     * countryType 地区类型  国内、国际
     *
     * ieFlag 进出港
     */
    private fun getCargosStatus(
        countryType: String,
        ieFlag: String,
        status: Int,
        businessType: String,
    ): ArrayList<CargoTrackingList> {
        val cargoStatusList = arrayListOf<CargoTrackingList>()
        val isMail = businessType == "YJE"//是否是邮件
        /**
         * 1.国内出港
         */
        if (gnStatus == countryType && exportStatus == ieFlag) {
            //tw备注2022年7月12日14:16:13：为什么要这么写。是因为原先需要，状态选中的字和未选中的字是不一样的。后来需要改为都一样，偷懒就没修改结构了。变成下面这样，有的判断，有的没加判断。但展示的都一样
            cargoStatusList.add(CargoTrackingList("数据录入", 1))
            cargoStatusList.add(CargoTrackingList("收运", 2))
            cargoStatusList.add(CargoTrackingList("制单", 3))
            cargoStatusList.add(CargoTrackingList("复磅", 4))
            cargoStatusList.add(CargoTrackingList("配载", 5))
            cargoStatusList.add(CargoTrackingList("截载", 6))
            cargoStatusList.add(CargoTrackingList("航班关闭", 7))
        }
        /**
         * 2.国内进港
         */
        else if (gnStatus == countryType && importStatus == ieFlag) {
            cargoStatusList.add(CargoTrackingList("舱单录入", 1))
            cargoStatusList.add(CargoTrackingList("发放", 2))
            cargoStatusList.add(CargoTrackingList("提取", 3))
            cargoStatusList.add(CargoTrackingList("出库", 4))
        }
        /**
         * 3.国际出港
         */
        else if (gjStatus == countryType && exportStatus == ieFlag) {
            cargoStatusList.add(CargoTrackingList("数据录入", 1))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("预配放行", 2))
            cargoStatusList.add(CargoTrackingList("收运", 3))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("运抵放行", 4))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("海关放行", 5))
            cargoStatusList.add(CargoTrackingList("板箱组装", 6))
            cargoStatusList.add(CargoTrackingList("板箱过磅", 7))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("装载放行", 8))

            cargoStatusList.add(CargoTrackingList("出库", 9))
            cargoStatusList.add(CargoTrackingList("关闭航班", 10))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("理货放行", 11))
        }
        /**
         * 4.国际进港
         */
        else if (gjStatus == countryType && importStatus == ieFlag) {
            cargoStatusList.add(CargoTrackingList("舱单录入", 1))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("原始舱单放行", 2))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("理货放行", 3))
            if (!isMail)
                cargoStatusList.add(CargoTrackingList("海关放行", 4))
            cargoStatusList.add(CargoTrackingList("出库", 5))
        }
        cargoStatusList.forEach {
            it.setStatusForCurrent(status)
        }
        return cargoStatusList
    }


    /**
     * 获取对应状态的货物流程图
     */
    private fun getCheckCargoList(
        countryType: String,
        ieFlag: String,
        status: String,
        businessType: String,
    ): ArrayList<CargoTrackingList> {
        val resultList = ArrayList<CargoTrackingList>()
        if (status.isValidInt()) {
            val num = status.toInt()
            if (num > 0) {
                val cargoList = getCargosStatus(countryType, ieFlag, num, businessType)
                resultList.addAll(cargoList)
            }
        }
        return resultList
    }

}