package mtp.polymer.com.autowidget.dialog

import android.app.DatePickerDialog
import android.app.Dialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import android.graphics.Color
import android.os.Build

import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import cn.muchinfo.rma.R
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.AccountData
import cn.muchinfo.rma.global.data.AvaildGoodsGroupData
import cn.muchinfo.rma.global.data.MiddleGoodsData

import cn.muchinfo.rma.lifecycle.addObserver
import cn.muchinfo.rma.lifecycle.getAppCompatActivity
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.autoWidget.dialog.AccountViewHolder
import cn.muchinfo.rma.view.base.app.Constant
import com.blankj.utilcode.util.SPUtils
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet

import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog

import io.reactivex.Observable
import mtp.polymer.com.autowidget.adapter.BaseAdapter


import org.jetbrains.anko.*
import java.util.*
import java.util.concurrent.TimeUnit

/**
 * 对话框的相关扩展方法
 */


fun LifecycleOwner.createLoadingDialog(
    hintStr: String = "",
    block: (QMUITipDialog.Builder.() -> Unit)? = null
): Dialog {
    val builder = QMUITipDialog.Builder(getAppCompatActivity())
        .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
    builder.setTipWord(hintStr)
    block?.invoke(builder)
    return builder.create().apply { addObserver { onDestroy { dismiss() } } }
}

fun AppCompatActivity.createErrorDialog(block: (QMUITipDialog.Builder.() -> Unit)? = null): Dialog {
    val builder = QMUITipDialog.Builder(getAppCompatActivity())
        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
    block?.invoke(builder)
    return builder.create().apply {
        setCanceledOnTouchOutside(false)
        setCancelable(true)
        addObserver { onDestroy { dismiss() } }
    }
}

fun AppCompatActivity.showErrorDialog(block: (QMUITipDialog.Builder.() -> Unit)? = null): Dialog {
    val builder = QMUITipDialog.Builder(getAppCompatActivity())
        .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
    block?.invoke(builder)
//    Utils.isSameDay(Date(), Date())
    return builder.create().apply {
        setCanceledOnTouchOutside(false)
        setCancelable(true)
        addObserver { onDestroy { dismiss() } }
    }.apply {
        autoDismissAfterShow(this@showErrorDialog)
    }
}

fun AppCompatActivity.createSuccessDialog(block: (QMUITipDialog.Builder.() -> Unit)? = null): Dialog {
    val builder = QMUITipDialog.Builder(getAppCompatActivity())
        .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
    block?.invoke(builder)
    return builder.create().apply {
        setCanceledOnTouchOutside(false)
        setCancelable(true)
        addObserver { onDestroy { dismiss() } }
    }
}

fun AppCompatActivity.showSuccessDialog(block: (QMUITipDialog.Builder.() -> Unit)? = null): Dialog {
    val builder = QMUITipDialog.Builder(getAppCompatActivity())
        .setIconType(QMUITipDialog.Builder.ICON_TYPE_SUCCESS)
    block?.invoke(builder)
    return builder.create().apply {
        setCanceledOnTouchOutside(false)
        setCancelable(true)
        addObserver { onDestroy { dismiss() } }
    }.apply {
        autoDismissAfterShow(this@showSuccessDialog)
    }
}

fun AppCompatActivity.createCustomDialog(
    cancelable: Boolean = true,
    createView: (_FrameLayout.(CustomDialogFragment) -> View)
): CustomDialogFragment {
    return CustomDialogFragment.createInstance(this, createView).apply {
        isCancelable = cancelable
    }
}

/**
 * @receiver AppCompatActivity
 * @param titleStr 头部内容
 * @param selectList List<SelectData> 选择的实体列表
 * @param select [@kotlin.ExtensionFunctionType] Function1<SelectData, Unit>?
 */
fun AppCompatActivity.creatBottomSheetDialog(
    titleStr: String,
    selectList: List<SelectData>,
    select: (SelectData.() -> Unit)? = null
) {
    val builder: QMUIBottomSheet.BottomListSheetBuilder =
        QMUIBottomSheet.BottomListSheetBuilder(this)
    builder.setGravityCenter(true)
        .setTitle(titleStr)
        .setAddCancelBtn(true)
    selectList.forEach {
        builder.addItem(it.value)
    }
    builder.setOnSheetItemClickListener { dialog, itemView, position, tag ->
        select?.invoke(selectList.get(position))
        dialog.dismiss()
    }
    builder.build().show()
}

/**
 * 专门用新增套保品种的选择
 * @receiver AppCompatActivity
 * @param titleStr 头部内容
 * @param selectList List<AvaildGoodsGroupData> 选择的实体列表
 * @param select [@kotlin.ExtensionFunctionType] Function1<AvaildGoodsGroupData, Unit>?
 */
