package com.miya.fastcashier.ui

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.ViewModelProvider
import com.fastcashier.lib_common.base.BaseActivity
import com.fastcashier.lib_common.function.account.AccountService
import com.fastcashier.lib_common.function.pay.OrderRecordManageKit
import com.fastcashier.lib_common.function.print.PrintService
import com.fastcashier.lib_common.ui.dialog.CommonDialog
import com.fastcashier.lib_common.util.DateUtils
import com.fastcashier.lib_common.util.clickWithTrigger
import com.fastcashier.lib_common.util.getVersionName
import com.miya.fastcashier.R
import com.miya.fastcashier.databinding.ActivityMainBinding
import com.miya.fastcashier.ui.dialog.AuthorizePasswordInputDialog
import com.miya.fastcashier.util.*
import com.miya.fastcashier.util.manage.AccountPasswordManageKit
import com.miya.fastcashier.util.manage.LocalKeyDataMKManageKit
import com.miya.fastcashier.viewmodel.MainViewModel
import com.sdy.miya.moblie.component.pay.core.utils.PayLogFileUtils
import com.fastcashier.lib_common.util.LogFileUtils
import java.util.*

class MainActivity : BaseActivity() {

    //退出登录 二次确认弹窗
    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel
    private var dateSelectHelper: DateSelectHelper? = null
    private var confirmDialog: CommonDialog? = 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)

        initView()
        initData()
        initListener()
    }

    private fun initView() {
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)

        binding.tvStoreName.text = AccountService.getAccountInfo()?.shopInfo?.storeName
        binding.tvSlog.text = AccountService.getUserName()
        binding.tvVersion.text = getVersionName(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()
            }
        })

        checkAccountPassword()
        OrderRecordManageKit.clearOrderDataYeaterday()
        LogFileUtils.deleteLog(LogFileUtils.DAYS_INTERVAL_LOG_DELETE)
        PayLogFileUtils.deleteLog(LogFileUtils.DAYS_INTERVAL_LOG_DELETE)
    }

    private fun initListener() {
        binding.llPay.clickWithTrigger {
            PriceInputActivity.start(this@MainActivity)
        }
        binding.llRefund.clickWithTrigger {
            toRefund()
        }
        binding.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)
        }

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

        binding.llStatistic.clickWithTrigger {

            dateSelectHelper = DateSelectHelper(this@MainActivity) {

                var currentDate = Date()
                if (currentDate.time <= it.time) {
                    CenterToasty.error(this@MainActivity, getString(R.string.toast_warn_time))
                        .show()
                    return@DateSelectHelper
                }
                viewModel.orderStatistics(it, currentDate, false)
            }
            dateSelectHelper!!.showDatePicker()
        }

        binding.llBalance.clickWithTrigger {
            showConfirmBalanceDialog()
        }
    }

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

    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 showConfirmBalanceDialog() {
        if (confirmDialog == null || !confirmDialog!!.isShowing) {
            confirmDialog = CommonDialog(this)
            confirmDialog!!.setCustomMessage(getString(R.string.app_text_confirm_balance))
                .setNegativeStr(getString(R.string.cancel))
                .setPositiveStr(getString(R.string.sure))
                .setMessageGravity(Gravity.CENTER_HORIZONTAL)
                .setOnClickListener(object : CommonDialog.OnDialogClickListener {
                    override fun onNegativeClick() {
                        confirmDialog!!.dismiss()
                        confirmDialog = null
                    }

                    override fun onPositiveClick() {
                        toBalance()
                        confirmDialog!!.dismiss()
                        confirmDialog = null
                    }
                })
                .show()
        }
    }

    private fun toBalance() {
        //上次记录的时间，或者当天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)
        }
    }

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