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
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.modular.ModularServiceManager
import com.ydl.ydlcommon.utils.MainUtils
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.TestHomeActivity
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
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 jumpTestHomeActivity(context: Context) {
            val intent = Intent(context, TestHomeActivity::class.java)
            context.startActivity(intent)
        }


        /**
         * 返回拼接好的人气字符串
         */
        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())
            }
            hitBuffer.append(context.resources.getString(R.string.tests_testhome_hit))

            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())
            }
            numBuffer.append(context.resources.getString(R.string.tests_testhome_peopletest))

            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)
            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)
            textView.text = sp
        }
        /**
         * 根据截取的位置 设置文本大小
         */
        fun priceStyleNew(context: Context, textView: TextView, content: String, subIndex: Int, EndIndex: Int) {
            val sp = SpannableString(content)
            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)
            textView.text = sp
        }

        /**
         * 更新优惠券信息
         * 只有当和上一次优惠券金额不一致时才会发事件通知更新
         */
        fun updateCouponMoney(){
            var userId = ModularServiceManager.getPlatformUserService()?.getUser()?.userId?: "";
            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
        }
    }
}