package com.miya.fastcashier.util.manage

import android.content.Context
import android.text.TextUtils
import com.blankj.utilcode.util.GsonUtils
import com.fastcashier.lib_common.function.account.AccountService.getUserName
import com.google.gson.reflect.TypeToken
import com.miya.fastcashier.bean.ChannelInfoBean
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
import kotlin.collections.HashMap

/**
 * 类说明：渠道管理类（用于处理品牌全局设置，以及换肤所需渠道配置）
 * 详细描述：目前通过本地资源文件加载  todo 后期能改成接口返回渠道最好
 * 创建人：zpxiang
 * 创建时间：
 * 修改人：
 * 修改时间：
 */
object ChannelManageKit {
    private var channelMap: HashMap<String, ChannelInfoBean>? = null//key为账号，value为所属的品牌信息
    private const val CHANNEL_OFFICIAL_ACCOUNT = "-1"
    private const val CHANNEL_OFFICIAL_CHANNELNAME = "通用"
    private const val CHANNEL_OFFICIAL_CHANNELNAME_EN = "common"

    /**
     * 初始化本地渠道数据
     */
    fun initChannelRes(context: Context?) {
        clearChannelResData()
        if (null == context) {
            initDefaultChannelRes()
            return
        }
        val assetsJson = getAssetsJson(context, "channel.json")
        if (TextUtils.isEmpty(assetsJson)) {
            initDefaultChannelRes()
            return
        }
        val channelInfoList = GsonUtils.fromJson<ArrayList<ChannelInfoBean>>(
            assetsJson,
            object : TypeToken<List<ChannelInfoBean?>?>() {}.type
        )
        channelMap = HashMap()
        if (!channelInfoList.isEmpty()) {
            for (i in channelInfoList.indices) {
                val channelInfoBean = channelInfoList[i]
                val channelAccountArray = channelInfoBean.channelAccountArray
                if (channelAccountArray.isEmpty()) {
                    initDefaultChannelRes()
                    continue
                }
                for (j in channelAccountArray.indices) {
                    val account = channelAccountArray[j]
                    channelMap!![account] = channelInfoBean
                }
            }
        }
    }

    private fun initDefaultChannelRes() {
        if (channelMap == null) {
            channelMap = HashMap()
        }
        val commonChannel = ChannelInfoBean()
        commonChannel.channelId = "-1"
        commonChannel.channelName = CHANNEL_OFFICIAL_CHANNELNAME
        commonChannel.channelNameEn = CHANNEL_OFFICIAL_CHANNELNAME_EN
        channelMap!![CHANNEL_OFFICIAL_ACCOUNT] = commonChannel
    }

    /**
     * 判断本地是否包含本品牌账户，此处暂时用来处理区别大屏和手持账号
     */
    fun containsAccount(context: Context?, account: String): Boolean {
        if (channelMap == null || channelMap!!.isEmpty()) {
            initChannelRes(context)
        }
        return channelMap!!.containsKey(account)
    }

    /**
     * 获取渠道名称
     */
    fun getAppChannelName(context: Context?): String {
        if (channelMap == null || channelMap!!.isEmpty()) {
            initChannelRes(context)
        }
        val containsKey = channelMap!!.containsKey(getUserName())
        return if (!containsKey) {
            CHANNEL_OFFICIAL_CHANNELNAME
        } else channelMap!![getUserName()]!!.channelName
    }

    /**
     * 获取App渠道编号
     */
    fun getAppChannelId(context: Context?): String {
        if (context == null) {
            return CHANNEL_OFFICIAL_ACCOUNT
        }
        if (channelMap == null || channelMap!!.isEmpty()) {
            initChannelRes(context)
        }
        return if (!channelMap!!.containsKey(getUserName())) {
            CHANNEL_OFFICIAL_ACCOUNT
        } else channelMap!![getUserName()]!!.channelId
    }

    fun clearChannelResData() {
        if (null == channelMap) {
            return
        }
        channelMap!!.clear()
        channelMap = null
    }

    /**
     * 读取json文件
     */
    private fun getAssetsJson(context: Context, fileName: String): String {
        val stringBuilder = StringBuilder()
        val assetManager = context.assets
        try {
            val bf = BufferedReader(InputStreamReader(assetManager.open(fileName), "UTF-8"))
            var line: String?
            while (bf.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }
}