package com.bbitcn.silk.ui.activity;

import android.app.Activity;
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.bbitcn.silk.base.BasePresenter;
import com.bbitcn.silk.model.net.Login;
import com.bbitcn.silk.ui.dialog.ConfirmDialog;
import com.bbitcn.silk.utils.MMKVUtil;
import com.bbitcn.silk.utils.global.Global;
import com.bbitcn.silk.utils.log.MyLog;
import com.bbitcn.silk.utils.network.Url;
import com.bbitcn.silk.utils.network.XHttpManager;
import com.bbitcn.silk.utils.network.XHttpShorthand;
import com.blankj.utilcode.util.EncryptUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

/**
 * @Author DuanKaiji
 * @CreateTime 2024年03月27日 13:51
 */
public class LoginActivityPresenter extends BasePresenter {

    private MutableLiveData<Integer> notice = new MutableLiveData<>();

    public MutableLiveData<Integer> getNotice() {
        return notice;
    }

    public LoginActivityPresenter(@NonNull Application application) {
        super(application);
        checkPermission();
    }

    /**
     * 登录
     *
     * @param account  账号
     * @param password 密码
     */
    public void login(String account, String password) {
        showLoadingDialog("正在登录中,请稍等");
        RequestParams params = XHttpManager.getInstance().getRequestParams(Url.login,false);
        params.addParameter("Platform", "1");
        params.addParameter("HardwareId", Global.getDeviceId());
        params.addParameter("TenantCode", Global.getCompanyId());
        params.addParameter("Account", account);
        params.addParameter("Password", EncryptUtils.encryptMD5ToString(password.getBytes()));
        x.http().post(params, new XHttpShorthand<Login>() {
            @Override
            public void success(Login model) {
                MyLog.app("登录成功");
                if(model.getResult()){
                    MMKVUtil.put(Global.USER_ACCOUNT, account);
                    MMKVUtil.put(Global.PASSWORD, password);
                    MMKVUtil.put(Global.TOKEN, model.getData().getTokenType() + " " + model.getData().getAccessToken());
                    notice.setValue(0);
                }else{
                    new ConfirmDialog(currentActivity, "提示", "登录失败：" + model.getMsg(), null).show();
                }
            }

            @Override
            public void error(Throwable e) {
                new ConfirmDialog(currentActivity, "提示", "登录失败：" + e.getMessage(), null).show();
                MyLog.appError("Token获取失败");
            }

            @Override
            public void myFinish() {
                super.myFinish();
                hideLoadingDialog();
            }
        });
    }

    private Activity currentActivity;

    public void setActivity(Activity activity) {
        this.currentActivity = activity;
    }

    /**
     * 检查与请求权限
     */
    void checkPermission() {
        XXPermissions.with(currentActivity)
                .permission(Permission.WRITE_EXTERNAL_STORAGE)
                .permission(Permission.READ_EXTERNAL_STORAGE)
                .permission(Permission.READ_PHONE_STATE)
                .permission(Permission.REQUEST_INSTALL_PACKAGES)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            MyLog.appError("获取部分权限成功，但部分权限未正常授予");
                            XXPermissions.startPermissionActivity(currentActivity, permissions);
                        }
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        if (doNotAskAgain) {
                            MyLog.app("被永久拒绝授权，需手动授予权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getApplication(), permissions);
                        } else {
                            MyLog.appError("权限请求失败");
                        }
                    }
                });
    }
}
