TestHomeUtils.kt 11.4 KB
Newer Older
konghaorui committed
1 2 3 4 5 6 7 8 9 10 11
package com.yidianling.tests.home.utils

import android.content.Context
import android.content.Intent
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.TextAppearanceSpan
import android.view.View
import android.widget.TextView
import com.ydl.ydlcommon.data.http.RxUtils
konghaorui committed
12 13
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.utils.MainUtils
konghaorui committed
14 15 16 17 18 19 20 21
import com.ydl.ydlcommon.utils.SharedPreferencesEditor
import com.yidianling.common.tools.LogUtil
import com.yidianling.tests.R
import com.yidianling.tests.TestRetrofitApi
import com.yidianling.tests.home.bean.TestHomeBodyBean
import com.yidianling.tests.home.bean.TestHomeDataBean
import com.yidianling.tests.home.config.ITestHomeConfig
import com.yidianling.tests.home.event.UpdateCouponMoneyEvent
konghaorui committed
22
import com.yidianling.tests.router.TestsIn
konghaorui committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
import de.greenrobot.event.EventBus
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import java.math.BigDecimal
import java.text.DecimalFormat
import java.text.NumberFormat


/**
 * @author yuanwai
 * @描述:测评首页工具类
 * @Copyright Copyright (c) 2018
 * @Company 壹点灵
 * @date 2018/7/28
 */
class TestHomeUtils {

