package com.yidian.shenghuoquan.newscontent.ui.auth

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.FileProvider
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.yidian.common.base.BaseFragment
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.shenghuoquan.newscontent.adapter.BottomSelectAdapter
import com.yidian.shenghuoquan.newscontent.bean.BottomSelectBean
import com.yidian.shenghuoquan.newscontent.constant.Constant
import com.yidian.shenghuoquan.newscontent.databinding.FragmentLifeAccountBusinessLicenseAuthBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.http.httpbean.AuthMerchantCheckBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.BusinessLicenseOCRBean
import com.yidian.shenghuoquan.newscontent.http.httpbean.IBusinessLicenseOCRCallback
import com.yidian.shenghuoquan.newscontent.ui.dialog.BottomSelectDialog
import com.yidian.shenghuoquan.newscontent.utils.BitmapUtil
import com.yidian.shenghuoquan.newscontent.utils.FileUtil
import com.yidian.shenghuoquan.newscontent.utils.InputFilterUtil
import com.yidian.shenghuoquan.newscontent.utils.KS3Core
import com.yidian.shenghuoquan.newscontent.widget.LifeAccountAuthBusinessInfoEditView
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() {
    // 输入过滤
    viewBinding.evRegistrationName.setInputFilters(InputFilterUtil.getRegistrationNameFilter(), InputFilter.LengthFilter(40))
    viewBinding.evRegistrationCode.setInputFilters(InputFilterUtil.getRegistrationCodeFilter(), InputFilter.LengthFilter(18))
  }


  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,
              "${activity?.packageName}.provider",
              file
            )
          }
        } else {
          Uri.fromFile(file)
        }
        startActivityForResult(
          Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(
            MediaStore.EXTRA_OUTPUT,
            photoUri
          ),
          Constant.REQUEST_CODE_OPEN_CAMERA
        )
      }
      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
    }
    val requestParams = HashMap<String, String?>()
    requestParams["business_image_objectid"] = objectKey
    requestParams["business_image_bucket"] = bucket
    ApiService.businessLicenseOCR(this, requestParams)
  }

  /**
   * 清除已输入的营业执照相关信息
   * 用户更换商户类型操作
   */
  fun clearBusinessLicenseInfo() {
    // 清除已上传的营业执照
    viewBinding.ivBusinessLicense.setImageDrawable(null)
    // 清除错误提示
    viewBinding.tvUploadErrorTips.isVisible = false
    viewBinding.ivClear.isVisible = false
    // 清除OCR或用户输入内容
    viewBinding.evRegistrationName.clearEditContent()
    viewBinding.evRegistrationCode.clearEditContent()
    // 设置上传区域可点击
    viewBinding.clBusinessLicenseUpload.isEnabled = true
    LifeAccountAuthDataManager.merchantAuthData.isBusinessLicenseUpload = false
    LifeAccountAuthDataManager.merchantAuthData.registrationName = ""
    LifeAccountAuthDataManager.merchantAuthData.registrationCode = ""

  }

  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.businessLicenseObjectKey = 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 as LifeAccountEnterpriseAuthActivity).checkNextCondition()
  }

  override fun businessLicenseOCRFailure(message: String?) {
    Log.e(
      Constant.LIFE_ACCOUNT_AUTH_TAG,
      "request business license ocr failure, message: $message"
    )
    // 营业执照OCR识别失败提示
    viewBinding.tvUploadErrorTips.isVisible = true
    viewBinding.tvUploadErrorTips.text =
      resources.getString(R.string.check_business_license_distinct)
  }

  override fun onTextClear(from: LifeAccountAuthBusinessInfoEditView) {
    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) {
      LifeAccountAuthDataManager.merchantAuthData.registrationName = text
    } else {
      LifeAccountAuthDataManager.merchantAuthData.registrationCode = text
    }
    // 检查下一步条件
    (activity as LifeAccountEnterpriseAuthActivity).checkNextCondition()
  }
}
