package com.pan_american.android.ui.login

import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.data.model.login.network.LoginRequest
import com.pan_american.android.data.model.login.network.LoginResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityLoginBinding
import com.pan_american.android.ui.workspace.WorkspaceActivity
import com.pan_american.android.util.CommitButton
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class LoginActivity : BaseActivity<ActivityLoginBinding>() {

    override fun getViewBinding() = ActivityLoginBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 避免从桌面启动程序后，会重新实例化入口类的activity
        if (!this.isTaskRoot) {
            // 当前类不是该Task的根部，那么之前启动
            if (intent != null) {
                // 当前类是从桌面启动的
                if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == intent.action) {
                    // finish掉该类，直接打开该Task中现存的Activity
                    finish()
                    return
                }
            }
        }

        initViews()
        initEvents()
    }

    override fun initViews() {

        binding.loginButton.setText(resources.getString(R.string.login))

        binding.systemInfo.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            String.format(getString(R.string.system_info), packageManager.getPackageInfo(packageName, PackageManager.PackageInfoFlags.of(0)).versionName)
        } else {
            String.format(getString(R.string.system_info), packageManager.getPackageInfo(packageName, 0).versionName)
        }
    }

    override fun initEvents() {
        binding.loginButton.setOnClickListener {
            if (binding.account.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.account_input_hint))
            } else if (binding.password.text.isNullOrBlank()) {
                showMessage(resources.getString(R.string.password_input_hint))
            } else {
                login()
            }
        }

        binding.icpCode.setOnClickListener {
            val uri = Uri.parse("https://beian.miit.gov.cn")
            startActivity(Intent(Intent.ACTION_VIEW, uri))
        }
    }

    private fun login() {

        binding.loginButton.setButtonStatus(CommitButton.STATUS_IN_COMMITING)

        val loginRequest =
            LoginRequest(binding.account.text.toString(), binding.password.text.toString())
        val apiService = ServiceCreator.create<APIService>()

        apiService.login(loginRequest).enqueue(object : Callback<LoginResponse> {
            override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
                val loginResponse = response.body()
                if (loginResponse != null) {
                    if (loginResponse.code == 200) {
                        OASystem.token = "Bearer " + loginResponse.data.token
                        OASystem.userInfo = loginResponse.data.userInfo
                        OASystem.authData = loginResponse.data.authData
                        OASystem.unReadCount = loginResponse.data.unReadCount - loginResponse.data.announcementUnReadCount
                        OASystem.announcementUnReadCount = loginResponse.data.announcementUnReadCount
                        val intent = Intent(OASystem.context, WorkspaceActivity::class.java)
                        startActivity(intent)
                        back()
                    } else {
                        //登陆失败重新显示登录按钮
                        binding.loginButton.setButtonStatus(CommitButton.STATUS_COMMITTED)
                        showMessage(loginResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<LoginResponse>, t: Throwable) {

                //登陆失败重新显示登录按钮
                binding.loginButton.setButtonStatus(CommitButton.STATUS_COMMITTED)

                showErrorInfo(R.string.login_failed)
            }
        })
    }
}