package com.pan_american.android.ui.customer_resource.company_customer

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.util.Base64
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.PopupWindow
import android.widget.TextView
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.StaggeredGridLayoutManager
import com.google.gson.Gson
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.BaseResponse
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.entity.SiftListItem
import com.pan_american.android.data.model.common.network.SelectorResponse
import com.pan_american.android.data.model.customer_resource.company_customer.entity.MarketCustomer
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.customer_resource.company_customer.network.MarketCustomerDetailRequest
import com.pan_american.android.data.model.customer_resource.company_customer.network.MarketCustomerDetailResponse
import com.pan_american.android.data.model.customer_resource.company_customer.network.UpdateClientTypeRequest
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityAddNewCustomerBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.pan_american.android.util.CommitButton
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileWriter

class AddNewCustomerActivity : BaseActivity<ActivityAddNewCustomerBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private var fromList = false

    private var id = 0

    private lateinit var marketCustomer: MarketCustomer

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

    private lateinit var popView: View

    //客户级别
    private var customerLevel = ArrayList<Selector>()

    //客户类别
    private var customerClass = ArrayList<Selector>()

    //负责人
    private var customerManager = ArrayList<SiftListItem>()

    //业务归属
    private var customerServiceClass = ArrayList<SiftListItem>()

    //负责人 id列表
    private var customerManagerList = ArrayList<Int>()

    //业务归属 id列表
    private var customerServiceClassList = ArrayList<Int>()

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

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

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

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

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

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

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

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

        intent.apply {
            fromList = getBooleanExtra("fromList", false)
        }

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

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

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

        initTitle()

        //先获取级别、类别、负责人、业务归属标识
        initSelectorItem()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == OASystem.CAMERA_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startGetPhoto()
            } else {
                showMessage(resources.getString(R.string.camera_permission_hint))
            }
        }
    }

    override fun initTitle() {

        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            if (fromList) {
                titleText.text = resources.getString(R.string.market_customer_resource_detail)
            } else {
                rightTextField.visibility = View.VISIBLE
                titleText.text = resources.getString(R.string.add_market_customer_resource)
            }

            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) {

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

            id = intent.getIntExtra("id", 0)

            initMarketCustomerInfo()

            if (!OASystem.authorization(OASystem.MARKET_CUSTOMER, OASystem.EDIT)) {
                binding.apply {
                    customerLevel.isEnabled = false
                    customerClassify.isEnabled = false
                    weight.isEnabled = false
                    customerName.isEnabled = false
                    male.isEnabled = false
                    female.isEnabled = false
                    customerPhoneNumber.isEnabled = false
                    customerTelephone.isEnabled = false
                    customerEmail.isEnabled = false
                    wechat.isEnabled = false
                    customerJob.isEnabled = false
                    departmentName.isEnabled = false
                    departmentNameAbbr.isEnabled = false
                    customerCity.isEnabled = false
                    customerLocation.isEnabled(false)
                    passportCode.isEnabled = false
                    passportDeadline.isEnabled = false
                    customerBirthday.isEnabled = false
                    customerEstimate.isEnabled = false
                    customerFinished.isEnabled = false
                    customerLeader.isEnabled = false
                    businessCategory.isEnabled = false
                    notes.isEnabled(false)

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

        } else {
            binding.commit.setText(resources.getString(R.string.add))

            for (item in customerManager) {
                if (item.id == OASystem.userInfo.userId) {

                    customerManagerList.add(item.id)

                    item.isChecked = true

                    binding.customerLeader.text = item.name
                }
            }

            marketCustomer = MarketCustomer()
        }
    }

    override fun initEvents() {

        binding.customerLevel.setOnClickListener {
            initCustomerLevelSelector()
        }

        binding.customerClassify.setOnClickListener {
            if (marketCustomer.lvlid == 0) {
                showMessage(resources.getString(R.string.customer_level_select_hint))
            } else {
                initCustomerClassifySelector()
            }
        }

        binding.customerLeader.setOnClickListener {
            initCustomerManagerList()
        }

        binding.businessCategory.setOnClickListener {
            initCustomerServiceClassSift()
        }

        binding.weight.setOnClickListener {
            showSelector {
                val adapter = ListAdapter.Builder<Selector>().apply {
                    setLayoutId(R.layout.item_selector)
                    setData(OASystem.weight)
                    addBindView { itemView, data ->
                        itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                            text = data.name

                            if (marketCustomer.weight == data.name) {
                                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) {

                            OASystem.weight[position].apply {
                                binding.weight.text = name
                                marketCustomer.weight = id.toString()
                            }

                            popupWindow.dismiss()
                        }
                    }
            }
        }

        binding.passportDeadline.setOnClickListener {
            showDatePicker(resources.getString(R.string.passport_lifespan), binding.passportDeadline)
        }

        binding.customerBirthday.setOnClickListener {
            showDatePicker(resources.getString(R.string.birthday), binding.customerBirthday)
        }

        binding.commit.setOnClickListener {

            if (!OASystem.authorization(OASystem.MARKET_CUSTOMER, OASystem.EDIT)) {
                back()
                return@setOnClickListener
            }

            if (fromList) {
                initAndUpdateMarketCustomer(2)
            } else {
                initAndUpdateMarketCustomer(1)
            }
        }
    }

    private fun initSelectorItem() {
        for (item in OASystem.customerManager) {
            item.isChecked = false
            customerManager.add(item)
        }

        for (item in OASystem.customerLevel) {
            item.isChecked = false
            customerLevel.add(item)
        }

        for (item in OASystem.serviceClass) {
            item.isChecked = false
            customerServiceClass.add(item)
        }

        initViews()
        initEvents()
    }

    private fun initMarketCustomerInfo() {
        apiService.getMarketCustomerDetailById(MarketCustomerDetailRequest(id))
            .enqueue(object : Callback<MarketCustomerDetailResponse> {
                override fun onResponse(
                    call: Call<MarketCustomerDetailResponse>,
                    response: Response<MarketCustomerDetailResponse>
                ) {
                    val detailResponse = response.body()

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

                            marketCustomer = detailResponse.data

                            binding.apply {
                                run {
                                    for (item in OASystem.customerLevel) {
                                        if (marketCustomer.lvlid == item.id) {
                                            customerLevel.text = item.name
                                            return@run
                                        }
                                    }
                                }

                                run {
                                    for (item in OASystem.customerClass) {
                                        if (marketCustomer.category == item.id) {
                                            customerClassify.text = item.name
                                            return@run
                                        }
                                    }
                                }

                                if (marketCustomer.weight.isNotBlank()) {   //老数据未选择权重避免闪退
                                    run {
                                        for (item in OASystem.weight) {
                                            if (marketCustomer.weight.toInt() == item.id) {
                                                weight.text = item.name
                                                return@run
                                            }
                                        }
                                    }
                                }

                                customerName.setText(marketCustomer.contact)

                                when (marketCustomer.gender) {
                                    0 -> {
                                        binding.male.isChecked = true
                                    }

                                    1 -> {
                                        binding.female.isChecked = true
                                    }
                                }

                                customerPhoneNumber.setText(marketCustomer.telephone)
                                customerTelephone.setText(marketCustomer.phone)
                                customerEmail.setText(marketCustomer.email)
                                wechat.setText(marketCustomer.weChat)
                                customerJob.setText(marketCustomer.job)
                                departmentName.setText(marketCustomer.client)
                                departmentNameAbbr.setText(marketCustomer.clientShort)
                                customerCity.setText(marketCustomer.location)
                                customerLocation.setText(marketCustomer.address)
                                passportCode.setText(marketCustomer.passport)
                                passportDeadline.text = marketCustomer.passportDate
                                customerBirthday.text = marketCustomer.birthday
                                customerEstimate.setText(marketCustomer.predele.toString())
                                customerFinished.setText(marketCustomer.finlishedDele.toString())

                                if (marketCustomer.ascribedUser.size != 0) {

                                    var managerText = ""

                                    marketCustomer.ascribedUser.forEach {
                                        for (item in customerManager) {
                                            if (it == item.id) {
                                                item.isChecked = true
                                                customerManagerList.add(it)
                                                managerText += "\t${item.name}"
                                            }
                                        }
                                    }

                                    binding.customerLeader.text = managerText
                                }

                                if (marketCustomer.ascribedDepartment.size != 0) {

                                    var serviceText = ""

                                    marketCustomer.ascribedDepartment.forEach {
                                        for (item in customerServiceClass) {
                                            if (it == item.id) {
                                                item.isChecked = true
                                                customerServiceClassList.add(it)
                                                serviceText += "\t${item.name}"
                                            }
                                        }
                                    }

                                    binding.businessCategory.text = serviceText
                                }

                                notes.setText(marketCustomer.remark)
                            }

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

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

    private fun initCustomerLevelSelector() {
        showSelector {
            val adapter = ListAdapter.Builder<Selector>().apply {
                setData(customerLevel)
                setLayoutId(R.layout.item_selector)
                addBindView { itemView, data ->
                    itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                        text = data.name

                        if (marketCustomer.lvlid == data.id) {
                            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) {

                        binding.customerLevel.text = customerLevel[position].name
                        marketCustomer.lvlid = customerLevel[position].id

                        binding.customerClassify.text = ""
                        marketCustomer.category = 0

                        customerClass.clear()
                        getCustomerClassWithLevelId(marketCustomer.lvlid)

                        popupWindow.dismiss()
                    }
                }
        }
    }

    private fun initCustomerClassifySelector() {
        showSelector {
            val adapter = ListAdapter.Builder<Selector>().setData(customerClass)
                .setLayoutId(R.layout.item_selector).addBindView { itemView, data ->
                    itemView.findViewById<TextView>(R.id.selector_item_name).apply {
                        text = data.name

                        if (marketCustomer.category == data.id) {
                            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) {

                        binding.customerClassify.text = customerClass[position].name
                        marketCustomer.category = customerClass[position].id

                        popupWindow.dismiss()
                    }
                }
        }
    }

    private fun initSiftListPopupWindow(block: () -> Unit) {
        popView = View.inflate(this, R.layout.popup_multi_item_selector, null)
        popupWindow = PopupWindow(
            popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )

        showPopupWindow {

            //初始化RecyclerView
            selector = popView.findViewById(R.id.selector_list)

            block()

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

    private fun initCustomerManagerList() {
        initSiftListPopupWindow {

            val adapter = ListAdapter.Builder<SiftListItem>().setData(customerManager)
                .setLayoutId(R.layout.item_customer_sift).addBindView { itemView, data ->

                    itemView.findViewById<CheckedTextView>(R.id.customer_sift).apply {
                        isChecked = data.isChecked
                        text = data.name
                    }

                }.create()

            val layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)

            selector.layoutManager = layoutManager
            selector.adapter = adapter

            adapter.onRecyclerViewItemClick =
                object : ListAdapter.OnRecyclerViewItemClick<SiftListItem> {
                    override fun onItemClick(position: Int) {

                        customerManager[position].apply {

                            if (isChecked) {
                                isChecked = false

                                run {
                                    for ((count, item) in customerManagerList.withIndex()) {
                                        if (item == id) {
                                            customerManagerList.removeAt(count)
                                            return@run
                                        }
                                    }
                                }

                            } else {
                                isChecked = true
                                customerManagerList.add(id)
                            }

                            adapter.notifyItemChanged(position)

                            if (customerManagerList.size == 0) {
                                binding.customerLeader.text =
                                    resources.getString(R.string.please_select)
                            } else {
                                var managerNames = ""

                                customerManagerList.forEach {
                                    for (item in customerManager) {
                                        if (it == item.id) {
                                            managerNames += "\t${item.name}"
                                        }
                                    }
                                }

                                binding.customerLeader.text = managerNames
                            }
                        }
                    }
                }

            popView.findViewById<TextView>(R.id.commit).setOnClickListener {
                popupWindow.dismiss()
            }
        }
    }

    private fun initCustomerServiceClassSift() {
        initSiftListPopupWindow {
            val adapter = ListAdapter.Builder<SiftListItem>().setData(customerServiceClass)
                .setLayoutId(R.layout.item_customer_sift).addBindView { itemView, data ->

                    itemView.findViewById<CheckedTextView>(R.id.customer_sift).apply {
                        isChecked = data.isChecked
                        text = data.name
                    }

                }.create()

            val layoutManager = StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL)

            selector.layoutManager = layoutManager
            selector.adapter = adapter

            adapter.onRecyclerViewItemClick =
                object : ListAdapter.OnRecyclerViewItemClick<SiftListItem> {
                    override fun onItemClick(position: Int) {

                        customerServiceClass[position].apply {

                            if (isChecked) {
                                isChecked = false

                                run {
                                    for ((count, item) in customerServiceClassList.withIndex()) {
                                        if (item == id) {
                                            customerServiceClassList.removeAt(count)
                                            return@run
                                        }
                                    }
                                }

                            } else {
                                isChecked = true
                                customerServiceClassList.add(id)
                            }

                            adapter.notifyItemChanged(position)

                            if (customerServiceClassList.size == 0) {
                                binding.businessCategory.text =
                                    resources.getString(R.string.please_select)
                            } else {
                                var serviceClasses = ""

                                customerServiceClassList.forEach {
                                    for (item in customerServiceClass) {
                                        if (it == item.id) {
                                            serviceClasses += "\t${item.name}"
                                        }
                                    }
                                }

                                binding.businessCategory.text = serviceClasses
                            }
                        }
                    }
                }

            popView.findViewById<TextView>(R.id.commit).setOnClickListener {
                popupWindow.dismiss()
            }
        }
    }

    private fun initAndUpdateMarketCustomer(type: Int) {

        when {
            marketCustomer.lvlid == 0 -> {
                showMessage(resources.getString(R.string.customer_level_select_hint))
                return
            }

            marketCustomer.category == 0 -> {
                showMessage(resources.getString(R.string.customer_classification_select_hint))
                return
            }

            marketCustomer.weight.isEmpty() -> {
                showMessage(resources.getString(R.string.weight_select_hint))
                return
            }

            binding.customerName.text.toString().trim().isEmpty() -> {
                showMessage(resources.getString(R.string.connector_name_input_hint))
                return
            }

            binding.customerPhoneNumber.text.toString().trim().isEmpty() -> {
                showMessage(resources.getString(R.string.connector_phone_input_hint))
                return
            }

            binding.customerJob.text.toString().trim().isEmpty() -> {
                showMessage(resources.getString(R.string.connector_job_input_hint))
                return
            }

            binding.departmentName.text.toString().isEmpty() -> {
                showMessage(resources.getString(R.string.connector_department_input_hint))
                return
            }

            binding.customerCity.text.toString().trim().isEmpty() -> {
                showMessage(resources.getString(R.string.connector_city_input_hint))
                return
            }
        }

        marketCustomer.apply {
            contact = binding.customerName.text.toString()

            when (binding.gender.checkedRadioButtonId) {
                binding.male.id -> {
                    gender = 0
                }

                binding.female.id -> {
                    gender = 1
                }
            }

            telephone = binding.customerPhoneNumber.text.toString()
            phone = binding.customerTelephone.text.toString()
            email = binding.customerEmail.text.toString()
            weChat = binding.wechat.text.toString()
            job = binding.customerJob.text.toString()
            client = binding.departmentName.text.toString()
            clientShort = binding.departmentNameAbbr.text.toString()
            location = binding.customerCity.text.toString()
            address = binding.customerLocation.getText()
            passport = binding.passportCode.text.toString()
            passportDate = binding.passportDeadline.text.toString()
            birthday = binding.customerBirthday.text.toString()

            if (binding.customerEstimate.text.toString().trim().isNotEmpty()) {
                predele = binding.customerEstimate.text.toString().toInt()
            }

            if (binding.customerFinished.text.toString().trim().isNotEmpty()) {
                finlishedDele = binding.customerFinished.text.toString().toInt()
            }

            if (customerManagerList.size == 0) {
                showMessage(resources.getString(R.string.director_select_hint))
                return
            } else {
                ascribedUser = customerManagerList
            }

            if (customerServiceClassList.size == 0) {
                showMessage(resources.getString(R.string.business_ownership_select_hint))
                return
            } else {
                ascribedDepartment = customerServiceClassList
            }

            remark = binding.notes.getText()

            status = type

            updateMarketCustomerInfo()
        }
    }

    private fun updateMarketCustomerInfo() {

        binding.commit.setButtonStatus(CommitButton.STATUS_IN_COMMITING)

        apiService.newClientOperation(marketCustomer).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val baseResponse = response.body()
                if (baseResponse != null) {
                    if (baseResponse.code == 200) {
                        if (!fromList) {
                            showMessage(resources.getString(R.string.insert_success))
                        } else {
                            showMessage(resources.getString(R.string.update_success))
                        }

                        OASystem.needRefresh = true

                        back()

                    } else {
                        showMessage(baseResponse.msg)

                        binding.commit.setButtonStatus(CommitButton.STATUS_COMMITTED)
                    }
                }
            }

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

                binding.commit.setButtonStatus(0)

                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)
        result.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)

        val file = File(filesDir, "data.txt")
        if (file.exists()) {
            file.delete()
        }
        file.createNewFile()
        val writer = FileWriter(file)
        writer.append(Gson().toJson(BusinessCardInfoRequest(transferBase64)))
        writer.flush()
        writer.close()

        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.customerName.setText(it.value)
                                    }

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

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

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

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

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

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

                            binding.customerPhoneNumber.setText(telephoneOCR)
                            binding.customerTelephone.setText(phoneOCR)
                            binding.customerLocation.setText(locationOCR)

                            outputImage.delete()

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

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

    private fun getCustomerClassWithLevelId(position: Int) {
        apiService.updateClientTypeList(UpdateClientTypeRequest(listOf(position))).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(call: Call<SelectorResponse>, response: Response<SelectorResponse>) {
                val selectorResponse = response.body()

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

                        for (item in selectorResponse.data) {
                            customerClass.add(item)
                        }

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

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