package cn.muchinfo.rma.view.base.home.customerdata

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.View
import android.view.Window
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.lifecycle.MutableLiveData
import cn.muchinfo.rma.R
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.UserInfoData
import cn.muchinfo.rma.global.utils.SelectIUtils
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.netManage.base.InteractiveException
import cn.muchinfo.rma.netManage.utils.UpLoadUtils
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.autoWidget.addressDialog.AddressDialog
import cn.muchinfo.rma.view.autoWidget.addressDialog.AddressItemData
import cn.muchinfo.rma.view.autoWidget.photopicter.PhotoUtils
import cn.muchinfo.rma.view.base.BaseActivity
import cn.muchinfo.rma.view.base.app.Constant
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.*
import com.zhy.http.okhttp.callback.StringCallback
import mtp.polymer.com.autowidget.dialog.SelectData
import mtp.polymer.com.autowidget.dialog.creatBottomSheetDialog
import mtp.polymer.com.autowidget.dialog.createLoadingDialog
import mtp.polymer.com.autowidget.utils.TaskUiModel
import mtp.polymer.com.autowidget.utils.bindTaskStatus
import okhttp3.Call
import org.jetbrains.anko.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.util.*

/**
 * 添加修改用户资料页面
 */
class AddCustomerDataActivity : BaseActivity<CustomerDataViewModel>() {

    /**
     * status 1 新增 2 修改 3审核 4撤回 5 停用 6详情 7 恢复
     */
    val status by lazy {
        intent.getStringExtra("status")
    }

    /**
     * 用于修改，审核，撤回时的数据回填
     */
    val data: UserInfoData by lazy {
        intent.getParcelableExtra<UserInfoData>("userInfoData") as UserInfoData
    }


    /**
     * 营业执照图片地址
     */
    private var uploadFile: String = "" // 上传成功后服务给的图片地址
    private val imageString: MutableLiveData<String> =
        MutableLiveData<String>().apply { value = "" } // 文件地址

    lateinit var document_type_text: TextView

    private var loadingDialog: Dialog? = null

    /**
     * 企业名称
     */
    lateinit var enterprise_name: EditText

    /**
     * 证件号码
     */
    lateinit var card_umber: EditText

    /**
     * 手机号码
     */
    lateinit var phone_number: EditText

    /**
     * 联系电话
     */
    lateinit var contact_number: EditText

    /**
     * 备注
     */
    lateinit var remark: EditText

    /**
     * 本页面选择的客户类型
     */
    var customerType: MutableLiveData<SelectData> = MutableLiveData()

    /**
     * 证件类型
     */
    val cardType: MutableLiveData<SelectData> = MutableLiveData()

    private val dialog by lazy { createLoadingDialog(hintStr = "正在提交") }

    private var addressDialog //地址选择控件
            : AddressDialog? = null
    var mData: List<AddressItemData> =
        ArrayList<AddressItemData>() //地址控件存储的数据


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

