package com.miya.fastcashier.util.manage

import android.Manifest
import android.os.Environment
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.EncodeUtils
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.fastcashier.lib_common.function.account.AccountService.getAccountPassword
import com.fastcashier.lib_common.function.account.AccountService.getUserName
import com.fastcashier.lib_common.function.account.AccountService.setAccountPassword
import com.fastcashier.lib_common.util.isBase64
import com.permissionx.guolindev.PermissionX
import java.nio.charset.Charset
import java.util.concurrent.Executors

/**
 * 类描述：账户管理员密码管理
 * 概述：密码以base64处理存到本地，初始化时解码到内存
 * 创建人：zpxiang
 * 创建时间：2022/4/1
 * 修改人：
 * 修改时间：
 */
class AccountPasswordManageKit private constructor() {

    companion object {
        private val FileDir = Environment.getExternalStorageDirectory().toString() + "/fastcashier/"
        const val ACCOUNT_DEFAULT_PASSWORD = "123456"
        private var sInstance: AccountPasswordManageKit? = null
        val instance: AccountPasswordManageKit?
            get() {
                if (sInstance == null) {
                    sInstance = AccountPasswordManageKit()
                }
                return sInstance
            }

        @Synchronized
        fun get(): AccountPasswordManageKit {
            return instance!!
        }
    }

    interface AccountPasswordManageCallback {
        fun onPasswordGet(password: String?)
    }

    fun checkAccountPassword(context: AppCompatActivity) {
        val accountPassword = getAccountPassword()
        if (!TextUtils.isEmpty(accountPassword)) return
        PermissionX.init(context)
            .permissions(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            .request { allGranted: Boolean, grantedList: List<String?>?, deniedList: List<String?>? ->
                if (allGranted) {
                    initAccountPassword(context, null)
                } else {
                    ToastUtils.showShort("请检查权限后重试")
                }
            }
    }

    val currentAccountFilePath: String
        get() = FileDir + getUserName()

    fun initAccountPassword(context: AppCompatActivity, callback: AccountPasswordManageCallback?) {
        if (FileUtils.isFileExists(currentAccountFilePath)) {
            Executors.newCachedThreadPool().execute {
                val password64 = FileIOUtils.readFile2String(
                    currentAccountFilePath
                )

                val password = if (isBase64(password64))
                    EncodeUtils.base64Decode(password64).toString(Charset.defaultCharset())
                else password64

                setAccountPassword(password)
                context.runOnUiThread { callback?.onPasswordGet(password) }
            }
            return
        }
        setAccountPassword(ACCOUNT_DEFAULT_PASSWORD)
        callback?.onPasswordGet(ACCOUNT_DEFAULT_PASSWORD)
        val password64 = EncodeUtils.base64Encode2String(ACCOUNT_DEFAULT_PASSWORD.toByteArray())
        if (FileUtils.createOrExistsFile(currentAccountFilePath)) {
            Executors.newCachedThreadPool().execute {
                FileIOUtils.writeFileFromString(
                    currentAccountFilePath,
                    password64
                )
            }
        }
    }

    fun loadAccountPassword(context: AppCompatActivity, callback: AccountPasswordManageCallback?) {
        val accountPassword = getAccountPassword()
        if (TextUtils.isEmpty(accountPassword)) {
            PermissionX.init(context)
                .permissions(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                )
                .request { allGranted: Boolean, grantedList: List<String?>?, deniedList: List<String?>? ->
                    if (allGranted) {
                        initAccountPassword(context, callback)
                    } else {
                        ToastUtils.showShort("请检查权限后重试")
                    }
                }
        } else {
            callback?.onPasswordGet(accountPassword)
        }
    }

    val accountPassword: String
        get() = getAccountPassword()

    fun updateAccountPassword(password: String?) {
        if (TextUtils.isEmpty(password)) return
        setAccountPassword(password!!)
        if (FileUtils.isFileExists(currentAccountFilePath)) {
            FileUtils.deleteAllInDir(currentAccountFilePath)
        }
        if (FileUtils.createOrExistsFile(currentAccountFilePath)) {
            val password64 = EncodeUtils.base64Encode2String(password.toByteArray())
            Executors.newCachedThreadPool()
                .execute { FileIOUtils.writeFileFromString(currentAccountFilePath, password64) }
        }
    }
}