package com.miya.fastcashier.utils.manage

import com.miya.fastcashier.utils.DateUtils
import com.tencent.mmkv.MMKV
import java.util.*

/**
 * 类描述：订单流水记录MMKV管理
 */
class OrderRecordManageKit {
    companion object {

        private val MMKV_ID = "fastcashier_order"

        /**
         * 根据本地记录生成流水单号
         */
        fun getSerialNumber(): String {
            val today = DateUtils.format8(Date())
            val no = getOrderMMKV().getInt(today, 0).toString()
            var listNo = no
            //真实流水单号五位
            for (index in 1..(5 - no.length)) {
                listNo = "0$listNo"
            }
            return listNo;
        }

        /**
         * 自增流水序列号，真实流水号需要getSerialNumber()进行拼凑
         */
        fun setSerialNumber() {
            val today = DateUtils.format8(Date())
            var no = getOrderMMKV().getInt(today, 0);
            getOrderMMKV().putInt(DateUtils.format8(Date()), ++no)
        }

        /**
         * 根据订单号获取流水号
         */
        fun getSerialNoByOrderNo(orderNo: String): String {
            return getOrderMMKV().getString(orderNo, "00000").toString()
        }

        fun setSerialNoByOrderNo(orderNo: String, serialNo: String) {
            getOrderMMKV().putString(orderNo, serialNo)
        }

        /**
         * 清除前一天的本地订单流水记录
         */
        fun clearOrderDataYeaterday() {
            val yeaterdayRecordExist: Boolean = isYeaterdayOrderRecordExist();
            if (yeaterdayRecordExist) {
                clearByTime(getYesterdayOrderMMKV())
            }
        }

        /**
         * 清除全部订单记录
         */
        fun clearAll() {
            clearByTime(getOrderMMKV())
            clearByTime(getYesterdayOrderMMKV())
        }

        /**
         * 清除指定日期记录
         */
        fun clearByTime(mmkv: MMKV) {
            mmkv.clearAll()
        }

        /**
         * 是否存在前一天的本地订单记录
         */
        private fun isYeaterdayOrderRecordExist(): Boolean {
            val actualSize = getYesterdayOrderMMKV().actualSize()
            return actualSize > 0
        }

        private fun getOrderMMKV(): MMKV {
            val MMKV_ID_WITHDAY = MMKV_ID.plus(DateUtils.format8(Date()))
            return MMKV.mmkvWithID(MMKV_ID_WITHDAY)
        }

        private fun getYesterdayOrderMMKV(): MMKV {
            val yesteday = DateUtils.getYestedayFormat8()
            val MMKV_ID_YESTERDAY = MMKV_ID.plus(yesteday)
            return MMKV.mmkvWithID(MMKV_ID_YESTERDAY)
        }
    }
}