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

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.text.InputFilter
import android.util.Log
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 com.bumptech.glide.Glide
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yidian.bcommon.base.BaseFragment
import com.yidian.bcommon.constant.GlobalConstants
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.ApiService
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.bmanagercenter.http.httpbean.BusinessLicenseOCRBean
import com.yidian.shenghuoquan.bmanagercenter.http.callback.IBusinessLicenseOCRCallback
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.shenghuoquan.bmanagercenter.utils.InputFilterUtil
import com.yidian.shenghuoquan.bmanagercenter.utils.KS3Core
import com.yidian.shenghuoquan.bmanagercenter.widget.LifeAccountAuthBusinessInfoEditView
import com.yidian.utils.ToastUtil
import java.io.File

/**
 * author: yinjiacheng
 * date: 5/28/21 3:22 PM
 * description: 生活号认证 营业执照认证
 */
class LifeAccountBusinessLicenseAuthFragment :
  BaseFragment<FragmentLifeAccountBusinessLicenseAuthBinding>(), View.OnClickListener,
  BottomSelectAdapter.OnItemClickListener<BottomSelectBean>, KS3Core.OnKS3TaskListener,
  IBusinessLicenseOCRCallback,
  LifeAccountAuthBusinessInfoEditView.OnLifeAccountAuthBusinessInfoEditViewCallback {

  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()
        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) {
      val uri = if (requestCode == Constant.REQUEST_CODE_OPEN_ALBUM) data?.data else photoUri
      val bitmap =
        BitmapUtil.generateBitmapFromUri(activity, uri, viewBinding.ivBusinessLicense)
      viewBinding.ivBusinessLicense.setImageBitmap(bitmap)
      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()
      // 显示清除按钮
      viewBinding.ivClear.visibility = View.VISIBLE
      // 上传区域不可点击
      viewBinding.clBusinessLicenseUpload.isEnabled = false
      // 执行上传金山云
      startUpload()
    }
  }

  /**
   * 执行营业执照上传金山云
   */
  private fun startUpload() {
    // 上传前压缩图像
    BitmapUtil.compressImage(
      commonPath + Constant.FILE_PATH_BUSINESS_LICENSE,
      10
    )
    KS3Core.INSTANCE.uploadObject(
      File(commonPath + Constant.FILE_PATH_BUSINESS_LICENSE),
      KS3Core.ObjectType.IMAGE,
      KS3Core.ScenarioType.BUSINESS_LICENSE,
      this
    )
  }

  /**
   * 执行营业执照OCR
   */
  private fun startBusinessLicenseOCR(objectKey: String?, bucket: String?) {
    if (objectKey == null || bucket == null) {
      Log.e(
        Constant.LIFE_ACCOUNT_AUTH_TAG,
        "business license objectKey or bucket is null, ocr suspend!"
      )
      return
    }
    ApiService.businessLicenseOCR(this, hashMapOf(Pair("business_image_url", "$bucket/$objectKey")))
  }

  /**
   * 清除已输入的营业执照相关信息
   * 用户更换商户类型操作
   */
  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
    LifeAccountAuthDataManager.merchantAuthData.isBusinessLicenseUpload = false
    LifeAccountAuthDataManager.merchantAuthData.registrationName = null
    LifeAccountAuthDataManager.merchantAuthData.registrationCode = null
    // 标识修改
    LifeAccountAuthDataManager.merchantAuthData.isAuthInfoModify = true
  }

  override fun onTaskStart() {

  }

  override fun onTaskProgress(progress: Double) {

  }

  override fun onTaskFinish() {

  }

  override fun onTaskCancel() {

  }

  override fun onTaskSuccess(bucket: String?, objectKey: String?) {
    LifeAccountAuthDataManager.merchantAuthData.isBusinessLicenseUpload = true
    LifeAccountAuthDataManager.merchantAuthData.businessLicenseBucket = bucket
    LifeAccountAuthDataManager.merchantAuthData.businessLicenseObjectKey = objectKey
    LifeAccountAuthDataManager.merchantAuthData.businessLicenseUrl = "${bucket}/${objectKey}"
    // 执行营业执照OCR
    startBusinessLicenseOCR(objectKey, bucket)
  }

  override fun onTaskFailure(statesCode: Int, message: String?) {

  }

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

  override fun businessLicenseOCRFailure(message: String?) {
    // 营业执照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 onTextClear(from: LifeAccountAuthBusinessInfoEditView) {
    // 标识修改
    LifeAccountAuthDataManager.merchantAuthData.isAuthInfoModify = true
    if (from == viewBinding.evRegistrationName) {
      LifeAccountAuthDataManager.merchantAuthData.registrationName = ""
    } else {
      LifeAccountAuthDataManager.merchantAuthData.registrationCode = ""
    }
    // 检查下一步条件
    (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
  }

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