        buildView()
        initData()
    }

    private fun initData() {
        if (status != "1") {
            customerType.postValue(
                SelectData(
                    id = data.userinfotype.toString(),
                    value = if (data.userinfotype == 1) {
                        "个人"
                    } else {
                        "企业"
                    }
                )
            )
            cardType.postValue(SelectData(id = data.cardtype.toString(),value = data.cardtypename ?: ""))

        }
        // 恢复数据
    }


    private fun buildView() {

        dialog.bindTaskStatus(context = this, taskUiModelData = viewModel.loadingDialogStatus)

        verticalLayout {
            loadingDialog = createLoadingDialog(hintStr = "请求中")
            loadingDialog?.bindTaskStatus(context, viewModel.loadingDialogStatus)
            topBar {
                commonLeftButton()
                commonTitle {
                    when (status) {
                        "1" -> {
                            text = "新增客户资料"
                        }
                        "2" -> {
                            text = "修改客户资料"
                        }
                        "3" -> {
                            text = "客户资料审核"
                        }
                        "4" -> {
                            text = "客户资料撤销"
                        }
                        "5" -> {
                            text = "停用客户资料"
                        }
                        "6" -> {
                            text = "客户资料详情"
                        }
                        "7" -> {
                            text = "恢复客户资料"
                        }
                    }
                }
            }

            frameLayout {
                scrollView {
                    verticalLayout {
                        // 客户类型
                        linearLayout {
                            // 客户类型点击
                            onThrottleFirstClick {
                                if (status != "1" && status != "2"){
                                    return@onThrottleFirstClick
                                }
                                val selectDataList = arrayListOf(
//                                    SelectData(id = "1", value = "个人"),
                                    SelectData(id = "2", value = "企业")
                                )
                                creatBottomSheetDialog("请选择客户类型", selectDataList) {
                                    customerType.postValue(this)
                                }
                            }
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                text = "*"
                                textColorInt = R.color.rma_star_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(37)
                            }

                            textView {
                                textResource = R.string.user_info_type
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(10)
                            }

                            textView {
                                customerType.bindOptional(context) {
                                    it.let {
                                        text = it?.value
                                    }
                                }
                                textResource = R.string.change_user_info_type
                                textSizeAuto = 31
                                textColorInt = R.color.rma_hint_text_color_ccc
                            }.lparams(autoSize(500), wrapContent) {
                                marginStart = autoSize(86)
                            }

                            view { }.lparams(0, autoSize(1), 1f)

                            imageView {
                                imageResource = R.mipmap.rma_more
                            }.lparams(autoSize(36), autoSize(36)) {
                                marginEnd = autoSize(25)
                            }

                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        // 企业名称
                        linearLayout {
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                text = "*"
                                textColorInt = R.color.rma_star_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(37)
                            }

                            textView {
                                textResource = R.string.an_enterprise_name
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(10)
                            }

                            editText {
                                if (status != "1"){
                                    setText(data.customername)
                                }
                                if (status != "1" && status != "2"){
                                    isEnabled = false
                                }
                                enterprise_name = this
                                hint = resources.getString(R.string.please_input_enterprise_name)
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_TEXT
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(autoSize(500), wrapContent) {
                                marginStart = autoSize(86)
                            }

                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        // 证件类型
                        linearLayout {
                            onThrottleFirstClick {
                                if (status != "1" && status != "2"){
                                    return@onThrottleFirstClick
                                }
                                val selectDataList = SelectIUtils.getDocumentType()
                                creatBottomSheetDialog("请选择证件类型", selectDataList) {
                                    cardType.postValue(this)
                                }
                            }
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                textResource = R.string.document_type
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            textView {
                                cardType.bindOptional(context) {
                                    it.let {
                                        text = it?.value
                                    }
                                }
                                document_type_text = this
                                textResource = R.string.please_select_document_type
                                textSizeAuto = 31
                                textColorInt = R.color.rma_hint_text_color_ccc
                            }.lparams(autoSize(500), wrapContent) {
                                marginStart = autoSize(86)
                            }

                            view { }.lparams(0, autoSize(1), 1f)

                            imageView {
                                imageResource = R.mipmap.rma_more
                            }.lparams(autoSize(36), autoSize(36)) {
                                marginEnd = autoSize(25)
                            }

                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        // 证件号码
                        linearLayout {
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                textResource = R.string.card_number
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            editText {
                                if (status != "1"){
                                    setText(data.cardnum)
                                }
                                if (status != "1" && status != "2"){
                                    isEnabled = false
                                }
                                card_umber = this
                                hint = resources.getString(R.string.please_input_card_number)
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_TEXT
//                    setDecimalInputType()
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(autoSize(500), wrapContent) {
                                marginStart = autoSize(86)
                            }

                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        // 营业执照
                        linearLayout {
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                textResource = R.string.business_license
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            textView {
                                if (status != "1" || status == "2"){
                                     if (data.attachment1.isNullOrEmpty()){
                                         visibility = View.VISIBLE
                                     }else{
                                         visibility = View.GONE
                                     }
                                }else{
                                    visibility = View.VISIBLE
                                }
                                imageString.bindOptional(context) {
                                    visibility = if (it.isNullOrEmpty()) {
                                        View.VISIBLE
                                    } else {
                                        View.GONE
                                    }
                                }
                                visibility = View.VISIBLE
                                onThrottleFirstClick {
                                    //审核，停用，复用，详情不需要点击
                                    if (status != "1" && status != "2"){
                                        return@onThrottleFirstClick
                                    }
                                    PhotoUtils().showPicker(this@AddCustomerDataActivity) {
                                        it.firstOrNull()?.let {
                                            viewModel.loadingDialogStatus.value =
                                                TaskUiModel.inFlight()
                                            UpLoadUtils(this@AddCustomerDataActivity).uploadPicture(
                                                File(it),
                                                object : StringCallback() {
                                                    override fun onError(
                                                        call: Call,
                                                        e: Exception,
                                                        id: Int
                                                    ) {
                                                        LogUtils.e("hidahdashdsdasd", e.message)
                                                        viewModel.loadingDialogStatus.value =
                                                            TaskUiModel.failed(
                                                                InteractiveException(
                                                                    errorMessage = e.message ?: ""
                                                                )
                                                            )
                                                    }

                                                    override fun onResponse(
                                                        response: String,
                                                        id: Int
                                                    ) {
                                                        /*[{"originalName":"tem.jpg","fileName":"201907161657044712.jpg","fileSize":"0KB","fileType":"image/jpeg","filePath":"./uploadFile/20190716/201907161657044712.jpg","submitName":null}]*/
                                                        try {
//                                                        if (!isFinishing) {
//                                                            viewModel.loadingDialogStatus.value
//                                                        }
                                                            viewModel.loadingDialogStatus.value =
                                                                TaskUiModel.success()
                                                            val jsonArray = JSONArray(response)
                                                            LogUtils.eTag(
                                                                "图片",
                                                                JSON.toJSONString(jsonArray)
                                                            )
                                                            for (i in 0 until jsonArray.length()) {
                                                                uploadFile =
                                                                    (jsonArray.get(i) as JSONObject).getString(
                                                                        "filePath"
                                                                    )
                                                                imageString.value = it
                                                                LogUtils.e("hidahdashd", uploadFile)
                                                            }
                                                        } catch (e: JSONException) {
                                                            e.printStackTrace()
                                                        }

                                                    }
                                                },
                                                10000.0,
                                                SPUtils.getInstance().getString(Constant.uploadUrl)
                                            )

                                        }
                                    }
                                }
                                gravity = Gravity.CENTER
                                textResource = R.string.update
                                textColorInt = R.color.rma_item_click_color
                                backgroundResource = R.drawable.rma_item_text_bg
                                textSizeAuto = 31
                            }.lparams(autoSize(134), autoSize(53)) {
                                marginStart = autoSize(86)
                            }

                            // 查看附件
                            textView {
                                onThrottleFirstClick {
                                    val path = imageString.value.guard {
                                        return@onThrottleFirstClick
                                    }
                                    PhotoUtils().showImageViewer(
                                        this@AddCustomerDataActivity,
                                        1,
                                        arrayListOf(path)
                                    )
                                }
                                textResource = R.string.check_the_attachment
                                textColorInt = R.color.rma_yellow_text_color
                                textSizeAuto = 31
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(86)
                            }
                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        // 手机号码
                        linearLayout {
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                textResource = R.string.phone_number
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            editText {
                                if (status != "1"){
                                    setText(data.mobile)
                                }
                                if (status != "1" && status != "2"){
                                    isEnabled = false
                                }
                                phone_number = this
                                hint = resources.getString(R.string.please_input_phone_number)
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_PHONE
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(autoSize(500), wrapContent) {
                                marginStart = autoSize(86)
                            }

                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        // 联系电话
                        linearLayout {
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                textResource = R.string.contact_phone_number
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            editText {
                                if (status != "1"){
                                    setText(data.telphone)
                                }
                                if (status != "1" && status != "2"){
                                    isEnabled = false
                                }
                                contact_number = this
                                hint = resources.getString(R.string.please_input_contact_phone_number)
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_PHONE
//                    setDecimalInputType()
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(autoSize(500), wrapContent) {
                                marginStart = autoSize(86)
                            }

                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        // 通讯地址
                        linearLayout {
                            onThrottleFirstClick {
                                if (status != "1" && status != "2"){
                                    return@onThrottleFirstClick
                                }

                                showAddress()
//                                val pvTime =
//                                    TimePickerBuilder(context,
//                                        OnTimeSelectListener { date, v ->
//                                            ToastUtils.showLong(TimeUtils.date2String(date))
//
//                                        }).build()
//                                pvTime.show()
                            }
                            gravity = Gravity.CENTER_VERTICAL

                            textView {
                                textResource = R.string.correspondence_address
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            textView {
                                textResource = R.string.please_select_address
                                textSizeAuto = 31
                                textColorInt = R.color.rma_hint_text_color_ccc
                            }.lparams(autoSize(500), wrapContent) {
                                marginStart = autoSize(86)
                            }

                        }.lparams(matchParent, autoSize(136))

                        viewItemUI()

                        linearLayout {
                            editText {
                                if (status != "1"){
                                    setText(data.address)
                                }
                                if (status != "1" && status != "2"){
                                    isEnabled = false
                                }
                                gravity = Gravity.TOP
                                hint = "请输入详细地址"
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_TEXT
//                    setDecimalInputType()
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(matchParent, autoSize(260)) {
                                marginStart = autoSize(270)
                            }
                        }.lparams(matchParent, autoSize(260))

                        viewItemUI()

                        // 备注
                        linearLayout {
                            gravity = Gravity.CENTER_VERTICAL
                            textView {
                                text = "备        注"
                                textSizeAuto = 31
                                textColorInt = R.color.rma_black_33
                            }.lparams(wrapContent, wrapContent) {
                                marginStart = autoSize(59)
                            }

                            editText {
                                if (status != "1"){
                                    setText(data.address)
                                }
                                if (status != "1" && status != "2" && status != "3"){
                                    isEnabled = false
                                }
                                remark = this
                                hint = "请输入备注"
                                background = null
                                inputType = EditorInfo.TYPE_CLASS_TEXT
//                    setDecimalInputType()
                                hintColorStr = "#CCCCCC"
                                textSizeAuto = 31
                                textColorStr = "#333333"
                            }.lparams(matchParent, autoSize(260)) {
                                marginStart = autoSize(59)
                            }
                        }.lparams(matchParent, autoSize(136)) {
                            bottomMargin = autoSize(200)
                        }
                    }
                }

                // 控制区
                linearLayout {
                    if (status == "6"){
                        visibility = View.GONE
                    }else {
                        visibility = View.VISIBLE
                    }
                    background = resources.getDrawable(R.color.white)
                    gravity = Gravity.CENTER_VERTICAL
                    textView {
                        onThrottleFirstClick {
                            if (status == "1" || status == "2"){//新增或者修改的保存草稿
                                commit(true)
                            }else{//审核拒绝
                                viewModel.requestUserInfoCheckMange(
                                    auditflag = 2,userid = data.userid?.toLong() ?: 0,audituserid = GlobalDataCollection.instance?.loginRsp?.userID?.toLong() ?: 0,remark = remark.text.toString()
                                ){
                                    finish()
                                }
                            }
                        }
                        gravity = Gravity.CENTER
                        backgroundResource = R.mipmap.rma_save_info_bg
                        if (status == "1" || status == "2"){
                            text = "保存草稿"
                        }else if (status == "3"){
                            text = "审核拒绝"
                        }
                        visibility = if (status == "5" || status == "7"|| status == "4") {
                            View.GONE
                        } else {
                            View.VISIBLE
                        }
                        textSizeAuto = 38
                        textColorInt = R.color.rma_star_color
                    }.lparams(autoSize(419), autoSize(119)) {
                        marginStart = autoSize(24)
                    }

                    textView {
                        onThrottleFirstClick {
                            if (status == "1" || status == "2"){//新增或者修改的保存草稿
                                commit(false)
                            }else{//审核通过
                                viewModel.requestUserInfoCheckMange(
                                    auditflag = 1,userid = data.userid?.toLong() ?: 0,audituserid = GlobalDataCollection.instance?.loginRsp?.userID?.toLong() ?: 0,remark = remark.text.toString()
                                ){
                                    finish()
                                }
                            }
                        }
                        if (status == "1" || status == "2"){
                            text = "提交审核"
                        }else if (status == "3"){
                            text = "审核通过"
                        }
                        visibility = if (status == "5" || status == "7"|| status == "4") {
                            View.GONE
                        } else {
                            View.VISIBLE
                        }
                        gravity = Gravity.CENTER
                        backgroundResource = R.mipmap.rma_submit_bg
                        textColorInt = R.color.white
                        textSizeAuto = 38
                    }.lparams(autoSize(419), autoSize(119)) {
                        marginStart = autoSize(13)
                    }

                    textView {
                        onThrottleFirstClick {
                            val params = mutableMapOf<String, Any>()
                            params["userid"] = data.userid ?: 0
                            params["userstate"] = 1
                            viewModel.modifyUserInfoApply(params) { isCompleted, err ->
                                if (!isCompleted) {
                                    viewModel.loadingDialogStatus.value =
                                        TaskUiModel.failed(InteractiveException(err?.message ?: ""))
                                    return@modifyUserInfoApply
                                }
                                viewModel.loadingDialogStatus.value = TaskUiModel.success(msg = "提交成功")
                                finish()
                            }
                        }
                        visibility = if (status == "4") {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                        gravity = Gravity.CENTER
                        backgroundResource = R.mipmap.rma_submit_bg
                        text = "撤销"
                        textColorInt = R.color.white
                        textSizeAuto = 38
                    }.lparams(autoSize(780), autoSize(119)) {
                        marginStart = autoSize(59)
                    }

                    textView {
                        onThrottleFirstClick {
                            if (status == "5"){//停用
                                viewModel.updateUserAccountStatus(userID = data.userid ?: 0,accountStatus = 6){isCompleted, err ->
                                    if (!isCompleted) {
                                        viewModel.loadingDialogStatus.value =
                                            TaskUiModel.failed(InteractiveException(err?.message ?: ""))
                                        return@updateUserAccountStatus
                                    }
                                    viewModel.loadingDialogStatus.value = TaskUiModel.success(msg = "提交成功")
                                    finish()
                                }
                            }else{//恢复
                                viewModel.updateUserAccountStatus(userID = data.userid ?: 0,accountStatus = 4){isCompleted, err ->
                                    if (!isCompleted) {
                                        viewModel.loadingDialogStatus.value =
                                            TaskUiModel.failed(InteractiveException(err?.message ?: ""))
                                        return@updateUserAccountStatus
                                    }
                                    viewModel.loadingDialogStatus.value = TaskUiModel.success(msg = "提交成功")
                                    finish()
                                }
                            }

                        }
                        visibility = if (status == "5" || status == "7") {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                        gravity = Gravity.CENTER
                        backgroundResource = R.mipmap.rma_submit_bg
                        if (status == "5"){
                            text = "停用"
                        }else if (status == "7"){
                            text = "恢复"
                        }

                        textColorInt = R.color.white
                        textSizeAuto = 38
                    }.lparams(autoSize(780), autoSize(119)) {
                        marginStart = autoSize(59)
                    }

                }.lparams(matchParent, autoSize(144)) {
                    gravity = Gravity.BOTTOM
                }

            }
        }
    }

    /**
     * 地址选择器
     */
    private fun showAddress() {
        addressDialog = AddressDialog(this, R.style.style_dialog)
        addressDialog?.setListener {
            mData = addressDialog?.getIdList()!!
            val builder = StringBuilder()
            mData.forEach {
                builder.append(it.getAddressName())
                builder.append(" ")
            }
            val mainHandler = Handler(Looper.getMainLooper())
            mainHandler.post {

            }
        }
        addressDialog?.show()
        val dialogWindow: Window? = addressDialog!!.getWindow()
        val lp = dialogWindow?.attributes
        lp?.width = ScreenUtils.getScreenWidth()
        lp?.height = ScreenUtils.getScreenHeight() * 2 / 3
        dialogWindow?.setGravity(Gravity.BOTTOM)
        dialogWindow?.attributes = lp
    }


    fun _LinearLayout.viewItemUI() {
        view {
            background = resources.getDrawable(R.color.rma_hint_line_color_eee)
        }.lparams(matchParent, autoSize(1)) {
            marginStart = autoSize(60)
        }
    }


    /**
     * 检验输入
     * @return Boolean 检验是否成功
     */
    private fun checkInput(): Boolean {
        if (customerType.value?.id?.isNullOrEmpty() == true) {
            ToastUtils.showLong("请选择客户类型")
            return false
        }
        if (enterprise_name.text.isNullOrEmpty()) {
            ToastUtils.showLong("请输入企业名称")
            return false
        }

        return true
    }

    /**
     * 提交新增客户资料
     * @param isDraft Boolean 是否保存草稿
     */
    private fun commit(isDraft: Boolean) {
        if (!checkInput()) {
            return
        }
        addUserInfo(isDraft)
    }

    private fun addUserInfo(isDraft: Boolean) {
        // 客户资料参数
        val params = mutableMapOf<String, Any>()
        params["userid"] = 1
        // FIXME: - 客户类型暂时写死为"企业"
        params["userinfotype"] = customerType.value?.id?.toInt() ?: 0
        // 企业名称
        params["customername"] = enterprise_name.text.toString()
        params["username"] = enterprise_name.text.toString()
        // 开户状态：1 - 未提交；2 - 待初审
        params["userstate"] = if (isDraft) 1 else 2
        // 所属机构
        // FIXME: - 这里应该判断一下UserID是否为0
        params["memberareaid"] = GlobalDataCollection.instance?.loginRsp?.userID ?: 0

        // 证件类型
        if (cardType.value?.id?.isNullOrEmpty() == false) {
            // FIXME: - 证件类型要从数据库枚举中获取
            params["cardtype"] = cardType.value?.id?.toInt() ?: 0
        }
        // 证件号码
        if (!card_umber.text.isNullOrEmpty()) {
            params["cardnum"] = card_umber.text.toString()
        }
        // 营业执照
        if (!uploadFile.isNullOrEmpty()) {
            params["cardfrontphotourl"] = uploadFile
        }
        // 手机号码
        if (!phone_number.text.isNullOrEmpty()) {
            params["mobilephone"] = phone_number.text.toString()
        }
        // 联系电话
        if (!contact_number.text.isNullOrEmpty()) {
            params["telphone"] = contact_number.text.toString()
        }
        // 通讯地址

        // 备注
        if (!remark.text.isNullOrEmpty()) {
            params["remark"] = remark.text.toString()
        }

        // 提交申请
        viewModel.loadingDialogStatus.value = TaskUiModel.inFlight()
        if (status == "2"){//修改
            viewModel.modifyUserInfoApply(params) { isCompleted, err ->
                if (!isCompleted) {
                    viewModel.loadingDialogStatus.value =
                        TaskUiModel.failed(InteractiveException(err?.message ?: ""))
                    return@modifyUserInfoApply
                }
                viewModel.loadingDialogStatus.value = TaskUiModel.success(msg = "提交成功")
                finish()
            }
        }else if (status == "1") {//新增
            viewModel.addUserInfoApply(params) { isCompleted, err ->
                if (!isCompleted) {
                    viewModel.loadingDialogStatus.value =
                        TaskUiModel.failed(InteractiveException(err?.message ?: ""))
                    return@addUserInfoApply
                }

                viewModel.loadingDialogStatus.value = TaskUiModel.success(msg = "提交成功")
                finish()
            }
        }

    }
}