package com.danding.yang800.Service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.danding.yang800.BuildConfig;
import com.danding.yang800.General.HttpCallBack;
import com.danding.yang800.General.Yang800App;
import com.danding.yang800.Util.VolleyUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
 * 此类可不用
 * */
public class LoginKeepService extends Service {

    SharedPreferences sp;
    RequestQueue requestQueue;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
    }

    // 获取位置
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        requestQueue = Volley.newRequestQueue(this);
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        //   keepLogin();
        Timer timer = new Timer();
        TimerTask tast = new TimerTask() {
            @Override
            public void run() {
                keepLogin();
            }
        };
        timer.schedule(tast, 0, 10 * 60 * 1000);
        return START_STICKY;
    }

    //    private void keepLogin() {
//        StringRequest stringRequest = new StringRequest(Request.Method.POST,
//                "http://" + BuildConfig.HOSTURL + "/xhr/login/loginHold.json",
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        Log.d("LoginActivity", response);
//                        // ToastUtil.show(LoginKeepService.this, response);
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            String code = json.getString("code");
//                            if (!code.equals("success")) {
//                                tokenLogin();
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//
//            @Override
//            public void onErrorResponse(VolleyError error) {
//
//            }
//        }) {
//            @Override
//            protected HashMap<String, String> getParams() { //
//                HashMap<String, String> map = new HashMap<String, String>();
//                return map;
//            }
//
//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                if (!sp.getString("Cookie", "").equals("")) {
//                    HashMap<String, String> headers = new HashMap<String, String>();
//                    headers.put("Cookie", sp.getString("Cookie", ""));
//                    return headers;
//                } else {
//                    return super.getHeaders();
//                }
//            }
//
//        };
//        stringRequest.setTag("POST_TAG");
//        requestQueue.add(stringRequest);
//
//
//    }
    public void keepLogin() {
        HashMap<String, String> map = new HashMap<String, String>();
        new VolleyUtil(this).request(this, "login.loginHold", false, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {

            }

            @Override
            public void onerrSuccess() {
                tokenLogin();
            }

            @Override
            public void onCatch() {

            }

            @Override
            public void onFail() {
            }
        });


    }

    //    private void tokenLogin() {
//        StringRequest stringRequest = new StringRequest(Request.Method.POST,
//                "http://" + BuildConfig.HOSTURL + "/xhr/login/tokenLogin.json",
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        Log.d("LoginActivity", response);
//                        // ToastUtil.show(LoginKeepService.this, response);
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            String code = json.getString("code");
//                            if (code.equals("success")) {
//                                JSONObject jsondata = json.getJSONObject("data");
//                                JSONObject jsonUser = jsondata.getJSONObject("user");
//                                String userId = jsonUser.getString("userId");
//                                sp.edit().putString("userId", userId).commit();
//                                String token = jsonUser.getString("token");
//                                sp.edit().putString("token", token).commit();
//                                JSONObject jsonStore = jsondata.getJSONObject("store");
//                                String storeId = jsonStore.getString("id");
//                                sp.edit().putString("storeId", storeId).commit();
//                            } else {
//                                sp.edit().putBoolean("login", false).commit();
//                                sp.edit().putString("WXcode", "").commit();
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//
//
//                    }
//                }, new Response.ErrorListener() {
//
//            @Override
//            public void onErrorResponse(VolleyError error) {
//            }
//        }) {
//            @Override
//            protected HashMap<String, String> getParams() { //
//                HashMap<String, String> map = new HashMap<String, String>();
//                map.put("token", sp.getString("token", ""));
//                map.put("epCode", sp.getString("epCode", ""));
//                return map;
//            }
//
//
//            @Override
//            public Map<String, String> getHeaders() throws AuthFailureError {
//                HashMap<String, String> headers = new HashMap<String, String>();
//                headers.put("Cookie", sp.getString("Cookie", ""));
//                return headers;
//            }
//        };
//        stringRequest.setTag("POST_TAG");
//        requestQueue.add(stringRequest);
//    }
    public void tokenLogin() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("token", sp.getString("token", ""));
        map.put("epCode", sp.getString("epCode", ""));
        new VolleyUtil(this).request(this, "login.tokenLogin", false, map, new HttpCallBack() {
            @Override
            public void onSuccess(JSONObject json) {
                try {
                    JSONObject jsondata = json.getJSONObject("result");
                    JSONObject jsonUser = jsondata.getJSONObject("user");
                    int userId = jsonUser.getInt("userId");
                    sp.edit().putInt("userId", userId).commit();
                    String token = jsonUser.getString("token");
                    sp.edit().putString("token", token).commit();
                    JSONObject jsonStore = jsondata.getJSONObject("store");
                    String storeId = jsonStore.getString("id");
                    sp.edit().putString("storeId", storeId).commit();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onerrSuccess() {
                sp.edit().putBoolean("login", false).commit();
                sp.edit().putString("WXcode", "").commit();
            }

            @Override
            public void onCatch() {

            }

            @Override
            public void onFail() {
            }
        });
    }
}
