package com.bxzk.afxj.View;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.bxzk.afxj.Entity.LoginBeanOut;
import com.bxzk.afxj.retrofit.ApiManager;
import com.bxzk.afxj.retrofit.Node;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.bxzk.afxj.Contract.LoginContract;
import com.bxzk.afxj.Presenter.LoginPresenter;
import com.bxzk.afxj.R;
import com.bxzk.afxj.View.BaseActivity.BaseBarActivity;
import com.bxzk.afxj.application.BApplication;
import com.bxzk.afxj.database.CommonDaoUtils;
import com.bxzk.afxj.database.bean.User;
import com.bxzk.afxj.database.table.DaoUtilsStore;
import com.bxzk.afxj.retrofit.ModelFilteredFactory;
import com.bxzk.afxj.util.EventBusUtils;
import com.bxzk.afxj.util.Log;
import com.bxzk.afxj.util.SPUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

public class LoginAct extends BaseBarActivity<LoginContract.View, LoginPresenter> implements LoginContract.View {
    @BindView(R.id.et_pwd)
    EditText et_pwd;
    @BindView(R.id.et_user)
    EditText et_user;
    @BindView(R.id.btn_lg)
    Button btn_lg;
    @BindView(R.id.cl_root)
    ConstraintLayout cl_root;
    @BindView(R.id.cl_pop)
    ConstraintLayout cl_pop;
    @BindView(R.id.tv_pop_text)
    TextView tv_pop_text;
    @BindView(R.id.tv_version)
    TextView tv_version;
    @BindView(R.id.iv_rotate)
    ImageView iv_rotate;

    private boolean payAvaliable; //支付环境是否正常
    private Disposable initDispose;

    @Override
    protected int setBaseContextView() {
        return R.layout.activity_login;
    }

    @Override
    protected void initLHView(@Nullable Bundle savedInstanceState) {
        test2();
    }





    @Override
    public void initValue(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void inject() {
        getActivityComponent().inject(this);
    }

    @SuppressLint("MissingPermission")
    private void initPresenter() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.request(
                Manifest.permission.SYSTEM_ALERT_WINDOW,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_PHONE_STATE,

                Manifest.permission.INSTALL_PACKAGES

        ).subscribe(aBoolean -> {
        });


    }



    private void startEventRegister() {
        EventBusUtils.register(this);


    }

    private static final int REQUEST_CODE_WRITE_SETTINGS = 1;

    private void requestWriteSettings() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE_WRITE_SETTINGS);
    }


    @OnClick({R.id.btn_scan})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.btn_scan:


                break;
        }
    }

    private void initUser() {

        //用户ID生成器

        DaoUtilsStore.getInstance().getUserDaoUtils().deleteAll();
        ArrayList<User> mUserList = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId((long) i);
            user.setUserId(i + "");
            // 随机生成汉语名称
            user.setUserName("tt" + i);
            user.setAge(18 + random.nextInt(10));
            mUserList.add(user);
        }


        DaoUtilsStore.getInstance().getUserDaoUtils().insertMultiple(mUserList);


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1000) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "权限授予失败，无法开启悬浮窗", Toast.LENGTH_SHORT).show();
                } else {
                    requestWriteSettings();
//                    presentationPresenter.openSearchPresentation(LoginAct.this);
//                    uploadServiceControler.startUpService(LoginAct.this);

                    //有悬浮窗权限开启服务绑定 绑定权限
                }
            }
        } else if (requestCode == REQUEST_CODE_WRITE_SETTINGS) {
            if (Settings.System.canWrite(this)) {
                startEventRegister();
            }
        }
    }

    @Override
    public void onLogin(LoginBeanOut loginBeanOut) {
        SPUtils.put(BApplication.getContext(), "token", loginBeanOut.getToken());

    }

    @Override
    public LifecycleTransformer bindLifecycle() {
        return bindToLifecycle();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cl_pop = null;
        EventBusUtils.removeAllStickyEvents();
        EventBusUtils.unregister(this);
       /* if (uploadServiceControler != null)
            uploadServiceControler.finishService(this);
        if (presentationPresenter != null)
            presentationPresenter.finishService(LoginAct.this);*/


    }



    public void onInit() {



    }

    private void skipWifiCon() {
//        startActivity(new Intent(this, WifiConnectAct.class));
        if (payAvaliable) return;
        Intent intent = new Intent();
        intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
        startActivity(intent);
    }

    public boolean isPayAvaliable() {
        return payAvaliable;
    }

    public void setPayAvaliable(boolean payAvaliable) {
        this.payAvaliable = payAvaliable;
    }





    /**
     * 键盘事件
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (com.bxzk.afxj.Manage.ActivityManager.activities.size() == 1) {
            finish();
        }
    }



    public void test2() {
        Map<String,String> map=new HashMap<>();
        map.put("pwd",1+"");
        map.put("username",10+"");
        String request= Node.getRequestParams("UserLogin",map);
        RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), request);
        Observable<ResponseBody> login = ApiManager.getInstence().getXmlService().login(body);
        Observable<ResponseBody> loginWebBeanInObservable = ModelFilteredFactory.simpleCompose2(login);
        loginWebBeanInObservable.subscribe(new Observer<ResponseBody>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull ResponseBody loginWebBeanIn) {
                Log.e("");
            }

            @Override
            public void onError(@NonNull Throwable e) {
                Log.e("");

            }

            @Override
            public void onComplete() {

            }
        });
    }



}