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

import android.Manifest
import android.app.usage.UsageEvents.Event
import android.graphics.Color
import android.os.Bundle
import android.widget.LinearLayout
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.amap.api.maps2d.model.LatLng
import com.dahe.gldriver.R
import com.dahe.gldriver.adapter.WaybillAdapter
import com.dahe.gldriver.adapter.WaybillNodeAdapter
import com.dahe.gldriver.base.AppConfig
import com.dahe.gldriver.bean.OrderDetailBean
import com.dahe.gldriver.databinding.ActivityWaybillDetailBinding
import com.dahe.gldriver.event.OrderStauEvent
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.glex.bean.OrderBean
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.SelectPicUtils
import com.permissionx.guolindev.PermissionX
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus

/**
 * @ClassName WaybillDetailActivity
 * @Author john
 * @Date 2024/1/26 14:50
 * @Description 运单详情-接单
 */
class WaybillDetailActivity : BaseActivity<ActivityWaybillDetailBinding>() {
    var orderId: String = ""
    lateinit var gdLatLng: LatLng
    lateinit var loadPos: LatLng
    override fun initView(savedInstanceState: Bundle?) {
        orderId = intent.extras?.getString(AppConfig.ORDER_ID, "").toString()
        initRecy()
        getLocation()

        binding.btnCall.setOnClickListener {
            BaseUtils.callPhone(this@WaybillDetailActivity, "15838201105")
        }
        binding.btnReceiving.setOnClickListener {
            DataManager.getInstance().receivingOrders(orderId, "22")
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(BaseObserver(mContext, object : RxHttpCallBack<String>() {
                    override fun onSuccess(t: CommonResponseBean<String>) {
                        super.onSuccess(t)
                        EventBus.getDefault().post(OrderStauEvent(1))
                    }
                }))

        }

    }

    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)
                    val load = t.data.orderChildList.first { it.type == "1" }
                    var distance: String = ""
                    loadPos = LatLng(load.latitude.toDouble(), load.longitude.toDouble())
                    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 {
                        tvTime.text = t.data.receiverDeadline
                        tvCom.text = t.data.receiverBusinessName
                        tvUnloadDis.text = t.data.distance+"km"
                        tvCarType.text = """${t.data.vehicleLength} ${t.data.vehicleType}"""
                        if (!t.data.requirement.isNullOrEmpty()) tvRemark.text = t.data.requirement
                        if (!distance.isNullOrEmpty()) tvLoadDis.text = distance
                        tvConsignor.text = t.data.realCompanyName
                        tvType.text = if (t.data.orderType == "0") "一装一卸" else "一装多卸"
                        tvFreight.text = t.data.driverFreight.toString()
                        tvGoods.text = goods
                        btnCall.setOnClickListener {
                            PermissionX.init(this@WaybillDetailActivity)
                                .permissions(Manifest.permission.CALL_PHONE)
                                .request { allGranted, grantedList, deniedList ->
                                    if (allGranted) {
                                        BaseUtils.callPhone(
                                            this@WaybillDetailActivity,
                                            t.data.shipperContactPhone
                                        )
                                    } else {
                                        Toast.makeText(
                                            mContext,
                                            "开启权限失败,请在应用设置-权限中打开电话权限",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    }
                                }

                        }

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


    fun getLocation() {
        GDLocationUtils.instance.getLocation(this@WaybillDetailActivity) {
            //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("定位失败,请检查定位权限是否开启")
                }
            }
        }
    }


//    private fun initXml(data: OrderDetailBean) {
//        val load = data.orderChildList.find { it.type == "1" }
//        val unLoad = data.orderChildList.find { it.type == "2" }
//
//        binding.run {
//            tvTime.text = data.receiverDeadline
//            tvType.text = if (data.orderType == "0") "一装一卸" else "一装多卸"
//            tvLoad.text = load?.address
//            tvPhone.text = """${load?.name} ${load?.phone}"""
//
//            tvUnload.text = unLoad?.address
//            tvUnloadPhone.text = """${unLoad?.name} ${unLoad?.phone}"""
//
//
//            tvCom.text = data?.receiverBusinessName
//            tvConsignor.text = data?.realCompanyName
//            tvFreight.text = data?.driverFreight.toString()
//
//
//
//
//
//            btnCall.setOnClickListener {
//
//                PermissionX.init(this@WaybillDetailActivity)
//                    .permissions(Manifest.permission.CALL_PHONE)
//                    .request { allGranted, grantedList, deniedList ->
//                        if (allGranted) {
//                            BaseUtils.callPhone(
//                                this@WaybillDetailActivity,
//                                data.shipperContactPhone
//                            )
//                        } else {
//                            Toast.makeText(
//                                mContext,
//                                "开启权限失败,请在应用设置-权限中打开电话权限",
//                                Toast.LENGTH_SHORT
//                            ).show()
//                        }
//                    }
//
//            }
//        }
//    }

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

    }
}