package com.doverfuelingsolutions.issp.view.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import com.doverfuelingsolutions.issp.R
import com.doverfuelingsolutions.issp.api.SystemApi
import com.doverfuelingsolutions.issp.api.FuelInfoApi
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.doverfuelingsolutions.issp.utils.thread.ThreadUtil
import com.doverfuelingsolutions.issp.utils.log.DFSLog
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 kotlinx.coroutines.launch
import java.math.BigDecimal

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

    companion object {
        fun build(dc: DeviceClass) = FragmentPayType(dc)
    }

    private lateinit var binding: FragmentPayTypeBinding

    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
            setToolBar(binding.fragmentToolbar)
        }
        return binding.root
    }

    override fun onClick(v: View?) {
        when (v) {
            binding.payTypeScanCode -> {
                prepareBeforePay()
            }
            binding.payTypeAliFace -> { prepareBeforePay() }
        }
    }

    private fun prepareBeforePay() {
        loading(R.string.in_process_order)
        lifecycleScope.launch {
            val resultAccumulationInfo = FuelInfoApi.accumulationInfo(dc)
            if (resultAccumulationInfo.success && resultAccumulationInfo.data != null) {
                dc.amountTotalizer = BigDecimal(resultAccumulationInfo.data.AmountTotalizer)
                dc.volumeTotalizer = BigDecimal(resultAccumulationInfo.data.VolumeTotalizer)
                dc.saleEndTime = resultAccumulationInfo.data.SaleEndTime
            } else {
                hideLoading()
                DFSToastUtil.fail(R.string.fail_get_accumulation)
                return@launch
            }

            // 获取云订单（本地需要缓存，避免重复生成订单）
            var posTrx: PosTrx? = SPUtil.findWayneOrder(dc)
            if (posTrx == null) {
                val resultReportPayment = SystemApi.generateOrder(dc)
                if (resultReportPayment.success && resultReportPayment.data != null && !resultReportPayment.data.id.isNullOrEmpty()) {
                    posTrx = resultReportPayment.data
                    SPUtil.addWayneOrder(dc, posTrx)
                } else {
                    hideLoading()
                    DFSToastUtil.fail(StringUtil.get(R.string.fail_behave_reason, StringUtil.get(R.string.make_cloud_order), resultReportPayment.message))
                }
            }
            // 删除过期云订单
            ThreadUtil.io { SPUtil.removeExpiredWayneOrder() }

            // 锁定订单
            val resultLock = FusionManager.lockOrder(dc, true)
            hideLoading()
            if (resultLock.success) {
                dc.state = "Locked"
                SPUtil.addLockOrder(dc)
                (activity as MainActivity).setFragment(FragmentPayScanCode.build(dc, posTrx!!), true)
            } else {
                DFSToastUtil.fail(StringUtil.get(R.string.fail_behave_reason, StringUtil.get(R.string.lock_order), resultLock.message))
                DFSLog.e(resultLock)
            }
        }
    }
}