package com.xwkj.jcjcgz.mvp.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hjq.toast.ToastUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.xwkj.jcjcgz.di.component.DaggerLoginComponent;
import com.xwkj.jcjcgz.mvp.contract.LoginContract;
import com.xwkj.jcjcgz.mvp.model.entity.Login;
import com.xwkj.jcjcgz.mvp.presenter.LoginPresenter;

import com.xwkj.jcjcgz.R;
import com.zkjc.common.base.ZkjcBaseActivity;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/09/2024 14:59
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class LoginActivity extends ZkjcBaseActivity<LoginPresenter> implements LoginContract.View {
    private Handler handler = new Handler();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
//        onTime(0L);
    }

    private void onTime(long time) {

        handler.postDelayed(() -> {
            initXdjaReccvier();
        }, time);
    }

    private void initXdjaReccvier() {
        Uri uri = Uri.parse("content://com.ydjw.ua.getCredential");
        Bundle pararms = new Bundle();
        String paramsMessageId = UUID.randomUUID().toString();
        pararms.putString("messageId", paramsMessageId);
        pararms.putString("version", "1");
        pararms.putString("appId", "220000000000-3-1-19f3ce6443964fb0825538b0d9e89c39");
        pararms.putString("orgId", "220000000000");
        pararms.putString("networkAreaCode", "3");
        pararms.putString("packageName", "com.zkjc.sylzxtn");
        Bundle bundle = getContentResolver().call(uri, "", null, pararms);
        if (bundle == null) {
            ToastUtils.show("获取应用凭证失败！！！");
        }
        String messageId = bundle.getString("messageId");
        if (messageId.equals(paramsMessageId)) {
            String userCredential = bundle.getString("userCredential");
            String appCredential = bundle.getString("appCredential");
            if (!TextUtils.isEmpty(userCredential) && !TextUtils.isEmpty(appCredential)) {
                getAddress(appCredential, userCredential);
            } else {
                onTime(3000L);
            }
        }
    }

    private void getAddress(String appCredential, String userCredential) {
        SharedPreferences sp = getSharedPreferences("sys", MODE_PRIVATE);
        Uri uri = Uri.parse("content://com.ydjw.rsb.getResourceAddress");
        Bundle pararms = new Bundle();
        String paramsMessageId = UUID.randomUUID().toString();
        pararms.putString("messageId", paramsMessageId);
        pararms.putString("version", "1");
        pararms.putString("appCredential", appCredential);
        Bundle bundle = getContentResolver().call(uri, "", null, pararms);
        if (bundle == null) {
            ToastUtils.show("获取应用地址失败！！！");
            return;
        }
        String messageId = bundle.getString("messageId");
        if (messageId.equals(paramsMessageId)) {
            String resourceList = bundle.getString("resourceList");
            int code = bundle.getInt("resultCode");
            if (code == 0) {
                ToastUtils.show("寻址成功");
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("appCredential", appCredential);
                edit.putString("userCredential", userCredential);
                edit.putString("resourceList", resourceList);
                System.out.println("寻址" + resourceList);
                edit.commit();
            }
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }
    public void login(View view) {
        Map<String, String> map = new HashMap<>();
        map.put("username", "admin");
        map.put("password", /*MD5.md5("123456")*/"21232f297a57a5a743894a0e4a801fc3");
        map.put("tenantId", "000000");
        map.put("grant_type", "password");
        map.put("scope", "all");
        map.put("code", "asdf");

        mPresenter.login(map);
    }
    @Override
    public void onSuccess(String result) {
        try {
            SharedPreferences sharedPreferences = getSharedPreferences("sys", MODE_PRIVATE);
            System.out.println("用户信息" + result);
            JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
            if (jsonObject.has("access_token")) {
                Gson gson = new Gson();
                Login entity = gson.fromJson(result, Login.class);
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString("token", entity.getAccess_token());
                edit.putString("refresh_token", entity.getRefresh_token());
                edit.putString("userName", entity.getReal_name());
                edit.putString("tenantId", entity.getTenant_id());
                edit.putString("account", entity.getAccount());
                edit.putString("tokenType", entity.getToken_type());
                edit.putString("userId", entity.getUser_id());
                edit.putInt("expires_in", entity.getExpires_in());
                edit.putString("dept_id", entity.getDept_id());
                edit.putString("phone", entity.getPhone());
                edit.putString("dept_name", entity.getDept_name());
                edit.putString("jh", entity.getPoliceNumber());
                edit.putString("role_name", entity.getRole_name());
                edit.putBoolean("isFirst", false);

                edit.commit();
//                ArmsUtils.startActivity(MainActivity.class);
//                finish();
            } else {
                String error_description = jsonObject.get("error_description").getAsString();
                ToastUtils.show(error_description);
            }
        } catch (Exception e) {
            ToastUtils.show("登录失败！" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void onError(Throwable t) {

    }
}
