package com.dahe.gldriver.ui.waybill.activity

import android.Manifest
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.maps.AMap
import com.amap.api.maps.model.LatLng
import com.dahe.gldriver.R
import com.dahe.gldriver.adapter.WaybillNodeAdapter
import com.dahe.gldriver.base.AppConfig
import com.dahe.gldriver.bean.OrderDetailBean
import com.dahe.gldriver.databinding.ActivityWaybillUnloadBinding
import com.dahe.gldriver.net.BaseObserver
import com.dahe.gldriver.net.DataManager
import com.dahe.gldriver.net.RxHttpCallBack
import com.dahe.gldriver.utils.GDLocationUtils
import com.dahe.gldriver.utils.LocationUtils
import com.dahe.gldriver.utils.OrderUtils
import com.dahe.mylibrary.base.BaseActivity
import com.dahe.mylibrary.net.CommonResponseBean
import com.dahe.mylibrary.recycleviewswipe.RecycleViewDivider
import com.dahe.mylibrary.utils.ActivityUtils
import com.dahe.mylibrary.utils.BaseUtils
import com.dahe.mylibrary.utils.ConvertUtils
import com.dahe.mylibrary.utils.LoadingUtils
import com.dahe.mylibrary.utils.ToastUtils
import com.permissionx.guolindev.PermissionX
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * @ClassName WaybillLoadActivity
 * @Author john
 * @Date 2024/1/29 16:52
 * @Description 运单详情-卸货
 */
class WaybillUnlLoadActivity : BaseActivity<ActivityWaybillUnloadBinding>() {

    lateinit var aMap: AMap


    var orderId: String = ""
    var waybillId: String = ""
    lateinit var orderBean: OrderDetailBean
    override fun initView(savedInstanceState: Bundle?) {
        orderId = intent.extras?.getString(AppConfig.ORDER_ID, "").toString()
        setStatusHeightParams(binding.rlTop)
        setTitleBar("运单详情",true,true,"查看单据"){
            ActivityUtils.startActivity(mContext,SeeDocActivity::class.java,Bundle().apply { putString(AppConfig.ORDER_ID,orderId) })
        }

        initRecy()
        getLocation()
        binding.run {
            mapView.onCreate(savedInstanceState)
            aMap = mapView.map.apply {
                uiSettings.run { isZoomControlsEnabled = false }
            }

            btnRight.setOnClickListener {
                ActivityUtils.startActivity(
                    mContext,
                    WaybillUpPicActivity::class.java,
                    Bundle().apply {
                        putInt(AppConfig.SUCCESS_TYPE, 2)
                        putString(AppConfig.ORDER_ID, orderId)
                        putString(AppConfig.WAYBILL_ID, orderBean.waybillId)
                    })
            }
        }
    }

    override fun initDate() {

        DataManager.getInstance().orderDetail(orderId)
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<OrderDetailBean>() {
                override fun onSuccess(t: CommonResponseBean<OrderDetailBean>) {
                    super.onSuccess(t)
                    orderBean = t.data
                    val load = orderBean.orderChildList.first { it.type == "1" }
                    var distance = ""
                    loadPos = LatLng(load.latitude.toDouble(), load.longitude.toDouble())
                    LocationUtils.getInstance().changeCamera(loadPos, aMap!!)
                    if (::gdLatLng.isInitialized) {
                        distance = LocationUtils.getInstance().getDistance(
                            gdLatLng,
                            loadPos
                        ) + "km"
                    }
                    var goods =
                        t.data.goodsList.map { """${it.goodName},${it.goodItemGrossWeight}吨,${if (it.goodCube.isNullOrEmpty()) "" else it.goodCube + "方"}""" }
                            .reduce { acc, s ->
                                """${acc}
                                |${s}""".trimMargin()
                            }
                    binding.run {
                        tvWaybillNum.text = """运单号:${orderBean.orderNum}"""
                        tvWaybillStatu.text =
                            OrderUtils.getInstance().getOrderStatu(orderBean.orderStatus)
                        tvTime.text = orderBean.receiverDeadline
                        tvComName.text = orderBean.realCompanyName//货主

                        tvCarNum.text = orderBean.waybillInfo.vehicleNum
                        tvCarLen.text =
                            """${orderBean.waybillInfo.carLong}mm/${orderBean.waybillInfo.approvedLoad}吨"""
                        tvCarType.text = orderBean.vehicleType//车辆类型

                        if (!distance.isNullOrEmpty()) tvLoadDis.text = distance
                        tvUnloadDis.text = orderBean.distance + "km"


                        tvType.text = if (orderBean.orderType == "0") "一装一卸" else "一装多卸"

                        tvCom.text = orderBean?.receiverBusinessName//收货方
                        tvFreight.text = orderBean?.driverFreight.toString()

                        tvCarInfo.text = """${t.data.vehicleLength} ${t.data.vehicleType}"""
                        tvGoods.text = goods
                        if (!t.data.requirement.isNullOrEmpty()) tvRemark.text = t.data.requirement

                        btnLeft.setOnClickListener {
                            PermissionX.init(this@WaybillUnlLoadActivity)
                                .permissions(Manifest.permission.CALL_PHONE)
                                .request { allGranted, grantedList, deniedList ->
                                    if (allGranted) {
                                        BaseUtils.callPhone(
                                            this@WaybillUnlLoadActivity,
                                            orderBean.shipperContactPhone
                                        )
                                    } else {
                                        Toast.makeText(
                                            mContext,
                                            "开启权限失败,请在应用设置-权限中打开电话权限",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                }

                        }
                    }

                    adapter?.submitList(t.data.orderChildList)
//                    initXml(t.data)
                }
            }))
    }


    var adapter: WaybillNodeAdapter? = null
    private fun initRecy() {
        adapter = binding.recycler.run {
            layoutManager = LinearLayoutManager(mContext, RecyclerView.VERTICAL, false)
            setHasFixedSize(true)
            addItemDecoration(
                RecycleViewDivider(
                    LinearLayout.VERTICAL,
                    ConvertUtils.dp2px(16.0f),
                    Color.TRANSPARENT
                )
            )
            adapter = WaybillNodeAdapter()
            adapter as WaybillNodeAdapter
        }.apply {
            setOnItemClickListener { _, _, position ->
                ActivityUtils.startActivity(
                    mContext,
                    WaybillLoadActivity::class.java,
                    Bundle().apply { putString(AppConfig.ORDER_ID, items[position].orderId) })
            }
            addOnItemChildClickListener(R.id.btnOk) { adapter, view, position ->
                ActivityUtils.startActivity(mContext, WaybillDetailActivity::class.java)
            }
        }

    }


    override fun onResume() {
        super.onResume()
        binding.mapView.onResume();
    }

    override fun onPause() {
        super.onPause()
        binding.mapView.onPause();
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.mapView.onSaveInstanceState(outState);
    }

    lateinit var gdLatLng: LatLng
    lateinit var loadPos: LatLng
    fun getLocation() {
        GDLocationUtils.instance.getLocation(mContext) {
            //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
            runOnUiThread {
                LoadingUtils.instance.dissLoading()
                if (it.getErrorCode() == 0) {
                    it.getLongitude()//经    度
                    it.getLatitude()//纬    度
                    gdLatLng = LatLng(it.latitude, it.longitude)
                    if (::loadPos.isInitialized) {
                        var distance = LocationUtils.getInstance().getDistance(
                            gdLatLng,
                            loadPos
                        ) + "km"
                        binding.tvLoadDis.text = distance
                    }

                } else {
                    showToast("定位失败,请检查定位权限是否开启")
                }
            }
        }
    }

}