package com.dahe.gldriver.ui.account.authperson

import android.os.Bundle
import com.dahe.gldriver.R
import com.dahe.gldriver.base.AppConfig
import com.dahe.gldriver.bean.DiCarColor
import com.dahe.gldriver.bean.UpDrivingInfoBean
import com.dahe.gldriver.databinding.ActivityAuthDrivingBinding
import com.dahe.gldriver.net.BaseObserver
import com.dahe.gldriver.net.DataManager
import com.dahe.gldriver.net.RxHttpCallBack
import com.dahe.gldriver.ui.account.AuthSuccActivity
import com.dahe.gldriver.utils.DicUtils
import com.dahe.gldriver.utils.OcrUtils
import com.dahe.mylibrary.base.BaseActivity
import com.dahe.mylibrary.net.CommonResponseBean
import com.dahe.mylibrary.utils.ActivityUtils
import com.dahe.mylibrary.utils.ImageLoader
import com.dahe.mylibrary.utils.PickerUtils
import com.dahe.mylibrary.utils.TimeUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers

/**
 * @ClassName AuthRoleActivity
 * @Author 用户
 * @Date 2024/1/25 11:15
 * @Description 行驶证认证
 */
class AuthDrivingActivity : BaseActivity<ActivityAuthDrivingBinding>() {


    var upDrivingInfoBean = UpDrivingInfoBean()
    override fun initView(savedInstanceState: Bundle?) {
        setStatusBarColor(R.color.white)
        setTitleBar("实名认证", true)
        binding.btnOk.setOnClickListener {
            subMit()
        }
        binding.run {
            ivFront.setOnClickListener {
                selFrontPic()
            }

            ivBack.setOnClickListener {
                selBackPic()
            }
            ivRoadFront.setOnClickListener {
                OcrUtils.getInstance()
                    .noOcrUpPic(mContext, this@AuthDrivingActivity) { picPath, ocrResult ->
                        ImageLoader.getInstance()
                            .loadRoundImage(mContext, picPath.locPic, 12, ivRoadFront)
                        upDrivingInfoBean.roadLicensePhotoUrl = picPath.picPath
                    }
            }
            ivCar.setOnClickListener {
                OcrUtils.getInstance()
                    .noOcrUpPic(mContext, this@AuthDrivingActivity) { picPath, ocrResult ->
                        ImageLoader.getInstance()
                            .loadRoundImage(mContext, picPath.locPic, 12, ivCar)
                        upDrivingInfoBean.carUrl = picPath.picPath
                    }
            }

            tvDate.setOnClickListener {
                PickerUtils.getInstance().showDateSim(this@AuthDrivingActivity) {
                    tvDate.text = it
                }
            }
            //车辆类型
            tvCarType.setOnClickListener {
                //车辆类型
                DicUtils.getInstance()
                    .selectDicCarType(mContext, this@AuthDrivingActivity, isLoading = true) { position, item ->
                        var data = item as DiCarColor
                        tvCarType.text = data.dictLabel
                        upDrivingInfoBean.run {
                            vehicleTypeCode = data.dictValue
                            vehicleType = data.dictLabel
                        }
                    }
            }
            tvEnd.setOnClickListener {
                PickerUtils.getInstance().showDateSim(this@AuthDrivingActivity) {
                    tvEnd.text = it
                }
            }



            tvCarColor.setOnClickListener {
                DicUtils.getInstance()
                    .getCarColor(mContext, this@AuthDrivingActivity) { position, item ->
                        var data = item as DiCarColor
                        tvCarColor.text = data.dictLabel
                        upDrivingInfoBean.run {
                            plateColorCode = data.dictValue
                            plateColor = data.dictLabel
                        }
                    }
            }
        }
    }

    override fun initDate() {
    }

    /**
     * 行驶证正面
     */
    private fun selFrontPic() {
        OcrUtils.getInstance().ocrDriveing(mContext, this) { picPath, result ->
            ImageLoader.getInstance()
                .loadRoundImage(mContext, picPath.locPic, 12, binding.ivFront)
            upDrivingInfoBean.licenseFaceUrl = picPath.picPath//行驶证照片（正面）
            result?.data?.face?.data?.let {
                var isHasFow = it.vehicleType.contains("牵引车")
                upDrivingInfoBean.isTrailer = if (isHasFow) "1" else "0"//是否有挂车(0否 1是)


                //识别车辆类型后，调用接口匹配code值！！！？？？
                DicUtils.getInstance()
                    .getCarTypeByValue(mContext, it.vehicleType) { position, item ->
                        if (item != null) {
                            var data = item as DiCarColor
                            upDrivingInfoBean.run {
                                vehicleTypeCode = data.dictValue
                                vehicleType = data.dictLabel
                            }
                            binding.tvCarType.text = data.dictLabel
                        }
                    }

                binding.run {
                    etCarNum.setText(it.licensePlateNumber)
                    etOwner.setText(it.owner)
                    etUseNature.setText(it.useNature)
                    etCurbWeight.setText(it.curbWeight)
                    etPermittedWeight.setText(it.permittedWeight)
                }
            }
        }
    }

