package com.gingersoft.gsa.cloud.common.core.delivery

import android.util.Log
import android.view.View
import com.gingersoft.gsa.cloud.common.logan.LoganManager
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil
import java.io.Serializable
import kotlin.math.abs

class OrderDetails {

    /**
     * success : true
     * sysTime : 1585823531720
     * data : [{"Order_ID":50349,"NUMBER":1,"MEMBER_NAME":"忆逝1","PRICE":88,"discount_amount":0,"PHONE":"15728241877","ORDER_NO":"26202811401145744","Lunchbox":0,"remark":"","pid":0,"PRODUCT_NAME":[{"odsId":"1650249","PRICE":"88.0","num":"1","pid":"0","PRODUCT_NAME":"脆炸粟米蟹肉餅"}],"odsId":1650249,"addressDetail":"香港長沙灣青山道479 - 479A號麗昌工廠大廈 704 室及 802 室(接待處於 704 室蘋果迷你倉 - 荔枝角 (麗昌分店)分店","DELIVERY_CHARGE":0,"order_from":7,"sender":"","SEND_TIME":"盡快送達 18:27","PAY_AMOUNT":88,"ID":50349,"CREATE_TIME":"2020-04-02 17:57:29.0","takeFoodCode":"0","RECEIVER":"張學友 先生","TOTAL_AMOUNT":"88.0"}]
     */

    var code: String? = null
    var errorMsg: String? = null
    var success: Boolean = false
    var sysTime: Long = 0
    var data: List<DataBean>? = null

    class DataBean : Serializable {
        /**
         * Order_ID : 50349
         * NUMBER : 1
         * MEMBER_NAME : 忆逝1
         * PRICE : 88.0
         * discount_amount : 0.0
         * PHONE : 15728241877
         * ORDER_NO : 26202811401145744
         * Lunchbox : 0.0
         * remark :
         * pid : 0
         * PRODUCT_NAME : [{"odsId":"1650249","PRICE":"88.0","num":"1","pid":"0","PRODUCT_NAME":"脆炸粟米蟹肉餅"}]
         * odsId : 1650249
         * addressDetail : 香港長沙灣青山道479 - 479A號麗昌工廠大廈 704 室及 802 室(接待處於 704 室蘋果迷你倉 - 荔枝角 (麗昌分店)分店
         * DELIVERY_CHARGE : 0.0
         * order_from : 7
         * sender :
         * SEND_TIME : 盡快送達 18:27
         * PAY_AMOUNT : 88.0
         * ID : 50349
         * CREATE_TIME : 2020-04-02 17:57:29.0
         * takeFoodCode : 0
         * RECEIVER : 張學友 先生
         * TOTAL_AMOUNT : 88.0
         */
        var trkNo: String? = null
        var delivery_man_phone_num: String? = null
        var deliveryMode: String? = null
        var delivery_man_name: String? = null
        var Order_ID: Int = 0
        var NUMBER: Int = 0
        var MEMBER_NAME: String? = null
        var PRICE: Double = 0.toDouble()

        //        var discount_amount: Double = 0.toDouble()
        var takeTime: String? = null
        var PHONE: String? = null
        var memberTypeId: Int = 0
        var ORDER_NO: String? = null
        var levelName1: String? = null
        var Lunchbox: Double = 0.toDouble()
        var remark: String? = null
        var pid: Int = 0
        var odsId: Int = 0
        var addressDetail: String? = null
        var DELIVERY_CHARGE: Double = 0.toDouble()
        var order_from: Int = 0
        var sender: String? = null
        var sendMobile: String? = null
        var SEND_TIME: String? = null
        var PAY_AMOUNT: Double = 0.toDouble()
        var ID: Int = 0
        var CREATE_TIME: String? = null
        var takeFoodCode: String? = null
        var billNo: String? = null
        var RECEIVER: String? = null
        var TOTAL_AMOUNT: String? = null

        //訂單類型#1:餐廳訂單;2:線上外賣訂單3:扫码点餐;4固定二维码订单;5:预点餐;6:積分訂單;7:自取订单；8：冷鏈
        var orderType: Int = 0

        //是否是預約單  0 ：即時單  1：是預約單
        var appointmentType: Int = 0

        //會員號碼
        var memberPhone: String? = null
        var orderPayType: Int = 0//0店內支付，1為貨到付款，2是在線支付
        var isDelete: Int = 1 //默認為1，為0是第三方物流,其他則是本店配送
        var payTime: String? = null
        var payType: Int = 0//1:積分支付;2:支付寶;3:财付通;4:微信支付;5:貨到付款;6:其他支付
        var PRODUCT_NAME: List<PRODUCTNAMEBean>? = null
        var couponList: List<CouponBean>? = null

        var estimatedTime: String? = null

        var orderStatus: Int = 0

        var addPoints: Double = 0.toDouble()//本次加多少積分
        var oldPoints: Double = 0.toDouble()//之前有多少積分
        var nowPoints: Double = 0.toDouble()//現在有多少積分
        var deliveryAmount: Double = 0.toDouble()//當前運輸工具金額
        var curStat: Int = 0//訂單已創建    1

