package com.miya.fastcashier.utils.manage

import android.Manifest
import android.os.Environment
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.FileIOUtils
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ToastUtils
import com.miya.fastcashier.service.AccountService.getAccountPassword
import com.miya.fastcashier.service.AccountService.getUserName
import com.miya.fastcashier.service.AccountService.setAccountPassword
import com.permissionx.guolindev.PermissionX
import java.util.concurrent.Executors

/**
 * 类描述：账户管理员密码管理
 * 概述：
 * 创建人：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 password = FileIOUtils.readFile2String(
                    currentAccountFilePath
                )
                setAccountPassword(password)
                context.runOnUiThread { callback?.onPasswordGet(password) }
            }
            return
        }
        setAccountPassword(ACCOUNT_DEFAULT_PASSWORD)
        callback?.onPasswordGet(ACCOUNT_DEFAULT_PASSWORD)
        if (FileUtils.createOrExistsFile(currentAccountFilePath)) {
            Executors.newCachedThreadPool().execute {
                FileIOUtils.writeFileFromString(
                    currentAccountFilePath,
                    ACCOUNT_DEFAULT_PASSWORD
                )
            }
        }
    }

    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)) {
            Executors.newCachedThreadPool()
                .execute { FileIOUtils.writeFileFromString(currentAccountFilePath, password) }
        }
    }
}