package com.miya.fastcashier.ui

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.miya.fastcashier.R
import com.miya.fastcashier.databinding.ActivityLoginBinding
import com.miya.fastcashier.databinding.ActivityMainBinding
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.service.PrintService
import com.miya.fastcashier.ui.dialog.MessageDialog
import com.miya.fastcashier.utils.CenterToasty
import com.miya.fastcashier.utils.DateSelectHelper
import com.miya.fastcashier.utils.clickWithTrigger
import com.miya.fastcashier.viewmodel.MainViewModel
import com.sdy.miya.moblie.component.pay.platform.bean.PayServiceResponse
import com.tencent.mmkv.MMKV
import java.lang.Exception
import java.util.*

class MainActivity : BaseActivity() {

    //退出登录 二次确认弹窗
    private var alertDialog: MessageDialog? = null
    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel
    private var dateSelectHelper: DateSelectHelper? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        val llPay = binding.llPay
        val llRefund = binding.llRefund
        val tvPrintLast = binding.tvPrintLast
        val ivLoginOut = binding.ivLoginOut
        val tvStoreName = binding.tvStoreName
        val tvSlog = binding.tvSlog

        tvStoreName.text = AccountService.getAccountInfo()?.shopInfo?.storeName
        tvSlog.text = AccountService.getUserName()

        llPay.clickWithTrigger {
            val intent = Intent()
            intent.setClass(this@MainActivity, PriceInputActivity::class.java)
            startActivity(intent)
        }
        llRefund.clickWithTrigger {
            val intent = Intent()
            intent.setClass(this@MainActivity, RefundActivity::class.java)
            startActivity(intent)
        }
        tvPrintLast.clickWithTrigger {
            try {
                PrintService.printLastOrderInfo()
            } catch (e: Exception) {
                e.message?.let { it1 -> CenterToasty.error(this, it1, Toast.LENGTH_SHORT).show() };
            }
        }
        binding.llSearchOrder.clickWithTrigger {
            val intent = Intent(this@MainActivity, SearchOrderActivity::class.java)
            startActivity(intent)
        }

        ivLoginOut.clickWithTrigger {
            loginOut()
        }

        binding.llStatistic.clickWithTrigger {
            if (dateSelectHelper == null) {
                dateSelectHelper = DateSelectHelper(this@MainActivity) {
                    viewModel.orderStatistics(it, Date(), false)
                }
            }
            dateSelectHelper!!.showDatePicker()
        }

        binding.llBalance.clickWithTrigger {
            //上次记录的时间，或者当天0点
            val timeMillis = MMKV.defaultMMKV().getLong("balanceDate", 0L)
            if (timeMillis > 0L && timeMillis <= System.currentTimeMillis()) {
                viewModel.orderStatistics(Date(timeMillis), Date(), true)
            } else {
                val startDate = Calendar.getInstance()
                startDate.set(
                    startDate.get(Calendar.YEAR),
                    startDate.get(Calendar.MONTH),
                    startDate.get(Calendar.DAY_OF_MONTH),
                    0,
                    0,
                    0
                )
                viewModel.orderStatistics(startDate.time, Date(), true)
            }
        }


        initData()
    }

    private fun initData() {
        viewModel.statisticsLiveData.observe(this, { result ->
            result.onSuccess {

            }
            result.onFailure { e ->
                CenterToasty.error(this@MainActivity, e.message ?: "").show()
            }
        })

        viewModel.balanceLiveData.observe(this, { result ->
            result.onSuccess {
                MMKV.defaultMMKV().putLong("balanceDate", it)
            }
            result.onFailure { e ->
                CenterToasty.error(this@MainActivity, e.message ?: "").show()
            }
        })
    }


    private fun loginOut() {
        if (null == alertDialog) {
            alertDialog = MessageDialog(this)
                .setCustomMessage("是否确认退出登录账号")
                .setPositiveButton("确认退出") { _, _ ->
                    run {
                        MMKV.defaultMMKV().clearAll()
                        AccountService.setAccountInfo(null)

                        val intent = Intent()
                        intent.setClass(this@MainActivity, LoginActivity::class.java)
                        startActivity(intent)

                        finish()
                    }
                }
        }
        alertDialog?.show()
    }

    override fun onDestroy() {
        dateSelectHelper?.dismiss()
        super.onDestroy()
    }
}