package com.gingersoft.gsa.delivery_pick_mode.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication
import com.gingersoft.gsa.cloud.base.utils.toast.ToastUtils
import com.gingersoft.gsa.delivery_pick_mode.R
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.DeliveryConfig
import com.gingersoft.gsa.delivery_pick_mode.model.viewModel.DeliveryViewModel
import com.gingersoft.gsa.delivery_pick_mode.ui.activity.DeliverySettingActivity
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.TextAdapter
import com.gingersoft.gsa.delivery_pick_mode.ui.base.BaseFragment
import com.gingersoft.gsa.delivery_pick_mode.util.InjectorUtil
import com.jess.arms.utils.ArmsUtils
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.popup.QMUIPopup
import com.qmuiteam.qmui.widget.popup.QMUIPopups
import kotlinx.android.synthetic.main.update_delivery_fragment.*

class UpdateDeliveryFragment : BaseFragment(R.layout.update_delivery_fragment) {

    companion object {
        var deliveryMethod = arrayListOf("本店配送", "zeek", "lalamove")

        private const val info = "info"
        @JvmStatic
        fun newInstance(deliveryConfig: DeliveryConfig.Data.DeliveryInfo?): UpdateDeliveryFragment {
            return UpdateDeliveryFragment().apply {
                arguments = Bundle().apply {
                    putSerializable(info, deliveryConfig)
                }
            }
        }
    }

    private lateinit var viewModel: DeliveryViewModel
    var deliveryConfig: DeliveryConfig.Data.DeliveryInfo? = null

    var pop: QMUIPopup? = null
    var deliveryType = arrayListOf("短途送", "中途送", "長途送")
    var deliveryTypeTag = arrayListOf("SHORT_RANGE", "STANDARD", "LONG_DISTANCE")

    var selectDeliveryType = deliveryTypeTag[0]//用戶當前選中的配送類型
    var selectDeliveryMethodPosition = 0

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(activity?.viewModelStore!!, InjectorUtil.getDeliveryFactory())[DeliveryViewModel::class.java]

        top_bar_update_delivery.setTitle("配送設置")
        top_bar_update_delivery.setBackgroundColor(resources.getColor(R.color.theme_color))
        top_bar_update_delivery.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener { activity?.let { it.onBackPressed() } }

        deliveryConfig = arguments?.getSerializable(info) as DeliveryConfig.Data.DeliveryInfo?

        //初始化默認備送類型
        tv_delivery_type.text = deliveryType[0]
        tv_delivery_method.text = deliveryMethod[selectDeliveryMethodPosition]

        //如果數據不為空，那麼就是編輯，初始化數據
        deliveryConfig?.let {
            et_min_delivery_fee.setText(it.distributionFeeMin.toString())
            et_max_delivery_fee.setText(it.distributionFeeMax.toString())
            ed_delivery_fee.setText(it.distributionFee.toString())
            ed_start_delivery_fee.setText(it.deliveryCost.toString())
            ed_difference_fee.setText(it.lackPrice.toString())
            ed_desc.setText(it.desc)
            //備送類型
            if (deliveryTypeTag.indexOf(it.distributionType) != -1) {
                tv_delivery_type.text = deliveryType[deliveryTypeTag.indexOf(it.distributionType)]
            }
            selectDeliveryType = it.distributionType
            //備送方式
            tv_delivery_method.text = deliveryMethod[it.type]
            selectDeliveryMethodPosition = it.type
        }

        layout_delivery_type.setOnClickListener {
            //修改備送類型
            showPopup(it, deliveryType)
        }

        layout_delivery_method.setOnClickListener {
            //修改配送方式
            showPopup(it, deliveryMethod)
        }

        btn_save_delivery.setOnClickListener {
            //保存
            if (et_min_delivery_fee.text.isEmpty()) {
                ToastUtils.show(context, "請輸入最小運費值")
                return@setOnClickListener
            }
            if (et_max_delivery_fee.text.isEmpty()) {
                ToastUtils.show(context, "請輸入最大運費值")
                return@setOnClickListener
            }
            if (ed_delivery_fee.text.isEmpty()) {
                ToastUtils.show(context, "請輸入運費")
                return@setOnClickListener
            }
            if (ed_start_delivery_fee.text.isEmpty()) {
                ToastUtils.show(context, "請輸入最低消費")
                return@setOnClickListener
            }
            showLoading()
            if (deliveryConfig == null) {
                //新增
                viewModel.addDeliveryConfig(et_min_delivery_fee.text.toString(), et_max_delivery_fee.text.toString(), ed_delivery_fee.text.toString(), ed_start_delivery_fee.text.toString(), selectDeliveryType, selectDeliveryMethodPosition,
                        ed_desc.text.toString(), GsaCloudApplication.getRestaurantId(), GsaCloudApplication.getMemberId(), ed_difference_fee.text.toString()) {
                    cancelDialogForLoading()
                    if (it != null && it.success) {
                        ToastUtils.show(context, "保存成功")
                        (activity as DeliverySettingActivity).onBackPressed()
                    } else {
                        ToastUtils.show(context, "保存失敗")
                    }
                }
            } else {
                //編輯
                viewModel.updateDeliveryConfig(et_min_delivery_fee.text.toString(), et_max_delivery_fee.text.toString(), ed_delivery_fee.text.toString(), ed_start_delivery_fee.text.toString(), selectDeliveryType, selectDeliveryMethodPosition,
                        ed_desc.text.toString(), deliveryConfig!!.id, GsaCloudApplication.getRestaurantId(), GsaCloudApplication.getMemberId(), ed_difference_fee.text.toString(), 0) {
                    cancelDialogForLoading()
                    if (it != null && it.success) {
                        ToastUtils.show(context, "修改成功")
                        (activity as DeliverySettingActivity).onBackPressed()
                    } else {
                        ToastUtils.show(context, "修改失敗")
                    }
                }
            }
        }
    }

    var adapter: TextAdapter? = null
    private fun showPopup(it: View, list: MutableList<String>) {
        if (pop == null) {
            val view = LayoutInflater.from(context).inflate(R.layout.recyclerview, null)
            val listView = view.findViewById<RecyclerView>(R.id.ryview)
            listView.layoutManager = LinearLayoutManager(context)
            adapter = TextAdapter(list)
            adapter?.setOnItemClickListener { _, _, _ -> }

            listView.layoutParams.width = (ArmsUtils.getScreenWidth(context) * 0.7).toInt()
            listView.adapter = adapter

            pop = QMUIPopups.popup(context)
                    .preferredDirection(QMUIPopup.DIRECTION_CENTER_IN_SCREEN)
                    .view(view)
                    .radius(QMUIDisplayHelper.dp2px(context, 5))
                    .arrow(true)
                    .shadow(true)
                    .dimAmount(0.6f)
                    .offsetYIfTop(0)
                    .animStyle(QMUIPopup.ANIM_AUTO)
                    .show(it)
        } else {
            adapter?.setNewInstance(list)
            pop?.show(it)
        }
        adapter?.setOnItemClickListener { _, _, position ->
            when (it.id) {
                R.id.layout_delivery_type -> {
                    //修改備送類型
                    tv_delivery_type.text = list[position]
                    selectDeliveryType = deliveryTypeTag[position]
                }
                R.id.layout_delivery_method -> {
                    //修改備送方式
                    tv_delivery_method.text = list[position]
                    selectDeliveryMethodPosition = position
                }
            }
            pop!!.dismiss()
        }
    }

}
