package com.yidianling.ydl_pay.pay.payDialog

import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.graphics.Point
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.view.*
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.StringUtils
import com.ydl.ydlcommon.utils.log.LogHelper
import com.ydl.ydlcommon.utils.remind.ToastHelper
import com.yidianling.ydl_pay.R
import com.yidianling.ydl_pay.common.bean.params.AliPayParam
import com.yidianling.ydl_pay.common.bean.params.WxPayParam
import com.yidianling.ydl_pay.common.http.HttpUtils
import com.yidianling.ydl_pay.pay.RxPay
import com.yidianling.ydl_pay.pay.bean.PayStatus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.pay_dialog_pay.*
import kotlinx.android.synthetic.main.pay_fragment_loading_dialog.view.*
import java.util.concurrent.TimeUnit
import kotlin.properties.Delegates

@SuppressLint("ValidFragment")
//新的支付弹窗
class PayDialog : Dialog {

    //回调函数
    private var callBack: CallBack? = null

    /**
     * 支付类型
     * 1.微信支付 2.支付宝支付
     */
    private val PAY_WECHAT = 1
    private val PAY_ALI = 2

    //加载中弹窗
    private var dialog: AlertDialog? = null
    private var dialogContentView: View? = null

    /**
     * 已选择支付方式
     */
    private var payType = PAY_WECHAT

    private var data: ConfidePayParams? = null

    private var activity: Activity by Delegates.notNull()

    constructor(context: Activity) : super(context) {
        this.activity = context
    }

    override fun onStart() {
        super.onStart()
        //设置 dialog 的宽高
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        //设置 dialog 的背景为 null
        window.setBackgroundDrawable(null)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //去除标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        val lp = window.attributes
        lp.gravity = Gravity.BOTTOM //底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
//        lp.windowAnimations = R.style.BottomDialogAnimation
        window.attributes = lp

        setContentView(R.layout.pay_dialog_pay)
        initView()


        if (data != null) {
            text_title.text = data!!.payTitle ?: "倾诉服务"
            setFoodPrice("￥${StringUtils.save2Double(data?.orderPrice ?: 0.00)}")
            setSaleText("-￥${StringUtils.save2Double(data?.coupnPrice ?: 0.00)}")
            setAvliableMoney("-￥${StringUtils.save2Double(data?.avliableMoney ?: 0.00)}")
            setPayMoney()
        }
    }

    fun initView() {
        //确定支付
        text_pay.setOnClickListener {
            appPay()
        }
        //切换支付方式
        ll_wechat.setOnClickListener {
            payType = PAY_WECHAT
            iv_wechat.setImageResource(R.drawable.pay_img_select)
            iv_alipay.setImageResource(R.drawable.pay_img_no_select)
        }
        ll_alipay.setOnClickListener {
            payType = PAY_ALI
            iv_wechat.setImageResource(R.drawable.pay_img_no_select)
            iv_alipay.setImageResource(R.drawable.pay_img_select)
        }
    }

    //设置回调函数
    fun setCallback(callBack: CallBack): PayDialog {
        this.callBack = callBack
        return this
    }

    //设置数据
    fun show(data: ConfidePayParams?) {
        this.data = data
        show()
    }

    //设置三方支付是否显示
    fun setOtherPayVisibity(visibity: Int) {
        text_paytip.visibility = visibity
        lin_pay.visibility = visibity
    }

    //设置商品价格
    fun setFoodPrice(moeny: String) {
        text_oldmoney.text = moeny
    }

    //设置可用余额
    fun setAvliableMoney(moeny: String) {
        text_yu_e.text = moeny
    }

    //设置优惠信息
    fun setSaleText(money: String) {
        text_youhui.text = money
    }

    //设置应支付金额
    fun setPayMoney() {
        if (data != null && data!!.orderPrice != null && data!!.coupnPrice != null && data!!.avliableMoney != null) {
            var price: Double = data!!.orderPrice!! - data!!.coupnPrice!! - data!!.avliableMoney!!
            if (price < 0.00) {
                price = 0.00
            }
            text_money.text = "￥${StringUtils.save2Double(price)}"
        } else {
            text_money.text = "--"
        }
    }

    /**
     * app 支付，微信或支付宝
     */
    @SuppressLint("CheckResult")
    private fun appPay() {

        if (data?.payId == null) {
            ToastHelper.show("支付id有误，请返回重试")
            return
        }

        Observable.just(payType)
            .subscribeOn(Schedulers.io())
            .flatMap {
                when (it) {
                    0, 1 -> {
                        wxPayById(data?.payId!!,data?.merchantType.toString())
                    }
                    else -> {
                        aliPayById(data?.payId!!)
                    }
                }
            }
            .observeOn(AndroidSchedulers.mainThread())
            .doOnSubscribe { showProgressDialog("") }
            .doAfterTerminate { if (!activity.isFinishing) dismissProgressDialog() }
            .subscribe({
                //防止支付后支付端和服务端通知同步延迟 , 1.5秒后回调callback
                Observable.timer(1500, TimeUnit.MILLISECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        if (activity != null && !activity.isFinishing) dismissProgressDialog()
                        this.callBack?.onSuccess()
                    }
                LogHelper.getInstance().writeLogSync("支付成功")
                this.callBack?.onSuccess()
                dismiss()
            }, {
                ToastHelper.show(it.message ?: "支付失败")
                LogHelper.getInstance().writeLogSync("支付失败：${it.message}")
            })
    }

    /**
     * 微信支付
     * @param payId 支付id
     */
    private fun wxPayById(payId: String,merchantType:String): Observable<PayStatus> {
        val bean = WxPayParam(payId, 1,merchantType)
        return HttpUtils.wxPay(bean)
            .compose(RxUtils.resultData())
            .observeOn(AndroidSchedulers.mainThread())
            .flatMap { RxPay.wxPay(activity, it.option) }
    }

    /**
     * 支付宝支付
     * @param payId 支付Id
     */
    private fun aliPayById(payId: String): Observable<PayStatus> {
        var bean = AliPayParam(payId, 1)
        return HttpUtils.getAliPayOrderId(bean)
            .compose(RxUtils.resultData())
            .flatMap {
                RxPay.aliPay(activity, it.aliSign)
            }
    }

    /**
     * 显示加载中弹窗
     */
    private fun showProgressDialog(str: String?) {
        if (activity == null || activity.isFinishing) {
            return
        }
        if (dialog != null && dialog!!.isShowing) {
            return
        }
        if (dialog == null) {
            dialog = AlertDialog.Builder(activity)
                .create()
        }
        if (dialogContentView == null) {
            dialogContentView = LayoutInflater.from(activity).inflate(R.layout.pay_fragment_loading_dialog, null)
            dialogContentView?.tvMsg?.visibility = View.GONE
        }
        dialog?.show()
        dialog?.window?.setContentView(dialogContentView)
        dialog?.window?.setGravity(Gravity.CENTER)
        val p = dialog?.window!!.attributes  //获取对话框当前的参数值
        var point = Point()
        activity.windowManager.defaultDisplay.getSize(point)// 获取屏幕宽、高用
        p.height = (point.y * 0.2).toInt()
        p.width = (point.x * 0.35).toInt()
        dialog?.window!!.attributes = p     //设置生效
    }

    /**
     * 隐藏加载中弹窗
     */
    private fun dismissProgressDialog() {
        if (dialog != null && dialog!!.isShowing) {
            dialog!!.dismiss()
        }
    }

}

/**
 * 支付成功回调函数
 */
interface CallBack {
    fun onSuccess()
    fun onError()
}