package com.yidian.shenghuoquan.newscontent.ui.store

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import com.tbruyelle.rxpermissions3.Permission
import com.tbruyelle.rxpermissions3.RxPermissions
import com.yidian.common.base.BaseActivity
import com.yidian.common.extensions.hideKeyBoard
import com.yidian.common.utils.EditTextUtils
import com.yidian.common.utils.ToastUtils
import com.yidian.common.utils.ValidationUtils
import com.yidian.shenghuoquan.newscontent.databinding.ActivityStoreEditBinding
import com.yidian.shenghuoquan.newscontent.http.ApiService
import com.yidian.shenghuoquan.newscontent.utils.StorageUtil
import com.yidian.shenghuoquan.newscontent.widget.CommonTopBarView

/**
 * 新增/编辑门店
 */
class EditStoreActivity : BaseActivity<ActivityStoreEditBinding>(), CommonTopBarView.OnCommonTopBarActionCallback {

  // 是否为新建门店
  private var isAddStore: Boolean = false
  private var store = Store("", "", "", "", "")

  override fun createViewBinding(): ActivityStoreEditBinding {
    return ActivityStoreEditBinding.inflate(layoutInflater)
  }

  override fun getXPageName(): String {
    return ""
  }

  override fun init(savedInstanceState: Bundle?) {
    intent?.let {
      when (it.getSerializableExtra("from")) {
        fromAddStore -> {
          isAddStore = true
          viewBind.bvTopBar.setPageTitle("新建门店")
          initContent()
        }
        fromEditStore -> {
          isAddStore = false
          viewBind.bvTopBar.setPageTitle("编辑门店")
          initContent(it)
        }
      }
      initClick()
    }
  }

  private fun initContent(intent: Intent? = null) {
    if (intent == null) {
      viewBind.storePhoneNum.setText("")
      viewBind.storeAddressEdit.text = ""
      viewBind.storeName.setText("")
      store.shop_id = ""
      store.sub_shop_id = ""
      store.latitude = ""
      store.longitude = ""
    } else {
      viewBind.storePhoneNum.setText(intent.getStringExtra("phone"))
      viewBind.storeAddressEdit.text = intent.getStringExtra("address")
      viewBind.storeName.setText(intent.getStringExtra("shop_name"))
      store.shop_id = intent.getStringExtra("shop_id") ?: ""
      store.sub_shop_id = intent.getStringExtra("sub_shop_id") ?: ""
      store.latitude = intent.getStringExtra("latitude") ?: ""
      store.longitude = intent.getStringExtra("longitude") ?: ""
    }
  }

  private fun initClick() {
    viewBind.bvTopBar.setOnCommonTopBarCallback(null, this)
    viewBind.addressLayout.setOnClickListener {
      val rxPermissions = RxPermissions(this)
      rxPermissions.request(
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION,
      )
        .subscribe {
          if (it) {
            startActivityForResult(Intent(this@EditStoreActivity, SelectAddressActivity::class.java), 200)
          } else {
            ToastUtils.showShort("需要授予位置权限才能使用该功能")
          }
        }
    }
    EditTextUtils.clearEditText(viewBind.storeName, viewBind.ivClearName)
    EditTextUtils.clearEditText(viewBind.storePhoneNum, viewBind.ivClearPhone)
  }

  /**
   * 保存（新建和编辑）
   */
  override fun onDoAction() {
    hideKeyBoard()
    if (isAddStore) {
      toAddStore()
    } else {
      toUpdateStore()
    }
  }

  private fun toAddStore() {
    if (!dataValidation()) {
      return
    }
    val requestParams = HashMap<String, String?>()
    requestParams["life_account_id"] = StorageUtil.getLifeAccountId()
    requestParams["phone"] = viewBind.storePhoneNum.text.toString()
    requestParams["shop_name"] = viewBind.storeName.text.toString()
    requestParams["latitude"] = store.latitude
    requestParams["longitude"] = store.longitude
    requestParams["address"] = store.title
    ApiService.addStore(requestParams) {
      if (it) {
        ToastUtils.showLongSafe("保存成功，门店经纬度：${store.longitude}, ${store.latitude}")
        finish()
      }
    }
  }

  private fun toUpdateStore() {
    if (!dataValidation()) {
      return
    }
    val requestParams = HashMap<String, String?>()
    requestParams["sub_shop_id"] = store.sub_shop_id
    requestParams["life_account_id"] = StorageUtil.getLifeAccountId()
    requestParams["phone"] = viewBind.storePhoneNum.text.toString()
    requestParams["shop_id"] = store.shop_id
    requestParams["shop_name"] = viewBind.storeName.text.toString()
    requestParams["latitude"] = store.latitude
    requestParams["longitude"] = store.longitude
    requestParams["address"] = store.title
    ApiService.updateStore(requestParams) {
      if (it) {
        ToastUtils.showLongSafe("保存成功，门店经纬度：${store.longitude}, ${store.latitude}")
        finish()
      }
    }
  }

  private fun dataValidation(): Boolean {
    val storeName = viewBind.storeName.text.toString()
    val storePhoneNum = viewBind.storePhoneNum.text.toString()
    if (storeName.isBlank()) {
      ToastUtils.showShortSafe("请输入门店名称")
      return false
    }
    if (viewBind.storeAddressEdit.text.isBlank()) {
      ToastUtils.showShortSafe("请选择门店地址")
      return false
    }
    if (storePhoneNum.isBlank()) {
      ToastUtils.showShortSafe("请输入联系电话")
      return false
    }
    return true
  }

  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (resultCode == 200) {
      data?.let {
        viewBind.storeAddressEdit.text = it.getStringExtra("title")
        store.title = it.getStringExtra("title") ?: ""
        store.latitude = it.getStringExtra("latitude") ?: ""
        store.longitude = it.getStringExtra("longitude") ?: ""
      }
    }
  }

  companion object {
    const val fromAddStore = "fromAddStore"
    const val fromEditStore = "fromEditStore"
  }

  data class Store(
    var title: String,
    var latitude: String,
    var longitude: String,
    var shop_id: String,
    var sub_shop_id: String
  )
}
