package com.miya.fastcashier.repository

import android.text.TextUtils
import android.util.Log
import androidx.annotation.WorkerThread
import com.blankj.utilcode.util.LogUtils
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.utils.DateUtils
import com.sdy.miya.moblie.component.pay.core.constance.AppTagConstance
import com.sdy.miya.moblie.component.pay.core.result.MiYaMobilePayResult
import com.sdy.miya.moblie.component.pay.core.result.ResultBuilder
import com.sdy.miya.moblie.component.pay.platform.MiYaPlatformPayService
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse
import com.sdy.miya.moblie.component.pay.platform.bean.QueryTradesByTimeResponse
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*

/**
 * 提供支付、退款的功能
 */
object PayRepository {

    /**
     * 支付功能
     */
    @WorkerThread
    fun pay(orderNo: String, payPrice: String, token: String, payType: String): PayServiceResponse {

        val shopInfo = AccountService.getAccountInfo()?.shopInfo

        val baseUrl = shopInfo?.miyaPayPlatformUrl;
        val signKey = shopInfo?.miyaPayPlatformSignKey
        val saasid = shopInfo?.saasid
        val marketid = shopInfo?.storeId
        val posId = shopInfo?.posId
        val cashierCode = shopInfo?.operatorId
        val version = "1.5"

        checkNotNull(baseUrl) { "startPay baseUrl is null" }
        checkNotNull(payPrice) { "startPay payPrice is null" }
        checkNotNull(payType) { "startPay payType is null" }
        checkNotNull(signKey) { "startPay signKey is null" }
        checkNotNull(saasid) { "startPay saasid is null" }
        checkNotNull(marketid) { " startPay marketid is null" }
        checkNotNull(posId) { " startPay posId is null" }
        checkNotNull(cashierCode) { " startPay cashierCode is null" }
        checkNotNull(version) { " startPay version is null" }
        checkNotNull(orderNo) { " startPay oderNo is null" }

        val paramsMap: MutableMap<String, Any?> = HashMap(14, 1.0f)
        paramsMap["baseUrl"] = baseUrl
        paramsMap["signKey"] = signKey
        paramsMap["saasId"] = saasid
        paramsMap["marketId"] = marketid
        paramsMap["posId"] = posId
        paramsMap["cashierCode"] = cashierCode
        paramsMap["version"] = version
        paramsMap["token"] = token
        paramsMap["payPrice"] = payPrice
        paramsMap["payType"] = payType
        paramsMap["orderNo"] = orderNo
        paramsMap["appTag"] = AppTagConstance.QINGTING_TYPE
        paramsMap["needRetryWhenNetworkError"] = true

        try {
            //发起付款
            val miYaMobilePayResult =
                MiYaPlatformPayService.getService().syncStartMiYaPay(paramsMap)
            if (miYaMobilePayResult != null && miYaMobilePayResult.resultCode == ResultBuilder.SUCCESS) {
                return miYaMobilePayResult.payServiceResponse
            } else {
                throw RuntimeException(miYaMobilePayResult!!.errorMsg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException(e.message)
        }
    }

    /**
     * 退款功能
     */
    fun refundByOrderNo(params: Map<String, String>): PayServiceResponse {

        val shopInfo = AccountService.getAccountInfo()?.shopInfo

        val baseUrl = shopInfo?.miyaPayPlatformUrl;
        val signKey = shopInfo?.miyaPayPlatformSignKey
        val saasid = shopInfo?.saasid
        val marketid = shopInfo?.storeId
        val posId = shopInfo?.posId
        val cashierCode = shopInfo?.operatorId
        val version = "1.5"
        val oriOrderNo = params["oriOrderNo"]
        val refundOrderNo = params["refundOrderNo"]
        val refundPrice = params["refundPrice"]

        checkNotNull(baseUrl) { "refundByOrderNo baseUrl is null" }
        checkNotNull(signKey) { "refundByOrderNo signKey is null" }
        checkNotNull(saasid) { "refundByOrderNo saasid is null" }
        checkNotNull(marketid) { "refundByOrderNo marketid is null" }
        checkNotNull(oriOrderNo) { "refundByOrderNo oriOrderNo is null" }
        checkNotNull(refundOrderNo) { "refundByOrderNo refundOrderNo is null" }
        checkNotNull(refundPrice) { "refundByOrderNo refundPrice is null" }


        val paramsMap: MutableMap<String, Any> = HashMap(14, 1.0f)
        paramsMap["baseUrl"] = baseUrl
        paramsMap["signKey"] = signKey
        paramsMap["saasId"] = saasid
        paramsMap["marketId"] = marketid
        posId?.let {
            paramsMap["posId"] = it
        }
        cashierCode?.let {
            paramsMap["cashierCode"] = it
        }
        paramsMap["version"] = version
        paramsMap["oriOrderNo"] = oriOrderNo
        paramsMap["refundOrderNo"] = refundOrderNo
        paramsMap["refundPrice"] = refundPrice
        try {
            //发起付款
            val miYaMobilePayResult = MiYaPlatformPayService.getService()
                .syncRequestRefundOrderByOrderId(paramsMap)
            if (miYaMobilePayResult != null && miYaMobilePayResult.resultCode == ResultBuilder.SUCCESS) {
                return miYaMobilePayResult.payServiceResponse
            } else {
                throw RuntimeException(miYaMobilePayResult!!.errorMsg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException(e.message)
        }
    }

    /**
     * 只支持微信或者支付宝
     * payType 2是微信 1是支付宝
     */
    fun generatePayCode(orderNo: String, payPrice: String, payType: String): PayServiceResponse {

        val shopInfo = AccountService.getAccountInfo()?.shopInfo

        val baseUrl = shopInfo?.miyaPayPlatformUrl;
        val signKey = shopInfo?.miyaPayPlatformSignKey
        val saasid = shopInfo?.saasid
        val marketid = shopInfo?.storeId
        val posId = shopInfo?.posId
        val cashierCode = shopInfo?.operatorId
        val version = "1.5"

        checkNotNull(baseUrl) { "baseUrl is null" }
        checkNotNull(payPrice) { "payPrice is null" }
        checkNotNull(payType) { "payType is null" }
        checkNotNull(signKey) { "signKey is null" }
        checkNotNull(saasid) { "saasid is null" }
        checkNotNull(marketid) { "marketid is null" }
        checkNotNull(orderNo) { "orderNo is null" }

        val paramsMap: MutableMap<String, Any?> = HashMap(14, 1.0f)
        paramsMap["baseUrl"] = baseUrl
        paramsMap["signKey"] = signKey
        paramsMap["saasId"] = saasid
        paramsMap["marketId"] = marketid
        paramsMap["posId"] = posId
        paramsMap["cashierCode"] = cashierCode
        paramsMap["version"] = version
        paramsMap["payPrice"] = payPrice
        paramsMap["payType"] = payType
        paramsMap["orderNo"] = orderNo
        paramsMap["startTime"] = DateUtils.format18(Date())
        var date = Date()
        val calendar = Calendar.getInstance()
        calendar.time = date;
        //过期时间设置为超过2个小时即为过期
        calendar.add(Calendar.HOUR_OF_DAY, 2);
        date = calendar.time;
        paramsMap["expireTime"] = DateUtils.format18(date)

        try {
            val miYaMobilePayResult =
                MiYaPlatformPayService.getService().syncGenMiYaPayCode(paramsMap)
            if (miYaMobilePayResult != null && miYaMobilePayResult.resultCode == ResultBuilder.SUCCESS) {
                return miYaMobilePayResult.payServiceResponse
            } else {
                throw RuntimeException(miYaMobilePayResult!!.errorMsg)
            }
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException(e.message)
        }
    }

    fun payResultQuery(orderNo: String): PayServiceResponse {
        val shopInfo = AccountService.getAccountInfo()?.shopInfo

        val baseUrl = shopInfo?.miyaPayPlatformUrl;
        val signKey = shopInfo?.miyaPayPlatformSignKey
        val saasid = shopInfo?.saasid
        val marketid = shopInfo?.storeId
        val posId = shopInfo?.posId
        val cashierCode = shopInfo?.operatorId
        val version = "1.5"

        checkNotNull(baseUrl) { "baseUrl is null" }
        checkNotNull(signKey) { "signKey is null" }
        checkNotNull(saasid) { "saasid is null" }
        checkNotNull(marketid) { "marketid is null" }
//        checkNotNull(posId) { "posId is null" }
//        checkNotNull(cashierCode) { "cashierCode is null" }

        val paramsMap: MutableMap<String, Any?> = HashMap(14, 1.0f)
        paramsMap["baseUrl"] = baseUrl
        paramsMap["signKey"] = signKey
        paramsMap["saasId"] = saasid
        paramsMap["marketId"] = marketid
        paramsMap["posId"] = posId
        paramsMap["cashierCode"] = cashierCode
        paramsMap["version"] = version
        paramsMap["orderNo"] = orderNo

        try {
            val miYaMobilePayResult =
                MiYaPlatformPayService.getService().syncRequestOrderStateByOrderId(paramsMap)
            if (miYaMobilePayResult != null && miYaMobilePayResult.resultCode == ResultBuilder.SUCCESS) {
                return miYaMobilePayResult.payServiceResponse
            } else if (!TextUtils.isEmpty(miYaMobilePayResult.errorMsg)) {
                throw RuntimeException(miYaMobilePayResult.errorMsg)
            } else if (miYaMobilePayResult.payServiceResponse != null &&
                !TextUtils.isEmpty(miYaMobilePayResult.payServiceResponse.chanelErrorMsg)
            ) {
                if ("[微信]订单支付成功(有退款)".equals(miYaMobilePayResult.payServiceResponse.chanelErrorMsg)) {
                    //微信多次退款会有该提示，视为查询成功状态
                    return miYaMobilePayResult.payServiceResponse
                } else {
                    throw RuntimeException(miYaMobilePayResult.payServiceResponse.chanelErrorMsg)
                }

            } else {
                throw RuntimeException("支付异常！")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException(e.message)
        }
    }


    /**
     * 俩时间中的订单统计
     */
    fun requestOrderQueryByTime(beginDate: Date, endDate: Date): QueryTradesByTimeResponse {
        val shopInfo = AccountService.getAccountInfo()?.shopInfo

        val baseUrl = shopInfo?.miyaPayPlatformUrl
        val signKey = shopInfo?.miyaPayPlatformSignKey
        val saasid = shopInfo?.saasid
        val marketid = shopInfo?.storeId
        val userId = shopInfo?.posId
        val cashier = shopInfo?.operatorId
        val beginDateStr = DateUtils.format14(beginDate)
        val endDateStr = DateUtils.format14(endDate)
        checkNotNull(baseUrl, { "PayRepository requestOrderQueryByTime baseUrl is null" })
        checkNotNull(signKey, { "PayRepository requestOrderQueryByTime signKey is null" })
        checkNotNull(saasid, { "PayRepository requestOrderQueryByTime saasid is null" })
        checkNotNull(marketid, { "PayRepository requestOrderQueryByTime marketid is null" })
        checkNotNull(userId, { "PayRepository requestOrderQueryByTime userId is null" })
        checkNotNull(cashier, { "PayRepository requestOrderQueryByTime cashier is null" })
        checkNotNull(beginDateStr, { "PayRepository requestOrderQueryByTime beginDate is null" })
        checkNotNull(endDateStr, { "PayRepository requestOrderQueryByTime endDate is null" })
        val paramsMap: MutableMap<String, Any> = HashMap()
        paramsMap["baseUrl"] = baseUrl
        paramsMap["key"] = signKey
        paramsMap["version"] = "1"
        paramsMap["saasid"] = saasid
        paramsMap["marketid"] = marketid
        paramsMap["userid"] = userId
        paramsMap["cashier"] = cashier
        paramsMap["begin_date"] = beginDateStr
        paramsMap["end_date"] = endDateStr
        return MiYaPlatformPayService.getService().syncQueryTrades(paramsMap)
    }


}