package com.casic.br.extensions import android.content.Context import android.util.Log import com.casic.br.callback.OnImageCompressListener import com.casic.br.model.ErrorMessageModel import com.casic.br.utils.LocaleConstant import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.pengxh.kt.lite.extensions.createCompressImageDir import com.pengxh.kt.lite.extensions.toJson import com.pengxh.kt.lite.utils.SaveKeyValues import org.json.JSONObject import top.zibin.luban.Luban import top.zibin.luban.OnCompressListener import java.io.File import java.text.ParseException import java.util.* import kotlin.math.abs /** * String扩展方法 */ fun String.createCommand(value: Any): String { val map = HashMap<String, Any>() map[this] = value val command = map.toJson() Log.d("kTag", "createCommand: $command") return command } fun String.compressImage(context: Context, listener: OnImageCompressListener) { Luban.with(context) .load(this) .ignoreBy(100) .setTargetDir(context.createCompressImageDir().toString()) .filter { !(it.isBlank() || it.lowercase(Locale.getDefault()).endsWith(".gif")) } .setCompressListener(object : OnCompressListener { override fun onStart() { } override fun onSuccess(file: File) { listener.onSuccess(file) } override fun onError(e: Throwable) { listener.onError(e) } }).launch() } /** * 时间差-天 * */ fun String.diffDate(): Int { if (this.isBlank()) { return 0 } try { val diff = abs(System.currentTimeMillis() - this.toLong() * 1000L) return (diff / (86400000)).toInt() } catch (e: ParseException) { e.printStackTrace() } return 0 } 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() } //拼接图片地址 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.diffMinute(): Int { if (this.isBlank()) { return 0 } try { val diff = abs(System.currentTimeMillis() - this.toLong()) println(diff) return (diff / (60000)).toInt() } catch (e: ParseException) { e.printStackTrace() } return 0 } fun String.toChineseTypeName(): String { if (this.isBlank()) { return "其他" } return when (this) { "yyj" -> "智能油烟机" "rs" -> "智能热水器" "rqz" -> "智能燃气灶" "bgl" -> "智能壁挂炉" "pc" -> "Wi-Fi智能插排" "cz" -> "Wi-Fi智能插座" "wg2" -> "智能网关" else -> "其他" } }