    private fun selBackPic() {

        OcrUtils.getInstance().ocrDriveing(mContext, this) { picPath, result ->
            ImageLoader.getInstance()
                .loadRoundImage(mContext, picPath.locPic, 12, binding.ivBack)
            upDrivingInfoBean.licenseBackUrl = picPath.picPath//行驶证照片（反面）

            result?.data?.back?.data?.let {
                if (it.inspectionRecord.length > 13) {
                    val changeDateNoneFormat = TimeUtil.changeDateNoneFormat(
                        it.inspectionRecord.substring(6, 14),
                        "yyyy年MM月"
                    )
                    if (!changeDateNoneFormat.isNullOrEmpty()) {
                        upDrivingInfoBean.licenseValidity = changeDateNoneFormat//行驶证到期时间
                        binding.tvEnd.text = changeDateNoneFormat
                    }
                }
                //车长
                val split = it.overallDimension.split("mm")[0].split("X")
                if (split!=null&&split.size>2){
                    upDrivingInfoBean.run {
                        carLong = split[0]
                        carWidth = split[1]
                        carHeight = split[2]
                    }
                }
                upDrivingInfoBean.tractionWeight = it.tractionWeight
                upDrivingInfoBean.energySignCode = it.energySign
                binding.run {
                    etCurbWeight.setText(it.curbWeight)//整备质量
                    etPermittedWeight.setText(it.permittedWeight)//核定载质量
                }
            }
        }


//        PopsUtils.getInstance().showSimSelPic(mContext) {
//            var data = it[0]
//            ossServiceUtil.asyncPutImage(data.realPath, this@AuthDrivingActivity)
//            ossServiceUtil.setResultCallBack { data, oldPath ->
//                run {
//                    DataManager.getInstance().recognizeVehicleLicense(oldPath)
//                        .subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(
//                            BaseObserver(mContext,
//                                object : RxHttpCallBack<OcrPersonBean>() {
//                                    override fun onSuccess(t: CommonResponseBean<OcrPersonBean>) {
//                                        super.onSuccess(t)
////                                        t.data.data.back?.data.let {
////                                            driverInfoBean.licensePhotoBackUrl = oldPath
////                                        }
//                                    }
//                                })
//                        )
//
//                }
//            }
//
//
//            ImageLoader.getInstance().loadRoundImage(mContext, data.realPath, 12, binding.ivBack)
//        }
    }

    private fun subMit() {
        binding.run {
            if (etCarNum.text.isNullOrEmpty() ||
                tvCarType.text.isNullOrEmpty() ||
                tvEnd.text.isNullOrEmpty() ||
                tvCarColor.text.isNullOrEmpty()
            ) {
                showToast("请完善车辆信息")
                return@subMit
            }
        }

        upDrivingInfoBean.run {
            roadLicenseValidity = binding.tvDate.text.toString()//道路有效期
            licenseValidity = binding.tvEnd.text.toString()//行驶证有效期
            roadLicense = binding.etID.text.toString()//道路运输许可证号
            vehicleNum = binding.etCarNum.text.trim().toString()
            vehicleType = binding.tvCarType.text.trim().toString()
            plateColor = binding.tvCarColor.text.trim().toString()
        }

        DataManager.getInstance().addCar(upDrivingInfoBean)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<UpDrivingInfoBean>() {
                override fun onSuccess(t: CommonResponseBean<UpDrivingInfoBean>) {
                    super.onSuccess(t)
                    if (upDrivingInfoBean.isTrailer == "1") {
                        finish()
                        ActivityUtils.startActivity(mContext, AuthTrailerActivity::class.java,Bundle().apply {
                            putString(AppConfig.CAR_ID,t.data.carId)
                        })
                    } else {
                        ActivityUtils.startActivity(mContext, AuthSuccActivity::class.java)
                    }
                }
            }))
    }


    /**
     * 根据车牌号查询车辆信任
     * @param carNum String
     */
    private fun getCarInfoByCarNum(carNum: String) {
        DataManager.getInstance().getCarByCarVehicleNum(carNum)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<UpDrivingInfoBean>() {
                override fun onSuccess(t: CommonResponseBean<UpDrivingInfoBean>) {
                    super.onSuccess(t)
                    t.data.let {
                        binding.run {
                            ImageLoader.getInstance()
                                .loadRoundImage(mContext, it.licenseFaceUrl, 12, ivFront)
                            ImageLoader.getInstance()
                                .loadRoundImage(mContext, it.licenseBackUrl, 12, ivBack)
                            ImageLoader.getInstance()
                                .loadRoundImage(mContext, it.carUrl, 12, ivCar)
                            ImageLoader.getInstance()
                                .loadRoundImage(mContext, it.roadLicensePhotoUrl, 12, ivRoadFront)

                            etCarNum.setText(it.vehicleNum)
                            etOwner.setText(it.owner)
                            tvCarType.text = it.vehicleType
                            etUseNature.setText(it.useNature)
                            etID.setText(it.roadLicense)
                            tvDate.text = it.roadLicenseValidity
                        }
                    }

                }
            }))
    }


}