package com.yidianling.home.ui.view

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.ydl.ydl_image.manager.YDLImageCacheManager
import com.yidianling.home.R
import com.yidianling.home.event.IHomeBaseEvent
import com.yidianling.home.model.bean.HomeCourseBean
import kotlinx.android.synthetic.xlzx.home_course_item_view.view.*

/**
 * @author <a href="https://www.jianshu.com/u/c1e5310dd724">xujian</a>
 * @描述: 课程成长模块item
 * @Copyright Copyright (c) 2019
 * @Company 壹点灵
 * @date 2019/02/14
 */
class HomeCourseItemView(private val mContext: Context, private var homeEvent: IHomeBaseEvent?) :
    RelativeLayout(mContext) {

    init {
        initView()
    }

    private fun initView() {
        val params = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        layoutParams = params
        View.inflate(mContext, R.layout.home_course_item_view, this)
    }

    /**
     * 刷新数据
     */
    @SuppressLint("SetTextI18n")
    fun updateData(bean: HomeCourseBean.ListBean?) {

        YDLImageCacheManager.showImage(mContext, bean?.pic, homeModuleCourseItemViewImg)
        homeModuleCourseItemViewTitle.text = bean?.title
        homeModuleCourseItemViewPersonNum.text = bean?.readNums.toString()

        if (bean?.applyFee == 0f) {
            homeModuleCourseItemViewFreePrice.visibility = View.VISIBLE
            homeModuleCourseItemViewExpensePriceHideView.visibility = View.GONE
        } else {
            if (bean?.isPromotion == 1) {
                homeModuleCourseItemViewExpensePrice.text =
                    "￥" + getLastPrice(String.format("%.2f", bean?.promotionApplyFee?:0))
            } else {
                homeModuleCourseItemViewExpensePrice.text =
                    "￥" + getLastPrice(String.format("%.2f", bean?.applyFee?:0))
            }
        }

        setOnClickListener {
            bean?.let {
                homeEvent?.courseItemClick(bean)
            }
        }
    }

    fun getLastPrice(price: String): String {
        if (price.length > 3) {
            if ("0" == price[price.lastIndex].toString() && "0" == price[price.lastIndex - 1].toString() && "." == price[price.lastIndex - 2].toString()
            ) {
                return price.substring(0, price.length - 3)
            }
        }
        return price
    }
}