        //                    * * Order Assigned To Delivery Man - 配送員已接單  2
//                    * * Delivery Man Reached Pickup Point Nearby - 配送員已到達店鋪附近   3
//                    * * Delivery Man Reached Pickup Point - 配送员已到店  4
//                    * * Delivery In Progress - 訂單正在配送中  5
//                    * * Delivery Man Reached Destination Nearby - 配送員已到達目的地附近 6
//                    * * Order Delivered - 訂單已完成   7
//                    * * Order Cancelled Before Collection - 訂單已取消 - 取餐前    8
//                    * * Order Cancelled After Collection - 訂單已取消 - 取餐后    9
//                    * * Order Assigned To Another Delivery Man - 已指派另一位配送員    10
        var payMultiple: List<PayMultiple>? = null
        var companyType: Int = -1 //物流公司類型 0  本店配送 1:zeek;2:lalamove
        var labUrl: String? = null //打印文檔鏈接

        fun getShowTextByOrderType(): String {
            return when (orderType) {
                2 -> "外送"
                3 -> "掃碼點餐"
                8 -> "凍鏈"
                7 -> "自取"
                else -> "未知$orderType"
            }
        }

        fun getShowTextByOrderPayType(): String {
            return when (orderPayType) {
                1 -> "貨到付款"
                0 -> "店內支付"
                2 -> {
                    if (payMultiple != null) {
                        val payName = StringBuilder()
                        for (payMultiple in payMultiple!!) {
                            payName.append(payMultiple.payName)
                            payName.append(",")
                        }
                        if (payName.isNotEmpty()) {
                            payName.deleteCharAt(payName.length - 1)
                        }
                        "在線支付：$payName"
                    } else {
                        "在線支付"
                    }
                }
                else -> ""
            }
        }

        class PRODUCTNAMEBean : Serializable {
            /**
             * odsId : 1654481
             * PRICE : 760.0
             * num : 2
             * pid : 0
             * PRODUCT_NAME : Black Pepper Crab
             * child : [{"odsId":"1654482","PRICE":"0.0","num":"2","pid":"1654481","PRODUCT_NAME":"Pho"},{"odsId":"1654483","PRICE":"0.0","num":"2","pid":"1654481","PRODUCT_NAME":"rice flour"},{"odsId":"1654484","PRICE":"0.0","num":"2","pid":"1654481","PRODUCT_NAME":"Tang Meng"},{"odsId":"1654485","PRICE":"0.0","num":"2","pid":"1654481","PRODUCT_NAME":"Black Pepper Tiger Prawn"},{"odsId":"1654486","PRICE":"0.0","num":"2","pid":"1654481","PRODUCT_NAME":"Chilli Tiger Prawn"},{"odsId":"1654487","PRICE":"0.0","num":"2","pid":"1654481","PRODUCT_NAME":"Black Pepper Crab","child":[{"odsId":"1654488","PRICE":"0.0","num":"2","pid":"1654487","PRODUCT_NAME":"Pho"},{"odsId":"1654489","PRICE":"0.0","num":"2","pid":"1654487","PRODUCT_NAME":"rice flour"},{"odsId":"1654490","PRICE":"0.0","num":"2","pid":"1654487","PRODUCT_NAME":"Tang Meng"}]},{"odsId":"1654491","PRICE":"0.0","num":"2","pid":"1654481","PRODUCT_NAME":"Kam Heong Crab"}]
             */
            var odsId: String? = null
            var PRICE: String? = null
            var num: String? = null
            var pid: String? = null
            var PRODUCT_NAME: String? = null
            var child: List<ChildBeanX>? = null
            var printseting: String? = null
            var printToBill: Int = 1 //當金額=0時，是否打印在賬單上   0 否 1 是

            //0食品清单打印 账单打印
            //1食品清单不打印 账单不打印
            //2食品清单打印 账单不打印
            //3食品清单不打印 账单打印
            var printTo: Int = 0
            var lunchboxPrice: Double = 0.0

            class ChildBeanX : Serializable {
                /**
                 * odsId : 1654487
                 * PRICE : 0.0
                 * num : 2
                 * pid : 1654481
                 * PRODUCT_NAME : Pho
                 * child : [{"odsId":"1654488","PRICE":"0.0","num":"2","pid":"1654487","PRODUCT_NAME":"Pho"},{"odsId":"1654489","PRICE":"0.0","num":"2","pid":"1654487","PRODUCT_NAME":"rice flour"},{"odsId":"1654490","PRICE":"0.0","num":"2","pid":"1654487","PRODUCT_NAME":"Tang Meng"}]
                 */
                var odsId: String? = null
                var PRICE: String? = null
                var num: String? = null
                var pid: String? = null
                var PRODUCT_NAME: String? = null
                var child: List<ChildBean>? = null
                var printseting: String? = null
                var lunchboxPrice: Double = 0.0
                var printToBill: Int = 1 //當金額=0時，是否打印在賬單上   0 否 1 是