fun AppCompatActivity.creatHedgeBottomSheetDialog(
    titleStr: String,
    selectList: List<AvaildGoodsGroupData>,
    select: (AvaildGoodsGroupData.() -> Unit)? = null
) {
    val builder: QMUIBottomSheet.BottomListSheetBuilder =
        QMUIBottomSheet.BottomListSheetBuilder(this)
    builder.setGravityCenter(true)
        .setTitle(titleStr)
        .setAddCancelBtn(true)
    selectList.forEach {
        builder.addItem(it.goodsgroupname)
    }
    builder.setOnSheetItemClickListener { dialog, itemView, position, tag ->
        select?.invoke(selectList.get(position))
        dialog.dismiss()
    }
    builder.build().show()
}


/**
 * 专门用新增现货商品时的套保品种选择
 * @receiver AppCompatActivity
 * @param titleStr 头部内容
 * @param selectList List<MiddleGoodsData> 选择的实体列表
 * @param select [@kotlin.ExtensionFunctionType] Function1<MiddleGoodsData, Unit>?
 */
fun AppCompatActivity.creatGoodsHedgeBottomSheetDialog(
    titleStr: String,
    selectList: List<MiddleGoodsData>,
    select: (MiddleGoodsData.() -> Unit)? = null
) {
    val builder: QMUIBottomSheet.BottomListSheetBuilder =
        QMUIBottomSheet.BottomListSheetBuilder(this)
    builder.setGravityCenter(true)
        .setTitle(titleStr)
        .setAddCancelBtn(true)
    selectList.forEach {
        builder.addItem(it.middlegoodsname)
    }
    builder.setOnSheetItemClickListener { dialog, itemView, position, tag ->
        select?.invoke(selectList.get(position))
        dialog.dismiss()
    }
    builder.build().show()
}

/**
 * 查询单据用的时间选择器
 * @receiver AppCompatActivity
 * type 1 是选择年月日 2 是选择年月
 * @param selectTime [@kotlin.ExtensionFunctionType] Function1<String, Unit>?
 */
@RequiresApi(Build.VERSION_CODES.N)
fun AppCompatActivity.showDataSelectDialog(
    type: String = "1",
    selectTime: (String.() -> Unit)? = null
) {
    val calendar = Calendar.getInstance(Locale.CHINA)
    DatePickerDialog(
        this,
        DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
            if (type == "1") {
                selectTime?.invoke("$year-$monthOfYear-$dayOfMonth")
            } else {
                selectTime?.invoke("$year-$monthOfYear")
            }
        },
        calendar.get(Calendar.YEAR),
        calendar.get(Calendar.MONTH),
        calendar.get(Calendar.DAY_OF_MONTH)
    ).show()
}


fun LifecycleOwner.createWarningDialog(
    cancelable: Boolean = false,
    block: (QMUIDialog.MessageDialogBuilder.() -> Unit)
): QMUIDialog {
    val dialog = QMUIDialog.MessageDialogBuilder(getAppCompatActivity())
        .apply {
            block.invoke(this)
        }
        .create()
        .apply {
            setCancelable(cancelable)
            setCanceledOnTouchOutside(cancelable)
        }
    addObserver {
        onDestroy {
            dialog.dismiss()
        }
    }
    return dialog
}

fun AppCompatActivity.createPasswordInputDialog(
    titleStr: String,
    hintStr: String,
    onInputBlock: (CharSequence) -> Unit
): BottomInputDialogFragment {
    return BottomInputDialogFragment.createInstance(this, titleStr, hintStr).apply {
        this.onInputBlock = onInputBlock
        this@createPasswordInputDialog.addObserver { onDestroy { dismiss() } }
    }
}

fun AppCompatActivity.createInputDialog(
    titleStr: String,
    hintStr: String,
    actionStr: String,
    onInputBlock: (CharSequence) -> Unit
): BottomInputDialogFragment {
    return BottomInputDialogFragment.createInstance(
        appCompatActivity = this,
        titleStr = titleStr,
        hintStr = hintStr,
        inputType = EditorInfo.TYPE_CLASS_TEXT,
        actionStr = actionStr
    )
        .apply {
            this.onInputBlock = onInputBlock
            this@createInputDialog.addObserver { onDestroy { dismiss() } }
        }
}

/**
 * 选择资金账户的弹窗
 * @receiver AppCompatActivity
 * @param selectAccount [@kotlin.ExtensionFunctionType] Function1<AccountData, Unit>?
 * @return CustomDialogFragment
 */
