package com.yidian.shenghuoquan.bmanagercenter.ui.auth

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.text.InputFilter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yidian.bcommon.base.BaseFragment
import com.yidian.bcommon.constant.GlobalConstants
import com.yidian.bcommon.utils.ImageCompressUtils
import com.yidian.framework.mobile.insight.manage.XInsight
import com.yidian.framework.mobile.insight.ocr.BusinessLicenseCallBack
import com.yidian.framework.mobile.insight.ocr.BusinessLicenseResult
import com.yidian.shenghuoquan.bmanagercenter.R
import com.yidian.shenghuoquan.bmanagercenter.adapter.BottomSelectAdapter
import com.yidian.shenghuoquan.bmanagercenter.bean.BottomSelectBean
import com.yidian.shenghuoquan.bmanagercenter.constant.Constant
import com.yidian.shenghuoquan.bmanagercenter.databinding.FragmentLifeAccountBusinessLicenseAuthBinding
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.bmanagercenter.ui.dialog.BottomSelectDialog
import com.yidian.shenghuoquan.bmanagercenter.utils.BitmapUtil
import com.yidian.shenghuoquan.bmanagercenter.utils.FileUtil
import com.yidian.bcommon.utils.InputFilterUtil
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountAuthBusinessInfoEditView
import com.yidian.utils.ToastUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * author: yinjiacheng
 * date: 7/15/21 7:38 PM
 * description: 生活号认证 营业执照认证 接入XInsight
 */
