package com.yidianling.ydl_pay.pay.redpacket

import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.yidianling.common.tools.RxImageTool
import com.yidianling.ydl_pay.R
import kotlinx.android.synthetic.main.pay_redpacket_view.view.*

/**
 * @author yuanWai
 * @描述:红包View
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/10/24
 */
class RedPacketView : RelativeLayout{

    private var listener : ICheckedListener? = null

    constructor(mContext : Context):super(mContext){
        initView(0)
    }

    constructor(mContext : Context,marginTop : Int):super(mContext){
        initView(marginTop)
    }

    constructor(mContext : Context, attrs : AttributeSet) : super(mContext,attrs){
        initView(0)
    }

    constructor(mContext: Context,attrs : AttributeSet,defStyleAttr : Int) : super(mContext,attrs,defStyleAttr){
        initView(0)
    }

    private fun initView(marginTop : Int){
        View.inflate(context, R.layout.pay_redpacket_view,this)
        var params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,RxImageTool.dip2px(90f))
        val dp15 = RxImageTool.dip2px(15f)
        params.setMargins(dp15,marginTop,dp15,RxImageTool.dip2px(20f))
        layoutParams = params
        setBackgroundResource(R.drawable.pay_redpacket_item_bg)
    }

    @SuppressLint("SimpleDateFormat")
    fun initData(data : RedPacketBean?, position: Int, listener : ICheckedListener){
        this.listener = listener
        if (null == data){
            visibility = View.GONE
            return
        }
        visibility = View.VISIBLE
        val sb = StringBuffer()
//        val nf = NumberFormat.getInstance()
        sb.append("￥").append(if (null == data.coupon_money) 0 else data.coupon_money.toInt())
        //红包说明
        tv_title.text = data.title
        //截止日期
        val timeBuffer = StringBuffer()
        if (1 == data.use_type){
            //永久使用
            timeBuffer.append("永久有效")
        }else{
            //有效期内使用
            timeBuffer.append("有效期至").append(data.use_time_end)
        }
        tvTimeEnd.text = timeBuffer.toString()
        //红包金额
        tvMoney.text = sb.toString()
        //选择红包监听
        setOnClickListener {
            if (null != this.listener){
                this.listener!!.checked(data,position)
            }
        }
    }

    fun checked(isChecked: Boolean){
        if (isChecked){
            imgCheck.visibility = View.VISIBLE
        }else{
            imgCheck.visibility = View.GONE
        }
    }

    interface ICheckedListener{
        fun checked(bean : RedPacketBean, position : Int)
    }
}