                //0食品清单打印 账单打印
                //1食品清单不打印 账单不打印
                //2食品清单打印 账单不打印
                //3食品清单不打印 账单打印
                //var printTo: Int = 0
                class ChildBean : Serializable {
                    /**
                     * odsId : 1654488
                     * PRICE : 0.0
                     * num : 2
                     * pid : 1654487
                     * PRODUCT_NAME : Pho
                     */
                    var odsId: String? = null
                    var PRICE: String? = null
                    var num: String? = null
                    var pid: String? = null
                    var PRODUCT_NAME: String? = null
                    var printseting: String? = null
                    var lunchboxPrice: Double = 0.0
                    var printToBill: Int = 1 //當金額=0時，是否打印在賬單上   0 否 1 是
                    //0食品清单打印 账单打印
                    //1食品清单不打印 账单不打印
                    //2食品清单打印 账单不打印
                    //3食品清单不打印 账单打印
//                    var printTo: Int = 0
                }
            }
        }

        data class CouponBean(val id: Int, val couponName: String, val discount_amount: Double) : Serializable

        data class PayMultiple(val payTypeId: String, val amount: Double, val payName: String, val points: Double) : Serializable
    }


    companion object {
        //支付類型
        /**
         * 店內支付
         */
        const val inStorePay: Int = 0

        /**
         * 貨到付款
         */
        const val payOnDelivery: Int = 1

        /**
         * 在線支付
         */
        const val onLinePay: Int = 2


        //訂單類型
        /**
         * 自取
         */
        const val yourselfPickUp: Int = 7

        //配送類型
        /**
         * 第三方配送
         */
        const val thirdPartyDistribution: Int = 0

        /**
         * 本店配送
         */
        const val ourStoreDelivery: Int = 1


        //配送方式
        /**
         * 本店派送
         */
        const val ourStoreDistribution: Int = 0

        /**
         * zeek配送
         */
        const val zeekDistribution: Int = 1

        /**
         * lalamove配送
         */
        const val lalamoveDistribution: Int = 2

        /**
         * 製作中
         */
        const val inProduction: Int = 2

        //訂單狀態
        /**
         * 外送：指派送貨 自取：製作完成
         */
        const val appointDelivery: Int = 3

        /**
         * 結賬
         * 外送-已在線支付：修改訂單狀態為已結賬
         */
        const val closingAmount: Int = 4

        /**
         * 預約單狀態
         */
        const val bookingOrder: Int = 8


        //允許的金額誤差
        const val allowableError = 0.01

        @JvmStatic
        val verifiAmountTip = "支付金額與總金額不符，請檢查"

        /**
         * 驗證金額是否正確
         */
        @JvmStatic
        fun verificationAmount(orderDetail: DataBean): Boolean {
            val totalAmount = orderDetail.TOTAL_AMOUNT!!.toDouble()
            //遍歷所有商品，算出所有食品金額
            var foodAmount = 0.0
            orderDetail.PRODUCT_NAME?.let { produces ->
                for (product in produces) {
                    foodAmount = MoneyUtil.sum(foodAmount, product.PRICE!!.toDouble())
                    product.child?.let { childs ->
                        for (child in childs) {
                            foodAmount = MoneyUtil.sum(foodAmount, child.PRICE!!.toDouble())
                            child.child?.let { thirds ->
                                for (third in thirds) {
                                    foodAmount = MoneyUtil.sum(foodAmount, third.PRICE!!.toDouble())
                                }
                            }
                        }
                    }
                }
            }
            //食品金額加上餐盒費，配送費，應該等於總金額
            foodAmount = MoneyUtil.sum(MoneyUtil.sum(foodAmount, orderDetail.Lunchbox), orderDetail.DELIVERY_CHARGE)
            //後台返回的總金額與計算的總金額相減，如果不等於0，則是金額有問題，攔截
            var differenceAmount = MoneyUtil.sub(MoneyUtil.sub(totalAmount, foodAmount), allowableError)
            differenceAmount = abs(differenceAmount)
            if (MoneyUtil.compareTo(differenceAmount, allowableError) == 1) {
                LoganManager.w_delivery(LoganManager.EVENT_CALCULATE, "verificationAmount食品金額：${totalAmount} + ${foodAmount}");
                return true
            }
            var payAmount = foodAmount
            //遍歷計算優惠券與折扣，用總金額減去所有折扣，如果不等於支付金額，則是有問題
            orderDetail.couponList?.let {
                for (coupon in it) {
                    payAmount = MoneyUtil.sub(payAmount, coupon.discount_amount)
                }
            }

            //計算折扣後的金額，減去支付金額，如果不為0，則是有問題
            differenceAmount = MoneyUtil.sub(MoneyUtil.sub(payAmount, orderDetail.PAY_AMOUNT), allowableError)
            differenceAmount = abs(differenceAmount)
            if (MoneyUtil.compareTo(differenceAmount, allowableError) == 1) {
                LoganManager.w_delivery(LoganManager.EVENT_CALCULATE, "verificationAmount支付金額：${payAmount} + ${orderDetail.PAY_AMOUNT}");
                return true
            }
            return false
        }
    }
}