class LifeAccountBusinessLicenseAuthFragmentV2 :
  BaseFragment<FragmentLifeAccountBusinessLicenseAuthBinding>(), View.OnClickListener,
  BottomSelectAdapter.OnItemClickListener<BottomSelectBean>,
  LifeAccountAuthBusinessInfoEditView.OnLifeAccountAuthBusinessInfoEditViewCallback, BusinessLicenseCallBack {

  companion object {
    // 认证数据
    const val EXTRA_AUTH_DATA = "authData"
  }

  /**
   * sdcard/Android/data/package/cache
   */
  private val commonPath by lazy { activity?.externalCacheDir?.absolutePath }

  /**
   * 调用系统相机拍照，照片保存位置的Uri
   */
  private var photoUri: Uri? = null

  override fun createViewBinding(
    inflater: LayoutInflater,
    container: ViewGroup?
  ): FragmentLifeAccountBusinessLicenseAuthBinding {
    return FragmentLifeAccountBusinessLicenseAuthBinding.inflate(inflater, container, false)
  }

  override fun init(savedInstanceState: Bundle?) {
    super.init(savedInstanceState)
    initView()
    initListener()
    initData()
  }

  private fun initView() {
    // 输入过滤
    // 企业名称限制40汉字
    viewBinding.evRegistrationName.setInputFilters(InputFilterUtil.getRegistrationNameFilter(), InputFilter.LengthFilter(40))
    // 统一信用代码限制18位数字+大小写英文字母 小写字母自动转换大写字母
    viewBinding.evRegistrationCode.setInputFilters(
      InputFilterUtil.getRegistrationCodeFilter(),
      InputFilter.LengthFilter(18),
      InputFilter.AllCaps()
    )
  }


  private fun initListener() {
    viewBinding.clBusinessLicenseUpload.setOnClickListener(this)
    viewBinding.ivClear.setOnClickListener(this)
    viewBinding.evRegistrationName.setOnLifeAccountAuthBusinessInfoEditViewCallback(this)
    viewBinding.evRegistrationCode.setOnLifeAccountAuthBusinessInfoEditViewCallback(this)
  }

  private fun initData() {
    // 还原认证数据
    val authData =
      arguments?.getSerializable(EXTRA_AUTH_DATA) ?: return
    fillAuthInfo(authData as AuthMerchantCheckBean.Response)
  }

  /**
   * 认证流程中断，下次进入认证流程时还原进度
   */
  private fun fillAuthInfo(data: AuthMerchantCheckBean.Response) {
    // 营业执照区域
    Glide.with(this).load(data.entterprise_image_url).into(viewBinding.ivBusinessLicense)
    viewBinding.ivClear.isVisible = true
    viewBinding.clBusinessLicenseUpload.isEnabled = false
    // 填入注册名称和注册码
    viewBinding.evRegistrationName.fillEditContent(data.name)
    viewBinding.evRegistrationCode.fillEditContent(data.code)
    // 检查下一步条件
    (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.cl_business_license_upload -> {
        // 弹出上传方式选择
        context?.let {
          BottomSelectDialog(
            it,
            this,
            arrayListOf(
              BottomSelectBean(Constant.ITEM_TAKE_PHOTO),
              BottomSelectBean(Constant.ITEM_OPEN_ALBUM)
            )
          ).show()
        }
      }
      R.id.iv_clear -> {
        clearBusinessLicenseInfo()
        // 检查下一步条件
        (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
      }
    }
  }

  override fun onItemClick(view: View, position: Int, data: BottomSelectBean) {
    when (data.item) {
      Constant.ITEM_TAKE_PHOTO -> {
        // 调用系统相机进行营业执照采集
        val file = File(commonPath + Constant.FILE_PATH_BUSINESS_LICENSE_CAMERA)
        if (file.exists()) file.delete()
        if (file.parentFile?.exists() == false) file.parentFile?.mkdirs()
        file.createNewFile()
        photoUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
          //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
          activity?.let {
            FileProvider.getUriForFile(
              it,
              GlobalConstants.AUTHORITY,
              file
            )
          }
        } else {
          Uri.fromFile(file)
        }
        // 判断camera权限
        RxPermissions(this).request(Manifest.permission.CAMERA).subscribe {
          if (it) {
            startActivityForResult(
              Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
                MediaStore.EXTRA_OUTPUT,
                photoUri
              ),
              Constant.REQUEST_CODE_OPEN_CAMERA
            )
          } else {
            ToastUtil.showToast(activity, "请在设置里同意相关权限")
          }
        }
      }
      Constant.ITEM_OPEN_ALBUM -> {
        // 打开系统相册
        startActivityForResult(
          Intent(Intent.ACTION_PICK).setDataAndType(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            "image/*"
          ),
          Constant.REQUEST_CODE_OPEN_ALBUM
        )
      }
    }
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == Activity.RESULT_OK) {
      lifecycleScope.launch(Dispatchers.Main) {
        val uri = if (requestCode == Constant.REQUEST_CODE_OPEN_ALBUM) data?.data else photoUri
        var bitmap: Bitmap?
        withContext(Dispatchers.IO) {
          bitmap = BitmapUtil.generateBitmapFromUri(activity, uri, viewBinding.ivBusinessLicense)
        }
        viewBinding.ivBusinessLicense.setImageBitmap(bitmap)
        // 显示清除按钮
        viewBinding.ivClear.visibility = View.VISIBLE
        // 上传区域不可点击
        viewBinding.clBusinessLicenseUpload.isEnabled = false
        withContext(Dispatchers.IO) {
          FileUtil.generateFileFromUri(activity, uri, commonPath + Constant.FILE_PATH_BUSINESS_LICENSE)
        }
        // 删除从相机拍摄的照片
        if (requestCode == Constant.REQUEST_CODE_OPEN_CAMERA) File(commonPath + Constant.FILE_PATH_BUSINESS_LICENSE_CAMERA).delete()
        // 执行营业执照OCR
        startBusinessLicenseOCR()
      }
    }
  }

  /**
   * 执行营业执照OCR
   */
  private fun startBusinessLicenseOCR() {
    // 上传前压缩图像
    lifecycleScope.launch {
      activity?.let {
        ImageCompressUtils.compress(
          it,
          File(commonPath + Constant.FILE_PATH_BUSINESS_LICENSE),
          File(commonPath + Constant.FILE_PATH_BUSINESS_LICENSE),
          Constant.COMPRESS_DEST_WIDTH, Constant.COMPRESS_DEST_HEIGHT, Constant.COMPRESS_DEST_QUALITY
        )
      }
      XInsight.getBusinessLicenseOcrInfo(
        File(commonPath + Constant.FILE_PATH_BUSINESS_LICENSE),
        this@LifeAccountBusinessLicenseAuthFragmentV2
      )
    }
  }

  /**
   * 清除已输入的营业执照相关信息
   * 用户更换商户类型操作
   */
  fun clearBusinessLicenseInfo() {
    // 清除已上传的营业执照
    viewBinding.ivBusinessLicense.setImageDrawable(null)
    // 清除错误提示
    viewBinding.tvUploadErrorTips.isVisible = false
    activity?.let { viewBinding.viewBusinessLicenseUploadDivider.setBackgroundColor(ContextCompat.getColor(it, R.color.color_FFF2F2F2)) }
    viewBinding.ivClear.isVisible = false
    // 清除OCR或用户输入内容
    viewBinding.evRegistrationName.clearEditContent()
    viewBinding.evRegistrationCode.clearEditContent()
    // 设置上传区域可点击
    viewBinding.clBusinessLicenseUpload.isEnabled = true
    LifeAccountAuthDataManagerV2.merchantAuthData.isBusinessLicenseUpload = false
    LifeAccountAuthDataManagerV2.merchantAuthData.registrationName = null
    LifeAccountAuthDataManagerV2.merchantAuthData.registrationCode = null
    // 标识修改
    LifeAccountAuthDataManagerV2.merchantAuthData.isAuthInfoModify = true
  }

  override fun onTextClear(from: LifeAccountAuthBusinessInfoEditView) {
    // 标识修改
    LifeAccountAuthDataManagerV2.merchantAuthData.isAuthInfoModify = true
    if (from == viewBinding.evRegistrationName) {
      LifeAccountAuthDataManagerV2.merchantAuthData.registrationName = ""
    } else {
      LifeAccountAuthDataManagerV2.merchantAuthData.registrationCode = ""
    }
    // 检查下一步条件
    (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
  }

  override fun onTextChange(from: LifeAccountAuthBusinessInfoEditView, text: String) {
    if (from == viewBinding.evRegistrationName) {
      // 标识修改
      if (text != LifeAccountAuthDataManagerV2.merchantAuthData.registrationName) {
        LifeAccountAuthDataManagerV2.merchantAuthData.isAuthInfoModify = true
      }
      LifeAccountAuthDataManagerV2.merchantAuthData.registrationName = text
    } else {
      if (text != LifeAccountAuthDataManagerV2.merchantAuthData.registrationCode) {
        LifeAccountAuthDataManagerV2.merchantAuthData.isAuthInfoModify = true
      }
      LifeAccountAuthDataManagerV2.merchantAuthData.registrationCode = text
    }
    // 检查下一步条件
    (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
  }

  override fun onSucceed(businessLicenseResult: BusinessLicenseResult?, result: String?) {
    activity?.runOnUiThread {
      businessLicenseResult?.let { LifeAccountAuthDataManagerV2.generateBusinessLicenseData(it) }
      // 回显OCR结果
      viewBinding.evRegistrationName.fillEditContent(businessLicenseResult?.name)
      viewBinding.evRegistrationCode.fillEditContent(businessLicenseResult?.code)
      // 此时营业执照已上传并OCR识别完成 删除本地临时存储文件
      File(commonPath + Constant.FILE_PATH_BUSINESS_LICENSE).delete()
      // 检查下一步条件
      activity?.let { (it as LifeAccountEnterpriseAuthActivity).checkNextCondition() }
    }
  }

  override fun onFail(code: Int, errMsg: String?, errDomain: String?) {
    activity?.runOnUiThread {
      // 营业执照OCR识别失败提示
      viewBinding.tvUploadErrorTips.isVisible = true
      viewBinding.tvUploadErrorTips.text =
        resources.getString(R.string.check_business_license_distinct)
      activity?.let { viewBinding.viewBusinessLicenseUploadDivider.setBackgroundColor(ContextCompat.getColor(it, R.color.color_FFFF3A3A)) }
    }
  }

  override fun onUploadTask(imageUrl: String?) {
    LifeAccountAuthDataManagerV2.merchantAuthData.isBusinessLicenseUpload = true
    LifeAccountAuthDataManagerV2.merchantAuthData.businessLicenseUrl = imageUrl
  }
}
