package com.ydl.ydl_pay.widget

import android.content.Context
import android.os.Handler
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.ydl.ydl_pay.adapter.SelectCouponAdapter
import com.yidianling.ydl_pay.http.HttpUtils
import com.ydl.ydl_pay.toast.ToastHelper
import com.yidianling.ydl_pay.R
import com.yidianling.ydl_pay.bean.AllCouponListBean
import com.yidianling.ydl_pay.bean.CommonCouponBean
import com.yidianling.ydl_pay.bean.params.CheckRequestCouponBean
import com.yidianling.ydl_pay.http.utils.NetUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.head_course_code_view.view.*
import kotlinx.android.synthetic.main.view_pay_coupon.view.*

/**
 * @author jiucheng
 * @描述:支付优惠券选择view
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2019/4/4
 */
class PayCouponView(context: Context) : LinearLayout(context) {
    private var selectedCouponBean: CommonCouponBean? = null
    private var couponListBean: AllCouponListBean? = null
    private var listener: OnCouponClickListener? = null
    private var goodsId: String? = null
    private var adapter: SelectCouponAdapter? = null
    private var hasUseCouponCode = false
    private var courseCodeView: View? = null
    private var rt_coupon_code: EditText? = null
    private var tv_ensure: TextView? = null

    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_coupon, this)
        rl_back.setOnClickListener {
            hideSoftInput()

            if (listener != null) {
                listener!!.onBackClick(selectedCouponBean)
            }
        }

        var linearLayoutManager = LinearLayoutManager(context)
        rv_content.layoutManager = linearLayoutManager
    }


    /**
     * 动态隐藏软键盘
     *
     * @param context 上下文
     * @param edit    输入框
     */
    private fun hideSoftInput() {
        if (rt_coupon_code == null) {
            return
        }
        rt_coupon_code!!.clearFocus()
        val inputmanger = context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputmanger.hideSoftInputFromWindow(rt_coupon_code!!.windowToken, 0)
    }

    /**
    验证兑换券是否可用
     */
    private fun checkCourseCoupon(couponCode: String) {
        hideSoftInput()

        if (!NetUtils.isConnected(context)) {
            ToastHelper.show(context, context.getString(R.string.net_error))
            return
        }


        var bean = CheckRequestCouponBean()
        bean.couponCode = couponCode
        bean.courseId = goodsId
        HttpUtils.checkCourseCoupon(bean)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (it.code == 200) {
                        if (it.data != null) {
                            if (it.data.couponInfo != null) {
                                hasUseCouponCode = true
                                selectedCouponBean = it.data.couponInfo
                                if (tv_ensure != null) {
                                    tv_ensure!!.text = "取消使用"
                                }
                                clearSelectCoupon()

                                Handler().postDelayed({
                                    if (listener != null) {
                                        listener!!.onSelectCoupon(selectedCouponBean)
                                    }
                                }, 300)

                            } else {
                                ToastHelper.show(context, it.data.msg)
                            }
                        } else {
                            ToastHelper.show(context, it.msg)
                        }
                    } else {
                        ToastHelper.show(context, it.msg)
                    }
                }, { e ->
                    ToastHelper.show(context, e.message!!)
                })
    }


    fun setListener(listener: OnCouponClickListener) {
        this.listener = listener
    }

    /**
     * 设置数据
     */
    fun setData(couponListBean: AllCouponListBean, isCoursePay: Boolean, selectedCouponBean: CommonCouponBean?, goodsId: String) {
//        rl_course.visibility = if (isCoursePay) View.VISIBLE else View.GONE
        if (isCoursePay) {
            if (courseCodeView == null) {
                initCourseCodeView()
            }
        }

        this.couponListBean = couponListBean
        this.selectedCouponBean = selectedCouponBean
        this.goodsId = goodsId


        if (couponListBean.availableCount == 0 && couponListBean.unAvailableCount == 0) {
            rl_empty.visibility = View.VISIBLE
//            rv_content.visibility = View.GONE
        } else {
            if (this.selectedCouponBean == null && couponListBean.availableCount != 0) {
                this.couponListBean!!.available[0].hasSelected = 1
                this.selectedCouponBean = this.couponListBean!!.available[0]
            }
        }
        adapter = SelectCouponAdapter(this.couponListBean!!, context) {
            this.selectedCouponBean = it
            hasUseCouponCode = false
            if (tv_ensure != null) {
                tv_ensure!!.text = "使用"
            }

            hideSoftInput()

            Handler().postDelayed({
                if (listener != null) {
                    listener!!.onSelectCoupon(it)
                }
            }, 300)
        }
        if (courseCodeView != null) {
            adapter!!.setHeadView(courseCodeView!!)
        }
        rv_content.adapter = adapter
    }


    /**
     * 输入课程兑换码
     */
    private fun initCourseCodeView() {
        courseCodeView = View.inflate(context, R.layout.head_course_code_view, null)
        var parmas = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        courseCodeView!!.layoutParams = parmas
        rt_coupon_code = courseCodeView!!.rt_coupon_code
        tv_ensure = courseCodeView!!.tv_ensure
        rt_coupon_code!!.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                tv_ensure!!.isEnabled = !TextUtils.isEmpty(s) && s!!.length == 8
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })

        tv_ensure!!.setOnClickListener {
            if (hasUseCouponCode) {
                selectedCouponBean = null
                tv_ensure!!.text = "使用"
                hasUseCouponCode = false
            } else {
                checkCourseCoupon(rt_coupon_code!!.text.toString())
            }
        }
    }

    private fun clearSelectCoupon() {
        if(couponListBean!!.available!=null){
            repeat(couponListBean!!.available.size) {
                couponListBean!!.available[it].hasSelected = 0
            }
            adapter!!.notifyDataSetChanged()
        }
    }

    interface OnCouponClickListener {
        //返回按钮
        fun onBackClick(selectedCouponBean: CommonCouponBean?)

        //选择了优惠券
        fun onSelectCoupon(selectedCouponBean: CommonCouponBean?)
    }
}
