package com.unis.model;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;
import com.unis.model.bean.LoginBean;
import com.unis.model.bean.person.PersonBean;
import com.unis.model.bean.person.PersonTreeBean;
import com.unis.model.bean.user.UserBean;
import com.xyxsbj.mylibrary.tool.SPTool;
import com.xyxsbj.mylibrary.tool.ToastTool;

import org.json.JSONException;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名: com.unis.model
 * 类名: UserModel
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/11/25 15:55
 * 更新人:
 * 更新时间: 2020/11/25 15:55
 * 更新说明:
 * 版本号: 1.0
 */
public class UserModel {
    private UserModel() {
    }

    private static class SingleHolder {
        private static final UserModel INSTANCE = new UserModel();
    }

    public static UserModel get() {
        return SingleHolder.INSTANCE;
    }


    /**
     * 登录
     *
     * @param uName     用户名
     * @param uPassword 密码
     * @param callBack  回调
     */
    public void login(String uName, String uPassword, final DataCallback<LoginBean> callBack) {
        Map<String, String> map = new HashMap<>();
        map.put("uName", uName);
        map.put("uPassword", uPassword);
        OkGo.<String>post(UrlPath.login)
                .upJson(new Gson().toJson(map))
                .execute(new MyStringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        // 登录时 去掉token
                        request.removeHeader("Authorization");
                    }

                    @Override
                    protected void onSuccessResult(Response<String> response) throws JSONException {
                        Gson gson = new Gson();
                        String dataJson = getDataJson(response.body());
                        LoginBean bean = gson.fromJson(dataJson, LoginBean.class);

                        // 保存用户信息
                        String userInfo = gson.toJson(bean.getUser());
                        SPTool.saveString(Constant.KEY_USER, userInfo);
                        mUserBean = bean.getUser();

                        // 保存token
                        String accessToken = bean.getTokenInfo().getAccess_token();
                        SPTool.saveString(Constant.KEY_TOKEN, accessToken);

                        // 保存请求头Authorization: token_type+空格+access_token
                        String tokenType = bean.getTokenInfo().getToken_type();
                        String token = tokenType + " " + accessToken;
                        SPTool.saveString(Constant.KEY_HEAD_TOKEN, token);

                        // 添加cookie
//                        HttpUrl httpUrl = HttpUrl.parse(UrlPath.host);
//                        Cookie.Builder builder = new Cookie.Builder();
////                        Cookie cookieToken = builder.name("Token").value(tokenType + "%20" + accessToken).domain(httpUrl.host()).build();
//                        Cookie cookieToken = builder.name("Token").value(token).domain(httpUrl.host()).build();
//                        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
//                        cookieStore.saveCookie(httpUrl, cookieToken);
//
//                        CookieStore store = OkGo.getInstance().getCookieJar().getCookieStore();
//                        List<Cookie> allCookie = store.getAllCookie();
//                        LogTool.d("所有cookie如下：" + allCookie.toString());

                        // 设置请求头
//                        HttpHeaders headers = new HttpHeaders();
//                        headers.put("Authorization", token);
//                        OkGo.getInstance().init(BaseApp.getApp()).addCommonHeaders(headers);

                        if (callBack != null)
                            callBack.onSuccess(bean);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callBack.onError(getErrorMsg(response));
                    }
                });
    }

    /**
     * 刷新用户信息
     */
    public void refreshUser(final DataCallback<UserBean> callback) {
        UserBean user = getUser();
        if (user == null) {
            ToastTool.showLong("没有用户信息");
            callback.onError(null);
            return;
        }

        GetRequest<String> request = OkGo.get(UrlPath.user_info + "/" + user.getUid());
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response);
                SPTool.saveString(Constant.KEY_USER, json);
                UserBean bean = new Gson().fromJson(json, UserBean.class);
                mUserBean = bean;
                callback.onSuccess(bean);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callback.onError(getErrorMsg(response));
            }
        });
    }

    private UserBean mUserBean;

    /**
     * 获取用户信息
     */
    public UserBean getUser() {
        if (mUserBean != null)
            return mUserBean;
        String userJson = SPTool.getString(Constant.KEY_USER, null);
        if (userJson == null)
            return null;
        return new Gson().fromJson(userJson, UserBean.class);
    }

    /**
     * 获取请求头Token
     */
    public String getHeadToken() {
        return SPTool.getString(Constant.KEY_HEAD_TOKEN, null);
    }

    /**
     * 获取Token
     */
    public String getToken() {
        return SPTool.getString(Constant.KEY_TOKEN, null);
    }

    /**
     * 退出登录
     */
    public void logout(final DataCallback<String> callBack) {
        OkGo.<String>get(UrlPath.logout)
                .params("token", getToken())
                .execute(new MyStringCallback() {
                    @Override
                    protected void onSuccessResult(Response<String> response) throws JSONException {
                        callBack.onSuccess(response.body());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callBack.onError(getErrorMsg(response));
                    }
                });
    }

    /**
     * 移除用户信息
     */
    public void removeUser() {
        // 移除用户信息
        mUserBean = null;
        SPTool.remove(Constant.KEY_USER);
        // 移除token信息
        SPTool.remove(Constant.KEY_TOKEN);
        SPTool.remove(Constant.KEY_HEAD_TOKEN);
        // 移除字典
        SPTool.remove(Constant.KEY_ENUM_LIST);
        SPTool.remove(Constant.KEY_ENUM_ALL);
        // 移除库、仓、待办的选中项
        HouseModel.get().removeSelectHouse();
        DepotModel.get().removeSelectDepot();
        ProcessModel.get().removeSelectTodo();
    }

    /**
     * 获取人员树
     */
    public void getPersonTree(String depotId, final DataCallback<List<PersonTreeBean>> callBack) {
        OkGo.<String>get(UrlPath.person_tree)
                .params("depotId", depotId)
                .execute(new MyStringCallback() {
                    @Override
                    protected void onSuccessResult(Response<String> response) throws JSONException {
                        String json = getDataJson(response);
                        List<PersonTreeBean> list =
                                new Gson().fromJson(json, new TypeToken<List<PersonTreeBean>>() {
                                }.getType());
                        callBack.onSuccess(list);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callBack.onError(getErrorMsg(response));
                    }
                });
    }

    /**
     * 获取人员详情
     *
     * @param id
     * @param callBack
     */
    public void getPersonDetail(String id, final DataCallback<PersonBean> callBack) {
        OkGo.<String>get(UrlPath.person_detail + "/" + id)
                .execute(new MyStringCallback() {
                    @Override
                    protected void onSuccessResult(Response<String> response) throws JSONException {
                        String json = getDataJson(response);
                        PersonBean personBean = new Gson().fromJson(json, PersonBean.class);
                        callBack.onSuccess(personBean);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        callBack.onError(getErrorMsg(response));
                    }
                });

    }

    /**
     * 根据仓房id获取人员信息
     */
    public void getPersonDetailByHouse(String depotId, String houseId, final DataCallback<PersonBean> callback) {
        GetRequest<String> request = OkGo.get(UrlPath.person_detail_by_house);
        request.params("warehouseId", houseId);
        request.params("depotId", depotId);
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                String json = getDataJson(response);
                PersonBean bean = new Gson().fromJson(json, PersonBean.class);
                callback.onSuccess(bean);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callback.onError(getErrorMsg(response));
            }
        });
    }

    /**
     * 图片上传
     *
     * @param file
     * @param callback
     */
    public void uploadFile(File file, final DataCallback<String> callback) {
        PostRequest<String> request = OkGo.post(UrlPath.upload_file);
        request.params("file", file);
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                callback.onSuccess(getDataJson(response));
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callback.onError(getErrorMsg(response));
            }
        });

    }

    /**
     * 修改用户信息
     */
    public void update(Map<String, Object> userMap, final DataCallback<String> callback) {

        PostRequest<String> request = OkGo.post(UrlPath.person_update);
        request.upJson(new Gson().toJson(userMap));
        request.execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
                callback.onSuccess(null);
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                callback.onError(getErrorMsg(response));
            }
        });
    }


}
