package com.yidianling.ydl_pay.widget

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import com.yidianling.ydl_pay.R
import com.yidianling.ydl_pay.bean.CommonCouponBean
import com.yidianling.ydl_pay.bean.OrderInfoBean
import kotlinx.android.synthetic.main.view_pay_info_detail.view.*
import java.math.BigDecimal


/**
 * @author jiucheng
 * @描述:支付详细信息view
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/4/4
 */
@SuppressLint("ViewConstructor")
class PayInfoDetailView(context: Context, var listener: OnCouponDetailClickListener) :
    LinearLayout(context) {
    private var orderInfoBean: OrderInfoBean? = null
    /**
     * 是否使用余额
     */
    private var isUseChange = true

    /**
     * 使用余额,余额是否足够
     */
    private var isBalanceSufficient = false
    //需要sdk（支付宝、微信）支付的金额
    private var sdkPayMoney = 0.00f

    /**
     * 支付方式
     * 1024.微信支付 1025.支付宝支付
     */
    private var payWay = PAY_WECHAT

    /**
     * 支付类型
     * 1余额，2三方支付，3混合
     */
    private var useMoneyType = 1

    /**
     * 可用优惠券的数量
     */
    private var availableCount: Int = 0

    companion object {
        /**
         * 支付方式
         * 1024.微信支付 1025.支付宝支付
         */
        private const val PAY_WECHAT = 1024
        private const val PAY_ALI = 1025


        /**
         * 支付类型
         * 1余额，2三方支付，3混合
         */
        private const val MONEY_TYPE_CHANGE = 1
        private const val MONEY_TYPE_THIRD_PAY = 2
        private const val MONEY_TYPE_MIXED = 3
    }


    init {
        initView()
    }

    private fun initView() {
        orientation = VERTICAL
        val params = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        layoutParams = params
        View.inflate(context, R.layout.view_pay_info_detail, this)


        rl_discount.setOnClickListener {
            listener.selectCoupon("")
        }

        tv_change_money.setOnClickListener {
            if (isBalanceSufficient) {
                isUseChange = true
            } else {
                isUseChange = !isUseChange
            }

            setChooseChangeMoney(isUseChange)
            updateNeedPayMoney()
        }

        rl_weixin_pay.setOnClickListener {
            if (isBalanceSufficient) {
                isUseChange = false
                setChooseChangeMoney(isUseChange)
                updateNeedPayMoney()
            }
            setSelectPayWay(PAY_WECHAT)
        }

        rl_ali_pay.setOnClickListener {
            if (isBalanceSufficient) {
                isUseChange = false
                setChooseChangeMoney(isUseChange)
                updateNeedPayMoney()
            }
            setSelectPayWay(PAY_ALI)
        }

        tv_ensure_pay.setOnClickListener {
            useMoneyType = if (!isUseChange) {
                MONEY_TYPE_THIRD_PAY
            } else if (isUseChange && sdkPayMoney > 0) {
                MONEY_TYPE_MIXED
            } else {
                MONEY_TYPE_CHANGE
            }
            if (orderInfoBean!!.maxCoupon != null) {
                listener.ensurePay(
                    payWay,
                    sdkPayMoney,
                    useMoneyType,
                    orderInfoBean!!.maxCoupon.code,
                    orderInfoBean!!.maxCoupon.couponType
                )
            } else {
                listener.ensurePay(payWay, sdkPayMoney, useMoneyType, "", "")
            }
        }
    }

    fun setAvailableCount(availableCount: Int) {
        this.availableCount = availableCount
    }

    /**
     * 订单的信息
     * @param payBusinessType 业务类型
     */
    @SuppressLint("SetTextI18n")
    fun setData(orderInfoBean: OrderInfoBean, payBusinessType: Int) {
        this.orderInfoBean = orderInfoBean
        if (payBusinessType == 1) {
            tv_pay_title.text = "课程服务"
        }
        if (payBusinessType == 2) {
            tv_pay_title.text = "倾诉服务"
        }
        if (payBusinessType == 3) {
            tv_pay_title.text = "测评服务"
        }
        if (payBusinessType == 4) {
            tv_pay_title.text = "咨询服务"
        }

        if (payBusinessType == 5) {
            tv_pay_title.text = "送感谢"

            tv_change_money.isEnabled = false
            if (orderInfoBean.availableMoney >= orderInfoBean.applyFee) {
                rl_third_pay.visibility = View.INVISIBLE
                rl_third_pay.isEnabled = false
            }
        }


        //价格
        tv_price.text = orderInfoBean.applyFee.toString()
        //可用余额
        tv_change_useful.text = "[可用￥${orderInfoBean.availableMoney}]"
        rl_discount.visibility = if (orderInfoBean.isShowCoupon) View.VISIBLE else View.GONE

        setCouponData(orderInfoBean.maxCoupon)
    }

    /**
     * 设置优惠券的数据
     *
     */
    @SuppressLint("SetTextI18n")
    fun setCouponData(commonCouponBean: CommonCouponBean?) {
        if (commonCouponBean == null) {
            tv_discount_money.text = "0"
            tv_flag.visibility = View.GONE
            tv_discount_money.visibility = View.GONE
            tv_no_choose.visibility = View.VISIBLE
            if (availableCount == 0) {
                tv_no_choose.text = "暂无优惠"
            } else {
                tv_no_choose.text = "有${availableCount}张优惠券可用"
            }
            orderInfoBean!!.maxCoupon = null

        } else {
            tv_flag.visibility = View.VISIBLE
            tv_discount_money.visibility = View.VISIBLE
            tv_no_choose.visibility = View.GONE

            orderInfoBean!!.maxCoupon = commonCouponBean
            //优惠
            tv_discount_money.text = commonCouponBean.combinedAmount.toString()
        }

        updateNeedPayMoney()
    }

    /**
     * 更新还需支付的金额
     */
    private fun updateNeedPayMoney() {
        var needPay = if (orderInfoBean!!.maxCoupon == null) {
            orderInfoBean!!.applyFee
        } else {
            val b1 = BigDecimal(orderInfoBean!!.applyFee.toString())
            val b2 = BigDecimal(orderInfoBean!!.maxCoupon.combinedAmount.toString())
            b1.subtract(b2).toFloat()
        }

        if (needPay == 0f) {//优惠券已经完全抵扣
            ll_third_pay.visibility = View.GONE
            view_empty.visibility = View.VISIBLE
            ll_third_pay.isEnabled = false
        } else {//不能完全抵扣
            ll_third_pay.visibility = View.VISIBLE
            view_empty.visibility = View.GONE
            ll_third_pay.isEnabled = true
        }


        if (isUseChange) {//使用余额
            if (orderInfoBean!!.availableMoney >= needPay) {
                tv_change_money.text = needPay.toString()
                sdkPayMoney = 0f
                setSelectPayWay(0)

                isBalanceSufficient = true
            } else {
                tv_change_money.text = orderInfoBean!!.availableMoney.toString()

                val bd1 = BigDecimal(needPay.toString())
                val bd2 = BigDecimal(orderInfoBean!!.availableMoney.toString())
                sdkPayMoney = bd1.subtract(bd2).toFloat()
//                sdkPayMoney = needPay - orderInfoBean!!.availableMoney
                if (payWay == 0) {
                    setSelectPayWay(PAY_WECHAT)
                }
                isBalanceSufficient = false
            }
        } else {//不使用余额
            sdkPayMoney = needPay
        }

//        val bg = BigDecimal(sdkPayMoney.toDouble()).setScale(2, RoundingMode.UP)

        tv_pay_money.text = sdkPayMoney.toString()
    }

    /**
     * 选择支付方式
     */
    private fun setSelectPayWay(way: Int) {
        if (payWay == way) {
            return
        }
        payWay = way
        when (payWay) {
            PAY_WECHAT -> {//微信
                img_weixin_way.setImageResource(R.drawable.pay_img_select)
                img_ali_way.setImageResource(R.drawable.pay_img_no_select)
            }
            PAY_ALI -> {//支付宝
                img_weixin_way.setImageResource(R.drawable.pay_img_no_select)
                img_ali_way.setImageResource(R.drawable.pay_img_select)
            }
            else -> {
                img_ali_way.setImageResource(R.drawable.pay_img_no_select)
                img_weixin_way.setImageResource(R.drawable.pay_img_no_select)
            }
        }
    }


    /**
     * 是否选使用余额
     */
    private fun setChooseChangeMoney(isUse: Boolean) {
        if (isUse) {
            tv_change_money.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                R.drawable.pay_img_select,
                0
            )
        } else {
            tv_change_money.setCompoundDrawablesWithIntrinsicBounds(
                0,
                0,
                R.drawable.pay_img_no_select,
                0
            )
        }
    }


    interface OnCouponDetailClickListener {
        /**
         * 选择优惠券
         */
        fun selectCoupon(couponId: String)

        /**
         * 确认支付
         * @param payWay  支付方式  1024.微信支付 1025.支付宝支付
         * @param payMoney  还需支付金额
         * @param useMoneyType   支付类型  1余额，2三方支付，3混合
         * @param code    优惠券code
         * @param couponType    券类型 1兑换券 2新优惠券
         *
         */
        fun ensurePay(
            payWay: Int,
            payMoney: Float,
            useMoneyType: Int,
            code: String,
            couponType: String
        )
    }
}