package com.pan_american.android.ui.group_invite_official.invite_data

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.OpenableColumns
import android.text.Editable
import android.text.TextWatcher
import android.util.Base64
import android.view.Gravity
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.PopupWindow
import android.widget.TextView
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseRequest
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.CardAdapter
import com.pan_american.android.base.CustomAlertDialog
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.FileListItem
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.network.SelectorResponse
import com.pan_american.android.data.model.customer_resource.company_customer.network.BusinessCardInfoRequest
import com.pan_american.android.data.model.customer_resource.company_customer.network.BusinessCardInfoResponse
import com.pan_american.android.data.model.group_invite_official.invite_data.network.InviteDataDetailResponse
import com.pan_american.android.data.model.group_invite_official.invite_data.network.UpdateInviteDetailRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddInviteDataBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.CommitButton
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.ByteArrayOutputStream
import java.io.File


class AddInviteDataActivity : BaseActivity<ActivityAddInviteDataBinding>() {

    private var fromList = false

    private var dataId = 0

    private lateinit var titleBinding: LayoutTitleBinding

    private val apiService = ServiceCreator.create<APIService>()

    private val groupList = ArrayList<Selector>()

    private val groupSelected = ArrayList<Selector>()

    private lateinit var groupNameAdapter: CardAdapter<Selector>

    private var updateInviteDataDetailRequest = UpdateInviteDetailRequest()

    //监听拍照事件回调
    private lateinit var getPhotoResult: ActivityResultLauncher<Intent>

    //名片识别，图片Uri
    private lateinit var imageUri: Uri

    //输出文件路径
    private lateinit var outputImage: File

    //识别后手机号可能存在多个
    private var telephoneOCR = ""

    //识别后电话号码可能存在多个
    private var phoneOCR = ""

    //识别后地址可能存在多行
    private var locationOCR = ""

    private var fileListItem = ArrayList<FileListItem>()

    private lateinit var fileListAdapter: CardAdapter<FileListItem>

    private lateinit var fileSelectResult: ActivityResultLauncher<Intent>

    override fun getViewBinding() = ActivityAddInviteDataBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        intent.apply {
            fromList = getBooleanExtra("from_list", false)
            dataId = getIntExtra("data_id", 0)
        }

        getPhotoResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == Activity.RESULT_OK) {

                telephoneOCR = ""
                phoneOCR = ""
                locationOCR = ""

                //调用OCR接口进行名片识别
                getBusinessCardInfo()
            }
        }

        fileSelectResult = registerForActivityResult(
            ActivityResultContracts.StartActivityForResult(),
            ActivityResultCallback { result ->
                if (result.resultCode == RESULT_OK) {
                    val data: Intent? = result.data
                    if (data != null) {
                        val selectedImageUri = data.data
                        if (selectedImageUri != null) {

                            fileListItem.add(FileListItem().apply {
                                fileName = File(getFileName(selectedImageUri)).name

                                if (fileName.isBlank()) {
                                    showMessage(resources.getString(R.string.file_select_error_hint))
                                    return@ActivityResultCallback
                                }

                                uri = selectedImageUri
                            })

                            initFileNameList()
                        }
                    }
                }
            })

        initTitle()

        getGroupNameList()
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            if (fromList) {
                titleText.text = resources.getString(R.string.invite_data_detail)
            } else {
                titleText.text = resources.getString(R.string.add_invite_data)

                rightTextField.visibility = View.VISIBLE
            }

            backButton.setOnClickListener {
                back()
            }
        }

        titleBinding.rightTextField.setOnClickListener {
            if (ContextCompat.checkSelfPermission(
                    OASystem.context, Manifest.permission.CAMERA
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this, arrayOf(Manifest.permission.CAMERA), OASystem.CAMERA_REQUEST_CODE
                )
            } else {
                startGetPhoto()
            }
        }
    }

    override fun initViews() {
        if (fromList) {

            getInviteDataDetail()

            binding.commit.setText(resources.getString(R.string.update))

            if (!OASystem.authorization(OASystem.INVITE_DATA, OASystem.EDIT)) {
                binding.apply {
                    country.isEnabled = false
                    city.isEnabled = false
                    inviteeName.isEnabled = false
                    inviteeWebsite.isEnabled = false
                    industry.isEnabled = false
                    inviteeLocation.isEnabled(false)
                    inviteeInfo.isEnabled(false)
                    inviteContacts.isEnabled = false
                    contactsJob.isEnabled = false
                    contactsPhone.isEnabled = false
                    contactsEmail.isEnabled = false
                    wechat.isEnabled = false
                    faceBook.isEnabled = false
                    instagram.isEnabled = false
                    contactsFax.isEnabled = false
                    add.visibility = View.GONE
                    otherInfo.isEnabled(false)

                    commit.setText(resources.getString(R.string.back))
                }
            }

        } else {

            binding.commit.setText(resources.getString(R.string.add))

        }

        initEvents()
    }

    override fun initEvents() {

        binding.add.setOnClickListener {
            val selectorList = ArrayList<Selector>()

            for (item in groupList) {
                selectorList.add(item)
            }

            val popView = View.inflate(OASystem.context, R.layout.popup_smart_refresh_selector, null)
            popupWindow = PopupWindow(popView, RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT)

            showPopupWindow {

                val searchView: LinearLayout = popView.findViewById(R.id.search_view)
                searchView.visibility = View.VISIBLE

                val searchText: EditText = popView.findViewById(R.id.search_text)

                selector = popView.findViewById(R.id.selector_list)

                selectorContainer = popView.findViewById(R.id.selector_refresh_container)
                selectorContainer.setEnableRefresh(false)
                selectorContainer.setEnableLoadMore(false)

                val layoutManager = LinearLayoutManager(OASystem.context)
                selector.layoutManager = layoutManager

                val adapter = ListAdapter.Builder<Selector>().apply {
                    setData(selectorList)
                    setLayoutId(R.layout.item_selector)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.groupName

                            if (groupSelected.contains(data)) {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color_blue, null))
                            } else {
                                setTextColor(ResourcesCompat.getColor(resources, R.color.text_color, null))
                            }
                        }
                    }
                }.create()

                selector.adapter = adapter

                adapter.onRecyclerViewItemClick =
                    object : ListAdapter.OnRecyclerViewItemClick<Selector> {
                        override fun onItemClick(position: Int) {
                            selectorList[position].apply {

                                if (groupSelected.contains(this)) {
                                    showMessage(resources.getString(R.string.association_group_selected_hint))
                                    return
                                } else {
                                    groupSelected.add(this)
                                    initGroupNameList()
                                }

                                popupWindow.dismiss()
                            }
                        }
                    }

                searchText.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                    }

                    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                    }

                    override fun afterTextChanged(editable: Editable?) {

                        adapter.notifyItemRangeRemoved(0, selectorList.size)

                        selectorList.clear()

                        if (editable.isNullOrBlank()) {

                            for (item in groupList) {
                                selectorList.add(item)
                            }

                        } else {
                            for (i in 0 until groupList.size) {
                                groupList[i].apply {
                                    if (groupName.contains(editable)) {
                                        selectorList.add(this)
                                    }
                                }
                            }
                        }

                        if (selectorList.size == 0) {
                            showMessage(resources.getString(R.string.no_data))
                        } else {
                            for (i in 0 until selectorList.size) {
                                adapter.notifyItemInserted(i)
                            }
                        }
                    }
                })

                popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
            }
        }

        binding.upload.setOnClickListener {
            openFileManager()
        }

        binding.commit.setOnClickListener {
            if (!OASystem.authorization(OASystem.INVITE_DATA, OASystem.EDIT)) {
                back()
                return@setOnClickListener
            }

            if (binding.country.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_country_input_hint))
                return@setOnClickListener
            } else {
                updateInviteDataDetailRequest.country = binding.country.text.toString()
            }

            if (binding.city.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_city_input_hint))
                return@setOnClickListener
            } else {
                updateInviteDataDetailRequest.city = binding.city.text.toString()
            }

            if (binding.inviteeName.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_name_hint))
                return@setOnClickListener
            } else {
                updateInviteDataDetailRequest.unitName = binding.inviteeName.text.toString()
            }

            if (binding.inviteeWebsite.text.isNotBlank()) {
                updateInviteDataDetailRequest.unitWeb = binding.inviteeWebsite.text.toString()
            }

            if (binding.industry.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_industry_input_hint))
                return@setOnClickListener
            } else {
                updateInviteDataDetailRequest.field = binding.industry.text.toString()
            }

            if (binding.inviteeLocation.getText().isBlank()) {
                showMessage(resources.getString(R.string.invitee_location_hint))
                return@setOnClickListener
            } else {
                updateInviteDataDetailRequest.address = binding.inviteeLocation.getText()
            }

            if (binding.inviteeInfo.getText().isNotBlank()) {
                updateInviteDataDetailRequest.unitInfo = binding.inviteeInfo.getText()
            }

            if (binding.inviteContacts.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.invitee_contacts_hint))
                return@setOnClickListener
            } else {
                updateInviteDataDetailRequest.contact = binding.inviteContacts.text.toString()
            }

            if (binding.contactsJob.text.isNotBlank()) {
                updateInviteDataDetailRequest.job = binding.contactsJob.text.toString()
            }

            if (binding.contactsPhone.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.contacts_tel_hint))
                return@setOnClickListener
            } else {
                updateInviteDataDetailRequest.tel = binding.contactsPhone.text.toString()
            }

            if (binding.contactsEmail.text.isNotBlank()) {
                updateInviteDataDetailRequest.email = binding.contactsEmail.text.toString()
            }

            if (binding.wechat.text.isNotBlank()) {
                updateInviteDataDetailRequest.weChat = binding.wechat.text.toString()
            }

            if (binding.faceBook.text.isNotBlank()) {
                updateInviteDataDetailRequest.faceBook = binding.faceBook.text.toString()
            }

            if (binding.instagram.text.isNotBlank()) {
                updateInviteDataDetailRequest.ins = binding.instagram.text.toString()
            }

            if (binding.contactsFax.text.isNotBlank()) {
                updateInviteDataDetailRequest.fax = binding.contactsFax.text.toString()
            }

            if (groupSelected.size > 0) {
                var i = 0

                var groupIdStr = ""

                while (i < groupSelected.size) {
                    groupIdStr += groupSelected[i].id

                    i++

                    if (i < groupSelected.size) {
                        groupIdStr += ","
                    }
                }

                updateInviteDataDetailRequest.delegation = groupIdStr
            }

            if (binding.otherInfo.getText().isNotBlank()) {
                updateInviteDataDetailRequest.remark = binding.otherInfo.getText()
            }

            if (fromList) {
                updateInviteDataDetailRequest.status = 2
            } else {
                updateInviteDataDetailRequest.status = 1
            }

            updateInviteData()
        }
    }

    private fun getGroupNameList() {
        apiService.getGroupNameList(BaseRequest()).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(
                call: Call<SelectorResponse>,
                response: Response<SelectorResponse>
            ) {
                val listResponse = response.body()

                if (listResponse != null) {
                    if (listResponse.code == 200) {

                        for (item in listResponse.data) {
                            groupList.add(item)
                        }

                        initViews()

                    } else {
                        showMessage(listResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<SelectorResponse>, t: Throwable) {
                showErrorInfo(R.string.group_name_list_get_failed)
            }
        })
    }

    private fun getInviteDataDetail() {

        apiService.getInviteDataDetailById(dataId).enqueue(object : Callback<InviteDataDetailResponse> {
            override fun onResponse(
                call: Call<InviteDataDetailResponse>,
                response: Response<InviteDataDetailResponse>
            ) {
                val detailResponse = response.body()

                if (detailResponse != null) {
                    if (detailResponse.code == 200) {

                        detailResponse.data.apply {

                            updateInviteDataDetailRequest.id = id
                            updateInviteDataDetailRequest.createUserId = OASystem.userInfo.userId

                            binding.country.setText(country)
                            binding.city.setText(city)
                            binding.inviteeName.setText(unitName)
                            binding.inviteeWebsite.setText(unitWeb)
                            binding.industry.setText(field)
                            binding.inviteeLocation.setText(address)
                            binding.inviteeInfo.setText(unitInfo)
                            binding.inviteContacts.setText(contact)
                            binding.contactsJob.setText(job)
                            binding.contactsPhone.setText(tel)
                            binding.contactsEmail.setText(email)
                            binding.wechat.setText(weChat)
                            binding.faceBook.setText(faceBook)
                            binding.instagram.setText(ins)

                            if (delegation.isNotBlank()) {
                                val groupIds = delegation.split(",")

                                for (checkedItem in groupIds) {
                                    for (item in groupList) {
                                        if (checkedItem.toInt() == item.id) {
                                            groupSelected.add(item)
                                        }
                                    }
                                }

                                initGroupNameList()
                            }

                            if (sndFilePathItem.size > 0) {

                                for (item in sndFilePathItem) {
                                    fileListItem.add(FileListItem().apply {
                                        fileName = item.substringAfterLast("/")
                                        url = item
                                        fromServer = true
                                    })
                                }

                                initFileNameList()

                            }

                            binding.contactsFax.setText(fax)
                            binding.otherInfo.setText(remark)
                        }

                    } else {
                        showMessage(detailResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<InviteDataDetailResponse>, t: Throwable) {
                showErrorInfo(R.string.invite_data_info_get_failed)
            }
        })
    }

    private fun initGroupNameList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.groupList.layoutManager = layoutManager

        groupNameAdapter = CardAdapter.Builder<Selector>().apply {
            setData(groupSelected)
            setLayoutId(R.layout.item_delete_button_selector)
            setCanDelete(OASystem.authorization(OASystem.INVITE_DATA, OASystem.EDIT))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.left_text).text = data.groupName
            }
        }.create()

        binding.groupList.adapter = groupNameAdapter

        groupNameAdapter.onRecyclerViewItemClick = object : CardAdapter.OnRecyclerViewItemClick<Selector> {
            override fun onItemClick(position: Int) {

            }

            override fun onItemDelete(position: Int) {
                CustomAlertDialog.Builder().apply {
                    setTitle(resources.getString(R.string.alert))
                    setMessage(String.format(resources.getString(R.string.delete_alert_text), groupSelected[position].groupName))
                    setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                        dialog.dismiss()
                    }
                    setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->
                        groupSelected.removeAt(position)
                        binding.groupList.adapter!!.notifyItemRemoved(position)
                        binding.groupList.adapter!!.notifyItemRangeChanged(position, groupSelected.size - position)
                    }
                }.show()
            }
        }
    }

    private fun initFileNameList() {
        val layoutManager = LinearLayoutManager(OASystem.context)
        binding.inviteDataFileList.layoutManager = layoutManager

        fileListAdapter = CardAdapter.Builder<FileListItem>().apply {
            setData(fileListItem)
            setLayoutId(R.layout.item_delete_button_selector)
            setCanDelete(OASystem.authorization(OASystem.INVITE_DATA, OASystem.EDIT))
            addBindView { itemView, data ->
                itemView.findViewById<TextView>(R.id.left_text).text = data.fileName
            }
        }.create()

        binding.inviteDataFileList.adapter = fileListAdapter

        fileListAdapter.onRecyclerViewItemClick = object : CardAdapter.OnRecyclerViewItemClick<FileListItem> {
            override fun onItemClick(position: Int) {

            }

            override fun onItemDelete(position: Int) {
                CustomAlertDialog.Builder().apply {
                    setTitle(resources.getString(R.string.alert))
                    if (fileListItem[position].fromServer) {
                        setMessage(String.format(resources.getString(R.string.file_uploaded_delete_hint), fileListItem[position].fileName))
                    } else {
                        setMessage(String.format(resources.getString(R.string.delete_alert_text), fileListItem[position].fileName))
                    }
                    setNegativeButtonAndListener(resources.getString(R.string.cancel)) { dialog, _ ->
                        dialog.dismiss()
                    }
                    setPositiveButtonAndListener(resources.getString(R.string.confirm)) { _, _ ->

                        if (fileListItem[position].fromServer) {

                            deleteFileFromServer(position)

                        } else {
                            fileListItem.removeAt(position)
                            binding.inviteDataFileList.adapter!!.notifyItemRemoved(position)
                            binding.inviteDataFileList.adapter!!.notifyItemRangeChanged(position, fileListItem.size - position)

                            showMessage(resources.getString(R.string.delete_success))
                        }

                    }
                }.show()
            }
        }
    }

    private fun deleteFileFromServer(position: Int) {

        apiService.deleteInviteDataFile(updateInviteDataDetailRequest.id, fileListItem[position].fileName).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {

                val deleteResponse = response.body()

                if (deleteResponse != null) {
                    if (deleteResponse.code == 200) {

                        fileListItem.removeAt(position)
                        binding.inviteDataFileList.adapter!!.notifyItemRemoved(position)
                        binding.inviteDataFileList.adapter!!.notifyItemRangeChanged(position, fileListItem.size - position)

                        showMessage(resources.getString(R.string.delete_success))

                    } else {
                        showMessage(deleteResponse.msg)
                    }
                }
            }

            override fun onFailure(p0: Call<BaseResponse>, p1: Throwable) {
                showErrorInfo(R.string.delete_error)
            }
        })
    }

    private fun updateInviteData() {

        binding.commit.setButtonStatus(CommitButton.STATUS_IN_COMMITING)

        val requestBody = MultipartBody.Builder().setType(MultipartBody.FORM).apply {
            addFormDataPart("Id", updateInviteDataDetailRequest.id.toString())
            addFormDataPart("Country", updateInviteDataDetailRequest.country)
            addFormDataPart("City", updateInviteDataDetailRequest.city)
            addFormDataPart("UnitName", updateInviteDataDetailRequest.unitName)
            addFormDataPart("UnitWeb", updateInviteDataDetailRequest.unitWeb)
            addFormDataPart("Field", updateInviteDataDetailRequest.field)
            addFormDataPart("Address", updateInviteDataDetailRequest.address)
            addFormDataPart("UnitInfo", updateInviteDataDetailRequest.unitInfo)
            addFormDataPart("Contact", updateInviteDataDetailRequest.contact)
            addFormDataPart("Job", updateInviteDataDetailRequest.job)
            addFormDataPart("Tel", updateInviteDataDetailRequest.tel)
            addFormDataPart("Email", updateInviteDataDetailRequest.email)
            addFormDataPart("WeChat", updateInviteDataDetailRequest.weChat)
            addFormDataPart("FaceBook", updateInviteDataDetailRequest.faceBook)
            addFormDataPart("Ins", updateInviteDataDetailRequest.ins)
            addFormDataPart("Delegation", updateInviteDataDetailRequest.delegation)
            addFormDataPart("Fax", updateInviteDataDetailRequest.fax)
            addFormDataPart("Remark", updateInviteDataDetailRequest.remark)
            addFormDataPart("Status", updateInviteDataDetailRequest.status.toString())
            addFormDataPart("CreateUserId", updateInviteDataDetailRequest.createUserId.toString())
            for (item in fileListItem) {
                if (!item.fromServer) {
                    val file = contentResolver.openInputStream(item.uri)!!
                    val fileRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file.readBytes())
                    addFormDataPart("Files", item.fileName, fileRequestBody)
                    file.close()
                }
            }
        }.build()

        apiService.updateInviteData(requestBody).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {

                val updateResponse = response.body()

                if (updateResponse != null) {
                    if (updateResponse.code == 200) {

                        if (fromList) {
                            showMessage(resources.getString(R.string.update_success))
                        } else {
                            showMessage(resources.getString(R.string.insert_success))
                        }

                        OASystem.needRefresh = true

                        back()

                    } else {

                        binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)

                        showMessage(updateResponse.msg)
                    }
                }

            }

            override fun onFailure(call: Call<BaseResponse>, t: Throwable) {

                binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)

                showErrorInfo(R.string.update_error)
            }
        })
    }

    private fun startGetPhoto() {
        //创建File对象，用于存储拍照后的图片
        outputImage = File(externalCacheDir, "output_image.jpg")

        if (outputImage.exists()) {
            outputImage.delete()
        }

        outputImage.createNewFile()
        imageUri =
            FileProvider.getUriForFile(this, "com.pan_american.android.file_provider", outputImage)

        //启动相机程序
        val intent = Intent("android.media.action.IMAGE_CAPTURE")
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        getPhotoResult.launch(intent)
    }

    private fun getBusinessCardInfo() {

        var base64Adjusted = false

        var bitmapSampleSize = 2

        var bitmapQuality = 100

        val byteArrayOutputStream = ByteArrayOutputStream()

        var transferBase64: String

        do {
            val options = BitmapFactory.Options()
            options.inSampleSize = bitmapSampleSize

            val bitmap =
                BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri), null, options)

            bitmap!!.compress(Bitmap.CompressFormat.JPEG, bitmapQuality, byteArrayOutputStream)

            transferBase64 =
                Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.NO_WRAP)

            if (transferBase64.length < 1024 * 1024 * 2) {
                if (transferBase64.length < 1024 * 1024) {
                    base64Adjusted = true
                    byteArrayOutputStream.close()
                } else {
                    bitmapQuality -= 10
                }
            } else {
                bitmapSampleSize *= 2
            }
            byteArrayOutputStream.reset()
            bitmap.recycle()
        } while (!base64Adjusted)

        apiService.getBusinessCardInfo(BusinessCardInfoRequest(transferBase64))
            .enqueue(object : Callback<BusinessCardInfoResponse> {

                override fun onResponse(
                    call: Call<BusinessCardInfoResponse>,
                    response: Response<BusinessCardInfoResponse>
                ) {
                    val infoResponse = response.body()

                    if (infoResponse != null) {

                        if (infoResponse.code == 200) {

                            infoResponse.data.businessCardInfos.forEach {
                                when (it.name) {
                                    "姓名" -> {
                                        binding.inviteContacts.setText(it.value)
                                    }

                                    "手机" -> {
                                        telephoneOCR += if (telephoneOCR.isEmpty()) {
                                            it.value
                                        } else {
                                            " ,${it.value}"
                                        }
                                    }

                                    "电话" -> {
                                        phoneOCR += if (phoneOCR.isEmpty()) {
                                            it.value
                                        } else {
                                            " ,${it.value}"
                                        }
                                    }

                                    "邮箱" -> {
                                        binding.contactsEmail.setText(it.value)
                                    }

                                    "职位" -> {
                                        binding.contactsJob.setText(it.value)
                                    }

                                    "公司" -> {
                                        binding.inviteeName.setText(it.value)
                                    }

                                    "地址" -> {
                                        locationOCR += it.value
                                    }
                                }
                            }

                            if (telephoneOCR.isNotBlank()) {
                                binding.contactsPhone.setText(telephoneOCR)
                            } else {
                                binding.contactsPhone.setText(phoneOCR)
                            }

                            binding.inviteeLocation.setText(locationOCR)

                            outputImage.delete()

                        } else {
                            showMessage(infoResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<BusinessCardInfoResponse>, t: Throwable) {
                    showMessage("网络错误，请检查网络设置")
                }
            })
    }

    private fun getFileName(uri: Uri): String {
        var fileName = ""
        val projection = arrayOf(OpenableColumns.DISPLAY_NAME)
        contentResolver.query(uri, projection, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val columnIndex =
                    cursor.getColumnIndexOrThrow(OpenableColumns.DISPLAY_NAME)
                fileName = cursor.getString(columnIndex)
            }
        }

        return fileName
    }

    private fun openFileManager() {
        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.setType("*/*") // Use specific MIME type if you know the file type (e.g., "text/plain" for .txt files)

        fileSelectResult.launch(intent)
    }
}