package com.casic.smarttube.extensions import com.casic.smarttube.R import com.casic.smarttube.model.ErrorMessageModel import com.casic.smarttube.utils.LocaleConstant import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.pengxh.kt.lite.extensions.dateToTimestamp import com.pengxh.kt.lite.utils.SaveKeyValues import org.json.JSONObject import java.text.SimpleDateFormat import java.util.* /** * String扩展方法 */ fun String.separateResponseCode(): Int { if (this.isBlank()) { return 404 } return JSONObject(this).getInt("code") } fun String.toErrorMessage(): String { val errorModel = Gson().fromJson<ErrorMessageModel>( this, object : TypeToken<ErrorMessageModel>() {}.type ) return errorModel.message.toString() } /** * 下载路径为 http://xx.com/static/ 拼接downloadUrl * */ fun String.appendDownloadUrl(): String { if (this.isEmpty()) return this val defaultValue = SaveKeyValues.getValue( LocaleConstant.DEFAULT_SERVER_CONFIG, LocaleConstant.SERVER_BASE_URL ) as String return "$defaultValue/static/${this}" } //拼接图片地址 fun String.combineImagePath(): String { if (this.isEmpty()) return this val defaultValue = SaveKeyValues.getValue( LocaleConstant.DEFAULT_SERVER_CONFIG, LocaleConstant.SERVER_BASE_URL ) as String return "$defaultValue/static/${this.replace("\\", "/")}" } //电量转图片 fun String.toBatteryImage(): Int { if (this.isBlank()) { return R.drawable.ic_battery_0 } try { when (this.toInt()) { in 0..10 -> return R.drawable.ic_battery_0 in 11..30 -> return R.drawable.ic_battery_1 in 31..60 -> return R.drawable.ic_battery_2 in 61..90 -> return R.drawable.ic_battery_3 in 91..100 -> return R.drawable.ic_battery_4 } } catch (e: ClassCastException) { e.printStackTrace() } return R.drawable.ic_battery_0 } /** * 时间转月日 */ fun String.dateToMonthDay(): String { val timestamp = this.dateToTimestamp() val dateFormat = SimpleDateFormat("MM-dd", Locale.CHINA) return dateFormat.format(Date(timestamp)) }