package com.sipai.jspatrol.Loading;

import android.content.Context;

import com.sipai.jspatrol.Base.BaseModel;
import com.sipai.jspatrol.Bean.LoginInfo;
import com.sipai.jspatrol.Bean.User;
import com.sipai.jspatrol.utils.Global.GlobalVal;
import com.sipai.jspatrol.utils.OKHttpUtils;
import com.sipai.jspatrol.utils.okHttpCookie.CookiesManager;

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

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * created by lvliming on 2019/9/11
 */
public class LoadingModel extends BaseModel<LoadingPresenter, LoadingContract.Model> {
    public LoadingModel(LoadingPresenter loginPresenter){
        super(loginPresenter);
    }

    @Override
    public LoadingContract.Model getContract() {
        return new LoadingContract.Model() {
            @Override
            public void executeData(Context context, HashMap<String, String> map, String server, String url) throws Exception {
                CookiesManager.clearCookie(context);
                OKHttpUtils.OKCallGet(map,server,url).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        String result = GlobalVal.NET_ERROR;
                        LoginInfo item = new LoginInfo();
                        if (result.equals(GlobalVal.NET_ERROR)) {
                            item.setStatus(false);
                        }else if (result.equals(GlobalVal.DATA_ERROR)){
                            item.setStatus(false);
                        }else {
                            item = parseData(result);
                        }
                        p.getContract().responseResult(item);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        if (result!=null&&!result.isEmpty()&&!result.contains("html")){
//                            res = result;
                            LoginInfo item = new LoginInfo();
                            if (result.equals(GlobalVal.NET_ERROR)) {
                                item.setStatus(false);
                            }else if (result.equals(GlobalVal.DATA_ERROR)){
                                item.setStatus(false);
                            }else if(result.contains("该设备未关联")){
                                item.setStatus(false);
                                item.setReason("该设备未关联该用户！请至平台关联！");
                            }else {
                                item = parseData(result);
                            }
                            p.getContract().responseResult(item);
                        }else {
                            result = GlobalVal.DATA_ERROR;
                            LoginInfo item = new LoginInfo();
                            if (result.equals(GlobalVal.NET_ERROR)) {
                                item.setStatus(false);
                            }else if (result.equals(GlobalVal.DATA_ERROR)){
                                item.setStatus(false);
                            }else {
                                item = parseData(result);
                            }
                            p.getContract().responseResult(item);
                        }
                    }
                });
            }

            @Override
            public void executeComData(Context context, HashMap<String, String> map, String server, String url, String token) throws Exception {
                OKHttpUtils.getClient().newCall(OKHttpUtils.OKHttpRequest(map,server,url)).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        String result = GlobalVal.NET_ERROR;
                        String bizs = "";
                        p.getContract().responseComResult(result,bizs);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String res = response.body().string();
                        if (res!=null&&!res.isEmpty()&&!res.contains("html")){
                            p.getContract().responseComResult(GlobalVal.RESULT_SUCCESS,res);
                        }else {
                            p.getContract().responseComResult(GlobalVal.DATA_ERROR,res);
                        }
                    }
                });
            }
        };
    }

    private LoginInfo parseData(String result) {
        LoginInfo info = new LoginInfo();
        User user = new User();
        try {
            JSONObject jsonObject = new JSONObject(result);
            String res = jsonObject.optString("res");
            if (jsonObject.optString("Access_Token") != null && !jsonObject.optString("Access_Token").isEmpty()) {
                user.setToken(jsonObject.optString("Access_Token"));
            } else {
                user.setToken("");
            }
            if (jsonObject.getBoolean("status")) {
                JSONObject json = new JSONObject(res);
                user.setCaption(json.optString("caption"));
                user.setName(json.optString("name"));
                user.setId(json.optString("id"));
                if (json.optString("totaltime")!=null&&!json.optString("totaltime").isEmpty()) {
                    user.setTotaltime(Double.parseDouble(json.optString("totaltime")));
                }else {
                    user.setTotaltime(0);
                }
                user.setLastlogintime(json.optString("lastlogintime"));
                if (json.optString("dept") != null && !json.optString("dept").isEmpty()) {
                    JSONObject jsonob = new JSONObject(json.optString("dept"));
                    if (jsonob.optString("patrolTypeId") != null && !jsonob.optString("patrolTypeId").isEmpty()) {
                        user.setPatrolTypeId(jsonob.optString("patrolTypeId"));
                    }
                } else {
                    user.setPatrolTypeId("P");
                }
                if (json.optString("roles").contains("管理员")){
                    user.setNfc("true");
                }else {
                    user.setNfc("false");
                }
                if (json.optString("roles").contains("提交")){
                    user.setSubTask("true");
                }else {
                    user.setSubTask("false");
                }

                info.setUser(user);
                info.setStatus(true);
            } else {
                info.setStatus(false);
                info.setReason("登录失败");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return info;
    }
}
