package com.miya.fastcashier.ui

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider
import com.miya.fastcashier.databinding.ActivityMainBinding
import com.miya.fastcashier.service.AccountService
import com.miya.fastcashier.service.PrintService
import com.miya.fastcashier.ui.dialog.AuthorizePasswordInputDialog
import com.miya.fastcashier.utils.*
import com.miya.fastcashier.utils.manage.AccountPasswordManageKit
import com.miya.fastcashier.utils.manage.LocalKeyDataMKManageKit
import com.miya.fastcashier.utils.manage.OrderRecordManageKit
import com.miya.fastcashier.viewmodel.MainViewModel
import com.miya.print.utils.PrintLogger
import java.util.*

class MainActivity : BaseActivity() {

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

    companion object {
        @JvmStatic
        fun start(context: AppCompatActivity) {
            val intent = Intent()
            intent.setClass(context, MainActivity::class.java)
            context.startActivity(intent)
        }
    }

    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 ivSetting = binding.ivSetting
        val tvStoreName = binding.tvStoreName
        val tvSlog = binding.tvSlog

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

        llPay.clickWithTrigger {
            PriceInputActivity.start(this@MainActivity)
        }
        llRefund.clickWithTrigger {
            toRefund()
        }
        tvPrintLast.clickWithTrigger {
            try {
                PrintService.printLastOrderInfo()
            } catch (e: Exception) {
                e.message?.let { it1 -> CenterToasty.error(this, it1, Toast.LENGTH_SHORT).show() };
            }
        }
        binding.llSearchOrder.clickWithTrigger {
            SearchOrderActivity.start(this@MainActivity)
        }

        ivSetting.clickWithTrigger {
            SettingActivity.start(this@MainActivity)
        }

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

        binding.llBalance.clickWithTrigger {
            //上次记录的时间，或者当天0点
            var timeMillis = LocalKeyDataMKManageKit.getBalanceDate()
            if (timeMillis > 0L && timeMillis <= System.currentTimeMillis()) {
                val currentDate = Date()
                var daysAgoCurrent: Long = DateUtils.getDaysAgo(currentDate, 1)
                if (timeMillis <= daysAgoCurrent) {
                    timeMillis = daysAgoCurrent
                }
                viewModel.orderStatistics(Date(timeMillis), currentDate, 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()
        checkAccountPassword()
        OrderRecordManageKit.clearOrderDataYeaterday()
        LogFileUtils.deleteLog(LogFileUtils.DAYS_INTERVAL_LOG_DELETE)
    }

    private fun toRefund() {
        val FRAGMENT_TAG = "Authorize_Password"
        val fm: FragmentManager = getSupportFragmentManager()
        val oldFrag = fm.findFragmentByTag(FRAGMENT_TAG)
        if (oldFrag != null) {
            fm.beginTransaction().remove(oldFrag).commitAllowingStateLoss()
        }
        AuthorizePasswordInputDialog.newInstance().show(fm, FRAGMENT_TAG)
    }

    private fun checkAccountPassword() {
        AccountPasswordManageKit.get().checkAccountPassword(this)
    }

    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 {
                LocalKeyDataMKManageKit.putBalanceDate(it)
            }
            result.onFailure { e ->
                CenterToasty.error(this@MainActivity, e.message ?: "").show()
            }
        })
    }

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