    companion object {
        private var recommendListCache: List<TestHomeDataBean>? = null
        val TEST_MAX_COUPON_MONEY_SP_KEY = "TestMaxCouponMoneySpKey"

        /**
         * 读取Assets下文本文件
         */
        fun getAssertsFile(context: Context, fileName: String): ByteArray? {
            var inputStream: InputStream? = null
            val assetManager = context.assets
            try {
                inputStream = assetManager.open(fileName)
                if (inputStream == null) {
                    return null
                }

                var bis: BufferedInputStream? = null
                val length: Int
                try {
                    bis = BufferedInputStream(inputStream)
                    length = bis.available()
                    val data = ByteArray(length)
                    bis.read(data)

                    return data
                } catch (e: IOException) {

                } finally {
                    if (bis != null) {
                        try {
                            bis.close()
                        } catch (e: Exception) {

                        }
                    }
                }

                return null
            } catch (e: IOException) {
                e.printStackTrace()
            }

            return null
        }

        /**
         * 数据整合 将最后一个热门推荐数据 拆分成集合的形式
         */
        fun resetData(list: List<TestHomeDataBean>): List<TestHomeDataBean> {
            var dataList = ArrayList<TestHomeDataBean>()
            for (item in list) {
                if (item.type == ITestHomeConfig.TYPE_RECOMMENDED) {
                    resetRecommedData(item)
                    dataList.addAll(getRecommedDataByPage(1))
                } else {
                    dataList.add(item)
                }
            }

            return dataList
        }

        /**
         * 因为热门推荐列表在一个body下
         * 这个方法是将一个body拆分成多个body 供Recycleview使用
         */
        private fun resetRecommedData(databean: TestHomeDataBean): List<TestHomeDataBean> {
            if (null == recommendListCache) {
                recommendListCache = ArrayList()
            } else {
                (recommendListCache as ArrayList<TestHomeDataBean>).clear()
            }
            var index = 0
            for (item in databean.body!!) {
                var bodyList = ArrayList<TestHomeBodyBean>()
                //用于列表区分是否为第一个view 展示的样式是不同的
                item.recommendIsFirst = index == 0
                bodyList.add(item)
                var testHomeDataBean = TestHomeDataBean(databean.type, bodyList, databean.category, databean.head, databean.footer, databean.diviLine)

                (recommendListCache as ArrayList<TestHomeDataBean>).add(testHomeDataBean)
                index++
            }

            return recommendListCache as ArrayList<TestHomeDataBean>
        }

        /**
         * 根据页数返回下一页 热门推荐列表数据
         */
        fun getRecommedDataByPage(page: Int): List<TestHomeDataBean> {
            var dataList = ArrayList<TestHomeDataBean>()
            if (page == 4) {
                return dataList
            }
            for (i in (page - 1) * 10..((page - 1) * 10 + 9)) {
                if (i < recommendListCache!!.size) {
                    dataList.add(recommendListCache!!.get(i))
                }
            }
            return dataList
        }


        /**
         * 返回拼接好的人气字符串
         */
        fun getHits(context: Context, hits: String?): String {
            if (TextUtils.isEmpty(hits)) {
                return ""
            }
            var iHits = hits!!.toFloat()
            var fnum = DecimalFormat("#.0") as NumberFormat
            var hitBuffer = StringBuffer()
            if (iHits >= 10000) {
                iHits /= 10000
                hitBuffer.append(fnum.format(iHits))
                hitBuffer.append("万")
            } else {
                hitBuffer.append(iHits.toInt())
            }
165
            hitBuffer.append(context.resources.getString(R.string.tests_testhome_hit))
konghaorui committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

            return hitBuffer.toString()
        }

        fun getHitsNew(context: Context, hits: String?): String {
            if (TextUtils.isEmpty(hits)) {
                return ""
            }
            var iHits = hits!!.toFloat()
            var fnum = DecimalFormat("#.0") as NumberFormat
            var hitBuffer = StringBuffer()
            if (iHits >= 10000) {
                iHits /= 10000
                hitBuffer.append(fnum.format(iHits))
                hitBuffer.append("万")
            } else {
                hitBuffer.append(iHits.toInt())
            }
            return hitBuffer.toString()
        }

        /**
         * 返回拼接好的多少人测过的字符串
         */
        fun getNum(context: Context, num: String?): String {
            var iNum = num!!.toDouble()
            var fnum = DecimalFormat("#.0") as NumberFormat
            var numBuffer = StringBuffer()
            if (iNum >= 10000) {
                iNum /= 10000
                numBuffer.append(fnum.format(iNum))
                numBuffer.append("万")
            } else {
                numBuffer.append(iNum.toInt())
            }
201
            numBuffer.append(context.resources.getString(R.string.tests_testhome_peopletest))
konghaorui committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

            return numBuffer.toString()
        }

        fun getNumNew(context: Context, num: String?): String {
            var iNum = num!!.toDouble()
            var fnum = DecimalFormat("#.0") as NumberFormat
            var numBuffer = StringBuffer()
            if (iNum >= 10000) {
                iNum /= 10000
                numBuffer.append(fnum.format(iNum))
                numBuffer.append("万")
            } else {
                numBuffer.append(iNum.toInt())
            }
            return numBuffer.toString()
        }

        fun buildJumpMine(context: Context) {
            val intent = Intent()
            intent.putExtra(MainUtils.ACTION_TAG, MainUtils.JUMP_MAIN_TAB_CHANGE)
            intent.putExtra(MainUtils.MAIN_TAB_INDEX, 4)
            intent.setClassName(context, "com.cxzapp.yidianling.MainActivity")
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            context.startActivity(intent)
        }

        /**
         * 根据截取的位置 设置文本大小
         */
        fun priceStyle(context: Context, textView: TextView, content: String, subIndex: Int, EndIndex: Int) {
            val sp = SpannableString(content)
234 235
            sp.setSpan(TextAppearanceSpan(context, R.style.tests_style_price_start), 0, subIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            sp.setSpan(TextAppearanceSpan(context, R.style.tests_style_price_end), subIndex, EndIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
konghaorui committed
236 237 238 239 240 241 242
            textView.text = sp
        }
        /**
         * 根据截取的位置 设置文本大小
         */
        fun priceStyleNew(context: Context, textView: TextView, content: String, subIndex: Int, EndIndex: Int) {
            val sp = SpannableString(content)
243 244
            sp.setSpan(TextAppearanceSpan(context, R.style.tests_style_price_end), 0, subIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            sp.setSpan(TextAppearanceSpan(context, R.style.tests_style_price_start), subIndex, EndIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
konghaorui committed
245 246 247 248 249 250 251 252
            textView.text = sp
        }

        /**
         * 更新优惠券信息
         * 只有当和上一次优惠券金额不一致时才会发事件通知更新
         */
        fun updateCouponMoney(){
konghaorui committed
253
            var userId = TestsIn.getUserService().getUserInfo()?.uid?: "";
konghaorui committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
            TestRetrofitApi.getTestRetrofitApi()
                    .fetchMaxCoupon(userId)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(RxUtils.resultJavaData())
                    .subscribe(Consumer {
                        var lastCouponMoney = SharedPreferencesEditor.getString(TEST_MAX_COUPON_MONEY_SP_KEY)
                        if (TextUtils.isEmpty(lastCouponMoney)|| lastCouponMoney !== it.toString()){
                            SharedPreferencesEditor.putString(TEST_MAX_COUPON_MONEY_SP_KEY,it.toString())
                            EventBus.getDefault().post(UpdateCouponMoneyEvent(it))
                        }
                    }, object : ThrowableConsumer() {
                        override fun accept(msg: String) {
                           LogUtil.i(msg)
                        }
                    })
        }

        /**
         * 获取真实测试题价格
         * 减去优惠券价格
         * 如果为空则隐藏优惠券提示
         */
        fun getOriginalPrice(tv_coupon_money:TextView,price:String?,couponMoney:String):String{
            var couponMoney = couponMoney
            if (!TextUtils.isEmpty(couponMoney)
                            && "0" != couponMoney
                            && "0.0" != couponMoney
                            && "0.00" != couponMoney){
                tv_coupon_money.visibility = View.VISIBLE
                tv_coupon_money.text = String.format("券已抵扣%s元",couponMoney)
            }else{
                tv_coupon_money.visibility = View.GONE
                couponMoney = "0.0"
            }
            var newPrice  = price
            if ("元" == price?.substring(price.length-1,price.length)){
                newPrice = price.substring(0,price.length-1)
            }
            var numberPrice = BigDecimal(newPrice).toDouble()
            if (numberPrice <= BigDecimal(couponMoney).toDouble()){
                newPrice  = "0.00"
            }else{
//                newPrice = (numberPrice - couponMoney).toString()
                //解决Double相减精度损失
                val bd1 = BigDecimal(newPrice)
                val bd2 = BigDecimal(couponMoney)
                newPrice =  bd1.subtract(bd2).toDouble().toString()
            }
            return newPrice
        }
    }
}