fun AppCompatActivity.creatSelectAccountDialog(
    selectAccount: (AccountData.() -> Unit)? = null
): CustomDialogFragment {
    return createCustomDialog(cancelable = false) { dialog ->
        backgroundColor = Color.parseColor("#5f000000")
        val accountAdapter: BaseAdapter<AccountData, AccountViewHolder> =
            BaseAdapter { _, _ -> AccountViewHolder(this@creatSelectAccountDialog) }
        verticalLayout {
            gravity = Gravity.TOP

            view { }.lparams(matchParent, autoSize(120))

            verticalLayout {
                recyclerView {
                    background = resources.getDrawable(R.color.white)
                    adapter = accountAdapter
                }.lparams(matchParent, matchParent)
            }.lparams(matchParent, wrapContent)

            accountAdapter.setNewData(GlobalDataCollection.instance?.accountDataList)
            accountAdapter.setOnItemClickListener { adapter, view, position ->
                selectAccount?.invoke(
                    GlobalDataCollection.instance?.accountDataList?.get(position) ?: AccountData()
                )
                SPUtils.getInstance().put(
                    Constant.SELECT_ACCOUNT_ID,
                    GlobalDataCollection.instance?.accountDataList?.get(position)?.accountid ?: 0
                )
                dialog.dismiss()
            }

            linearLayout {
                background = resources.getDrawable(R.color.white)
                onThrottleFirstClick {
                    dialog.dismiss()
                }
                gravity = Gravity.CENTER
                textView {
                    text = "取消"
                    textSizeAuto = 36
                    textColorInt = R.color.rma_gray_color
                }.lparams(wrapContent, wrapContent)
            }.lparams(matchParent, autoSize(100))


        }.lparams(matchParent, matchParent)
    }
}

//fun AppCompatActivity.createStateDialog(textOne: String = "", textTwo: String = "", textThree: String = ""): CustomDialogFragment {
//    return createCustomDialog(cancelable = false) { dialog ->
////        backgroundColor = Color.parseColor("#3f000000")
//        verticalLayout {
//            background = resources.getDrawable(R.color.manager_background_bg)
//            onClick { }
//            linearLayout {
//                textView {
//                    gravity = Gravity.CENTER_HORIZONTAL
//                    text = resources.getString(R.string.descriptor)
//                    textSizeAuto = 40
//                    textColor = Color.WHITE
//                }.lparams(0, wrapContent, 1f) {
//                    gravity = Gravity.CENTER
//                }
//                imageView {
//                    onThrottleFirstClick { dialog.dismiss() }
//                    setImageDrawable(context.getTintDrawable(imageSrc = R.drawable.ic_remove, tintColorStr = "#ffa531"))
//                    padding = autoSize(40)
//                }.lparams(autoSize(118), autoSize(118)) {
//                    gravity = Gravity.END
//                }
//            }.lparams(matchParent, autoSize(118))
//            verticalLayout {
//                textView {
//                    textColor = Color.WHITE
//                    textSizeAuto = 32
//                    text = textOne
//                }.lparams(wrapContent, wrapContent){
//                    marginStart = autoSize(30)
//                    marginEnd = autoSize(30)
//                }
//                space(30)
//                textView {
//                    textColor = Color.WHITE
//                    textSizeAuto = 32
//                    text = textTwo
//                }.lparams(wrapContent, wrapContent){
//                    marginStart = autoSize(30)
//                    marginEnd = autoSize(30)
//                }
//                space(30)
//                textView {
//                    textColor = Color.WHITE
//                    textSizeAuto = 32
//                    text = textThree
//                }.lparams(wrapContent, wrapContent){
//
//                    marginStart = autoSize(30)
//                    marginEnd = autoSize(30)
//                }
//                space(30)
//
//            }
//
//        }.lparams(autoSize(750), wrapContent) {
//            gravity = Gravity.CENTER
//        }
//    }
//}

fun Dialog.autoDismissAfterShow(
    lifecycleOwner: LifecycleOwner,
    delay: Long = 1500,
    onDismissBlock: ((Dialog) -> Unit)? = null
) {
    show()
    Observable.timer(delay, TimeUnit.MILLISECONDS)
        .applySchedulers()
        .bindLifeCycle(lifecycleOwner, Lifecycle.Event.ON_STOP)
        .subscribe {
            dismiss().also { onDismissBlock?.invoke(this) }
        }
}

data class SelectData(
    var id: String,//现货商品id
    var value: String,
    var deliverygoodsid: String = "",//现货合同中的现货品种id
    var areauserid: String = "",//现货areauserid
    var enumdicname: String = ""//现货商品的单位名称
)
