package com.doverfuelingsolutions.issp.view.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.FuelInfoApi
import com.doverfuelingsolutions.issp.api.SystemApi
import com.doverfuelingsolutions.issp.databinding.FragmentPayTypeBinding
import com.doverfuelingsolutions.issp.fusion.FusionManager
import com.doverfuelingsolutions.issp.utils.DFSToastUtil
import com.doverfuelingsolutions.issp.utils.StringUtil
import com.wayne.www.waynelib.util.log.DFSLog
import com.doverfuelingsolutions.issp.utils.sp.SPKeys
import com.doverfuelingsolutions.issp.utils.sp.SPUtil
import com.doverfuelingsolutions.issp.view.MainActivity
import com.wayne.www.waynelib.fdc.message.DeviceClass
import com.wayne.www.waynelib.webservice.entity.PosTrx
import java.math.BigDecimal

class FragmentPayType private constructor(): FragmentBasic(), View.OnClickListener {

    companion object {
        fun build(dc: DeviceClass): FragmentPayType {
            return FragmentPayType().apply {
                arguments = bundleOf(
                    Pair("dc", dc)
                )
            }
        }
    }

    private lateinit var dc: DeviceClass

    private lateinit var binding: FragmentPayTypeBinding
    override val title = StringUtil.get(R.string.select_pay_type)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val data = arguments?.getSerializable("dc")
        if (data is DeviceClass) {
            dc = data
        } else {
            DFSToastUtil.fail("no DeviceClass")
            (requireActivity() as MainActivity).fragmentRouter.pop()
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        if (!this::binding.isInitialized) {
            binding = DataBindingUtil.inflate(inflater, R.layout.fragment_pay_type, container, false)
            binding.handler = this
        }
        return binding.root
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.payTypeScanCode -> {
                prepareBeforePay()
            }
            binding.payTypeAliFace -> {
                DFSToastUtil.fail("未配置刷脸支付功能")
            }
        }
    }

    private fun prepareBeforePay() {
        val dialog = loading(R.string.in_process_order)
        (requireActivity() as MainActivity).fragmentRouter.stopFragmentToolbarTimer()

        lifecycleScope.launchWhenStarted {
            // 累计数信息
            val resultAccumulationInfo = if (SPUtil.getBoolean(SPKeys.USE_FCC2)) {
                FuelInfoApi.accumulationInfoFromFCC2(dc)
            } else {
                FuelInfoApi.accumulationInfo(dc)
            }
            if (resultAccumulationInfo.success && resultAccumulationInfo.data != null) {
                //2022-10-8号，春洲 token：80322，出现在创建订单时枪号传成 1，这里将订单的枪号赋值为订单详情中的枪号
                dc.nozzleNo = resultAccumulationInfo.data.SiteLevelNozzleId
                dc.amountTotalizer = BigDecimal(resultAccumulationInfo.data.AmountTotalizer)
                dc.volumeTotalizer = BigDecimal(resultAccumulationInfo.data.VolumeTotalizer)
                dc.saleEndTime = resultAccumulationInfo.data.SaleEndTime
            } else {
                dialog.dismiss()
                (requireActivity() as MainActivity).fragmentRouter.resumeFragmentToolbarTimer()
                DFSToastUtil.fail(R.string.fail_get_accumulation)
                return@launchWhenStarted
            }

            // 查询油品 posItemUniqueId
            // 枪数据中有缓存 posItemUniqueId
            val nozzle = FusionManager.nozzles.find { it.physicalId == dc.nozzleNo }
            var posItemUniqueId = nozzle?.posItemUniqueId
            if (posItemUniqueId.isNullOrEmpty()) {
                val barcodeId = nozzle?.barcodeId ?: dc.productNo1.toInt()
                val resultBarcodeInfo = SystemApi.barcodeName(barcodeId)
                if (!resultBarcodeInfo.success || resultBarcodeInfo.data == null) {
                    dialog.dismiss()
                    // (requireActivity() as MainActivity).fragmentRouter.resumeFragmentToolbarTimer()
                    DFSToastUtil.fail("查询油品 posItemUniqueId 失败")
                    return@launchWhenStarted
                }
                posItemUniqueId = resultBarcodeInfo.data.Id
                DFSLog.w("barcodeId：$barcodeId")
            }

            // 获取云订单（本地需要缓存，避免重复生成订单），2025-07 ，从接口处理，不需要再缓存
//                    var posTrx: PosTrx? = SPUtil.findWayneOrder(dc)
//                    if (posTrx == null) {
//
//                    }
            var posTrx:PosTrx? = null
            val resultReportPayment = SystemApi.generateOrder(dc, posItemUniqueId)
            if (resultReportPayment.success && resultReportPayment.data != null && !resultReportPayment.data.id.isNullOrEmpty()) {
                posTrx = resultReportPayment.data
            } else {
                dialog.dismiss()
                (requireActivity() as MainActivity).fragmentRouter.resumeFragmentToolbarTimer()
                DFSToastUtil.fail(StringUtil.get(R.string.fail_behave_reason, StringUtil.get(R.string.make_cloud_order), resultReportPayment.message))
            }

            // 锁定订单
            if (posTrx == null) return@launchWhenStarted
            val resultLock = FusionManager.lockOrder(dc, true)
            dialog.dismiss()
            (requireActivity() as MainActivity).fragmentRouter.resumeFragmentToolbarTimer()
            if (resultLock.success) {
                dc.state = "Locked"
                SPUtil.addLockOrder(dc)
                (activity as MainActivity).fragmentRouter.push(FragmentPayScanCode.build(dc, posTrx))
            } else {
                DFSToastUtil.fail(StringUtil.get(R.string.fail_behave_reason, StringUtil.get(R.string.lock_order), resultLock.message))
            }
        }
    }
}