package com.lukouguoji.mit.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.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.load.engine.Resource
import com.lukouguoji.mit.R
import com.lukouguoji.mit.viewModel.OutLoadingViewModel
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.CPResourceUtil
import com.lukouguoji.module_base.util.Common
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*


@Route(path = ARouterConstants.ACTIVITY_URL_MONITOR_OUT_LOADING)
class OutLoadingActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: OutLoadingViewModel

    private val calendar = Calendar.getInstance()
    private val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
    private val ymdHmsSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//年月日 时分秒


    //搜索
    private lateinit var fdate: TextView
    private lateinit var startDateIcon: ImageView
    private lateinit var fno: EditText
    private lateinit var dest: EditText
    private lateinit var countryName: EditText
    private lateinit var searchLayout: LinearLayout

    private lateinit var formTitle: TextView
    private lateinit var submit: TextView
    private lateinit var operatorLayout: LinearLayout

    //表单
    private lateinit var fnoValue: TextView
    private lateinit var jiXingValue: TextView
    private lateinit var jiHaoValue: TextView
    private lateinit var jiWeiValue: TextView
    private lateinit var zhiDanDateValue: TextView

    private lateinit var h1Dest: TextView
    private lateinit var h1C: TextView
    private lateinit var h1M: TextView
    private lateinit var h1B: TextView
    private lateinit var h1Content: TextView

    private lateinit var h2Dest: TextView
    private lateinit var h2C: TextView
    private lateinit var h2M: TextView
    private lateinit var h2B: TextView
    private lateinit var h2Content: TextView

    private lateinit var h3Dest: TextView
    private lateinit var h3C: TextView
    private lateinit var h3M: TextView
    private lateinit var h3B: TextView
    private lateinit var h3Content: TextView

    private lateinit var h4Dest: TextView
    private lateinit var h4C: TextView
    private lateinit var h4M: TextView
    private lateinit var h4B: TextView
    private lateinit var h4Content: TextView

    private lateinit var h5Dest: TextView
    private lateinit var h5C: TextView
    private lateinit var h5M: TextView
    private lateinit var h5B: TextView
    private lateinit var h5Content: TextView

    private lateinit var totalNum: TextView
    private lateinit var pekNum: TextView
    private lateinit var totalPc: TextView
    private lateinit var totalWeight: TextView

    private lateinit var matchPerson: TextView
    private lateinit var balancePerson: TextView
    private lateinit var fuBangPerson: TextView
    private lateinit var driver: TextView
    private lateinit var monitorLoadUnload: TextView


    private fun initView() {
        viewModel = ViewModelProvider(this).get(OutLoadingViewModel::class.java)

        fdate = findViewById(R.id.fdate)
        startDateIcon = findViewById(R.id.startDateIcon)
        fno = findViewById(R.id.fno)
        dest = findViewById(R.id.dest)
        countryName = findViewById(R.id.countryName)
        searchLayout = findViewById(R.id.searchLayout)
        formTitle = findViewById(R.id.formTitle)
        submit = findViewById(R.id.submit)
        operatorLayout = findViewById(R.id.operatorLayout)

        //表单
        fnoValue = findViewById(R.id.fnoValue)
        jiXingValue = findViewById(R.id.jiXingValue)
        jiHaoValue = findViewById(R.id.jiHaoValue)
        jiWeiValue = findViewById(R.id.jiWeiValue)
        zhiDanDateValue = findViewById(R.id.zhiDanDateValue)
        h1Dest = findViewById(R.id.h1Dest)
        h1C = findViewById(R.id.h1C)
        h1M = findViewById(R.id.h1M)
        h1B = findViewById(R.id.h1B)
        h1Content = findViewById(R.id.h1Content)
        h2Dest = findViewById(R.id.h2Dest)
        h2C = findViewById(R.id.h2C)
        h2M = findViewById(R.id.h2M)
        h2B = findViewById(R.id.h2B)
        h2Content = findViewById(R.id.h2Content)
        h3Dest = findViewById(R.id.h3Dest)
        h3C = findViewById(R.id.h3C)
        h3M = findViewById(R.id.h3M)
        h3B = findViewById(R.id.h3B)
        h3Content = findViewById(R.id.h3Content)
        h4Dest = findViewById(R.id.h4Dest)
        h4C = findViewById(R.id.h4C)
        h4M = findViewById(R.id.h4M)
        h4B = findViewById(R.id.h4B)
        h4Content = findViewById(R.id.h4Content)
        h5Dest = findViewById(R.id.h5Dest)
        h5C = findViewById(R.id.h5C)
        h5M = findViewById(R.id.h5M)
        h5B = findViewById(R.id.h5B)
        h5Content = findViewById(R.id.h5Content)
        totalNum = findViewById(R.id.totalNum)
        pekNum = findViewById(R.id.pekNum)
        totalPc = findViewById(R.id.totalPc)
        totalWeight = findViewById(R.id.totalWeight)
        matchPerson = findViewById(R.id.matchPerson)
        balancePerson = findViewById(R.id.balancePerson)
        fuBangPerson = findViewById(R.id.fuBangPerson)
        driver = findViewById(R.id.driver)
        monitorLoadUnload = findViewById(R.id.monitorLoadUnload)

        fdate.setOnClickListener(this)
        startDateIcon.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        submit.setOnClickListener(this)

        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)
                    }
                }
            }
        })

        fdate.text = ymdSdf.format(Date())//tw2022年6月13日15:57:10 要求航班日期默认当天
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_out_loading)
        setBackArrow("出港装机")
        initView()

        //查询返回结果
        viewModel.searchParamLive.observe(this) {
            loadingCancel()
            //todo 1.获取数据
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                val dataObj = it.getJSONObject("data")
                val headObj = dataObj.getJSONObject("head")
                val bodyObj = dataObj.getJSONObject("body")
                val totalObj = dataObj.getJSONObject("total")
                viewModel.cars = ""
                dataObj.getJSONArray("cars").forEach { c ->
                    viewModel.cars += "$c,"
                }
                if (viewModel.cars.isNotEmpty()) {
                    viewModel.cars = viewModel.cars.substring(0, viewModel.cars.length - 1)
                }

                //1.head
                fnoValue.text = headObj.getString("fno") ?: ""
                jiXingValue.text = headObj.getString("aircraftCode") ?: ""
                jiWeiValue.text = headObj.getString("standId") ?: ""
                jiHaoValue.text = headObj.getString("airNum") ?: ""
                zhiDanDateValue.text = headObj.getString("opDate") ?: ""

                //2.body
                for (index in 1..5) {
                    val tempObj = bodyObj.getJSONObject("${index}HD")

                    val destRid = CPResourceUtil.getId(this, "h${index}Dest")
                    val tempDest = findViewById<TextView>(destRid)
                    val cRid = CPResourceUtil.getId(this, "h${index}C")
                    val tempC = findViewById<TextView>(cRid)
                    val mRid = CPResourceUtil.getId(this, "h${index}M")
                    val tempM = findViewById<TextView>(mRid)
                    val bRid = CPResourceUtil.getId(this, "h${index}B")
                    val tempB = findViewById<TextView>(bRid)
                    val contentRid = CPResourceUtil.getId(this, "h${index}Content")
                    val tempContent = findViewById<TextView>(contentRid)

                    tempDest.text = tempObj.getString("dest") ?: ""
                    tempC.text = tempObj.getString("c") ?: ""
                    tempM.text = tempObj.getString("m") ?: ""
                    tempB.text = tempObj.getString("b") ?: ""
                    var tempContentValue = ""
                    tempObj.getJSONArray("remark").forEach { r ->
                        tempContentValue = tempContentValue + r + "\n"
                    }
                    tempContent.text = tempContentValue
                }

                //3.totalObj
                totalPc.text = totalObj.getIntValue("pc").toString()
                totalNum.text = totalObj.getIntValue("count").toString()
                totalWeight.text = totalObj.getIntValue("weight").toString()
                var pekNumvlue = ""
                totalObj.getJSONObject("group").keys .forEach { r->
                    pekNumvlue = pekNumvlue + r+":"+totalObj.getJSONObject("group").getIntValue(r).toString()+ "车,"
                }
                pekNum.text = pekNumvlue //totalObj.getJSONObject("group").getIntValue("PEK").toString()

            }
        }

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

                when (viewModel.countryType) {
                    "0" -> {
                        formTitle.text = "国内出港货邮预装单"
                        operatorLayout.visibility = View.VISIBLE
                    }
                    "1" -> {
                        formTitle.text = "国际出港货邮预装单"
                        operatorLayout.visibility = View.GONE
                    }
                }

                countryName.setText(viewModel.countryName)
                dest.setText(viewModel.fdest)

                resetSearch()
            } else {
                //无数据
            }
        }

        //收获 返回结果
        viewModel.provideGjjCangDanObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status) {
                val data = it.getString("data")
                if (Constant.Result.succ == data) {
                    if (msg != null && msg != "") {
                        Common.showToast(this, msg)
                    } else {
                        Common.showToast(this, "货物发放成功！")
                    }
                    resetSearch()
                } else {
                    if (msg != null && msg != "") {
                        Common.showToast(this, msg)
                    } else {
                        Common.showToast(this, "货物发放失败！")
                    }
                }
            } else {
                if (msg != null && msg != "") {
                    Common.showToast(this, msg)
                } else {
                    Common.showToast(this, "货物发放失败！")
                }
            }
            //重新搜索
            resetSearch()
        }

    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.fdate -> {
                    Common.onYearMonthDay(this, fdate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        fdate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.startDateIcon -> {
                    fdate.text = ""
                }
                R.id.searchLayout -> {
                    countryName.setText("")
                    dest.setText("")

                    viewModel.countryType = ""
                    viewModel.countryName = ""
                    viewModel.fdest = ""

                    doFlight()
                }
                R.id.submit -> {
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_MONITOR_OUT_LOADING_PULL).withInt("fidParam", viewModel.fid ?: -9999)
                        .withString("fnoParam", viewModel.fno ?: "").withString("fdateParam", viewModel.fdate ?: "")
                        .withString("carsParam", viewModel.cars)
                        .navigation()
                }
                else -> {
                    Toast.makeText(this, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

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


    /**
     * 搜索
     */
    private fun searchFun() {
        /*if (fdate.text.toString() == "" || fno.text.toString() == "") {
            Common.showToast(this, "航班日期和航班号不可为空！")
            return
        }*/
        loading()
        viewModel.search(
            fdate.text.toString(),
            fno.text.toString()
        )
    }

    /**
     * 重置数据，搜索
     */
    private fun resetSearch() {
        searchFun()
    }

    /**
     * 查询航班是否存在
     */
    private fun doFlight() {
        if (fdate.text.toString() == "" || fno.text.toString() == "") {
            Common.showToast(this, "航班日期和航班号不可为空！")
            return
        }
        loading()
        viewModel.queryFlight(fdate.text.toString(), fno.text.toString(),getString(R.string.airport))
    }

}