package com.casic.electric.detector.widgets

import android.app.DatePickerDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.widget.AppCompatAutoCompleteTextView
import com.casic.electric.detector.R
import com.casic.electric.detector.extensions.appendZero
import com.casic.electric.detector.utils.DataBaseManager
import com.casic.electric.detector.utils.LocaleConstant
import com.casic.electric.detector.utils.QueryMode
import com.pengxh.kt.lite.extensions.initDialogLayoutParams
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class QueryMarkerDialog private constructor(builder: Builder) : Dialog(
    builder.context, R.style.UserDefinedDialogStyle
) {
    private val ctx = builder.context
    private val title = builder.title
    private val conditionArray = builder.conditionArray
    private val positiveBtn = builder.positiveBtn
    private val negativeBtn = builder.negativeBtn
    private val listener = builder.listener

    class Builder {
        lateinit var context: Context
        lateinit var title: String
        lateinit var conditionArray: Array<String>
        lateinit var positiveBtn: String
        lateinit var negativeBtn: String
        lateinit var listener: OnDialogButtonClickListener

        fun setContext(context: Context): Builder {
            this.context = context
            return this
        }

        fun setTitle(title: String): Builder {
            this.title = title
            return this
        }

        fun setConditionArray(conditionArray: Array<String>): Builder {
            this.conditionArray = conditionArray
            return this
        }

        fun setPositiveButton(name: String): Builder {
            positiveBtn = name
            return this
        }

        fun setNegativeButton(name: String): Builder {
            negativeBtn = name
            return this
        }

        fun setOnDialogButtonClickListener(listener: OnDialogButtonClickListener): Builder {
            this.listener = listener
            return this
        }

        fun build(): QueryMarkerDialog {
            return QueryMarkerDialog(this)
        }
    }

    private val calendar by lazy { Calendar.getInstance() }
    private lateinit var queryMode: QueryMode
    private lateinit var inputView: AppCompatAutoCompleteTextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        this.initDialogLayoutParams(0.8f)
        setContentView(R.layout.dialog_query_marker)
        setCanceledOnTouchOutside(false)
        initView()
    }

    private fun initView() {
        val dialogTitleView: TextView = findViewById(R.id.dialogTitleView)
        val conditionSpinner: Spinner = findViewById(R.id.conditionSpinner)
        val contentLayout: LinearLayout = findViewById(R.id.contentLayout)
        val contentSpinner: Spinner = findViewById(R.id.contentSpinner)
        inputView = findViewById(R.id.inputView)
        val dateSelectLayout: LinearLayout = findViewById(R.id.dateSelectLayout)
        val selectStartDateView: TextView = findViewById(R.id.selectStartDateView)
        val selectEndDateView: TextView = findViewById(R.id.selectEndDateView)
        val dialogCancelButton = findViewById<Button>(R.id.dialogCancelButton)
        val dialogConfirmButton = findViewById<Button>(R.id.dialogConfirmButton)

        if (title.isNotBlank()) {
            dialogTitleView.text = title
        }

        //根据选择项显示不同的内容区域
        if (conditionArray.isNotEmpty()) {
            val arrayAdapter = ArrayAdapter(
                ctx, android.R.layout.simple_spinner_dropdown_item, conditionArray
            )
            conditionSpinner.setSelection(0)
            conditionSpinner.adapter = arrayAdapter
            conditionSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    adapterView: AdapterView<*>?, view: View?, position: Int, id: Long
                ) {
                    if (position == 7) {
                        contentLayout.visibility = View.GONE
                        dateSelectLayout.visibility = View.VISIBLE

                        queryMode = QueryMode.DATE
                    } else {
                        contentLayout.visibility = View.VISIBLE
                        dateSelectLayout.visibility = View.GONE

                        //判断其他position
                        if (position == 0) {
                            contentSpinner.visibility = View.VISIBLE
                            inputView.visibility = View.GONE

                            //初始化contentSpinner
                            initContentSpinner(contentSpinner)

                            queryMode = QueryMode.TYPE
                        } else {
                            contentSpinner.visibility = View.GONE
                            inputView.visibility = View.VISIBLE

                            //初始化AppCompatAutoCompleteTextView
                            initTextView(position)

                            queryMode = QueryMode.INPUT
                        }
                    }
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {

                }
            }
        }

        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH) + 1
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        selectStartDateView.setOnClickListener {
            DatePickerDialog(ctx, { _, y, m, d ->
                selectStartDateView.text = String.format(
                    "%s-%s-%s", y, m.appendZero(), d.appendZero()
                )
            }, year, month, day).show()
        }

        selectEndDateView.setOnClickListener {
            DatePickerDialog(ctx, { _, y, m, d ->
                selectEndDateView.text = String.format(
                    "%s-%s-%s", y, m.appendZero(), d.appendZero()
                )
            }, year, month, day).show()
        }

        if (negativeBtn.isNotBlank()) {
            dialogCancelButton.text = negativeBtn
        }

        dialogCancelButton.setOnClickListener {
            listener.onCancelClick()
            dismiss()
        }

        if (positiveBtn.isNotBlank()) {
            dialogConfirmButton.text = positiveBtn
        }

        dialogConfirmButton.setOnClickListener {
            when (queryMode) {
                QueryMode.TYPE -> {
                    listener.onConfirmClick(
                        conditionSpinner.selectedItem.toString(),
                        contentSpinner.selectedItem.toString()
                    )
                }
                QueryMode.INPUT -> {
                    listener.onConfirmClick(
                        conditionSpinner.selectedItem.toString(),
                        inputView.text.toString()
                    )
                }
                else -> {
                    listener.onConfirmClick(
                        conditionSpinner.selectedItem.toString(),
                        selectStartDateView.text.toString(),
                        selectEndDateView.text.toString()
                    )
                }
            }
            dismiss()
        }
    }

    private fun initContentSpinner(contentSpinner: Spinner) {
        val arrayAdapter = ArrayAdapter(
            ctx, android.R.layout.simple_spinner_dropdown_item, LocaleConstant.CONTENT_ARRAY
        )
        contentSpinner.setSelection(0)
        contentSpinner.adapter = arrayAdapter
        contentSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?, view: View?, position: Int, id: Long
            ) {

            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }
    }

    private fun initTextView(position: Int) {
        //查库
        val autoCompleteData = HashSet<String>()
        CoroutineScope(Dispatchers.Main).launch {
            val labelBeans = withContext(Dispatchers.IO) {
                DataBaseManager.get.loadLabelByCondition(conditionArray[position], null)
            }
            for (labelBean in labelBeans) {
                when (position) {
                    1 -> autoCompleteData.add(labelBean.markerNumber)
                    2 -> autoCompleteData.add(labelBean.objectName)
                    3 -> autoCompleteData.add(labelBean.area)
                    4 -> autoCompleteData.add(labelBean.road)
                    5 -> autoCompleteData.add(labelBean.inspectionUnit)
                    6 -> autoCompleteData.add(labelBean.owner)
                    8 -> autoCompleteData.add(labelBean.markerId)
                }
            }

            //AppCompatAutoCompleteTextView逻辑
            val autoCompleteAdapter = ArrayAdapter(
                ctx, android.R.layout.simple_dropdown_item_1line, autoCompleteData.toArray()
            )
            inputView.setAdapter(autoCompleteAdapter)
        }
    }

    interface OnDialogButtonClickListener {
        fun onConfirmClick(selectedCondition: String, vararg contentValue: String)

        fun onCancelClick()
    }
}