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.unis.model.bean.MultiDepotBean;
import com.xyxsbj.mylibrary.tool.SPTool;

import org.json.JSONException;

import java.lang.reflect.Type;
import java.util.List;

/**
 * 包名: com.unis.model
 * 类名: DepotModel
 * 作用描述:
 * 创建人: mQ
 * 创建时间: 2020/12/14 9:53
 * 更新人:
 * 更新时间: 2020/12/14 9:53
 * 更新说明:
 * 版本号: 1.0
 */
public class DepotModel {
    private DepotModel() {
    }

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

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

    /**
     * 根据库id查询多级列表
     *
     * @param callBack
     */
    public void getMultiList(final DataCallback<List<MultiDepotBean>> callBack) {
        String depotId = UserModel.get().getUser().getDepotId();
        OkGo.<String>get(UrlPath.depot_multi_list)
                .params("depotId", depotId)
                .execute(new MyStringCallback() {
                    @Override
                    protected void onSuccessResult(Response<String> response) throws JSONException {
                        String dataJson = getDataJson(response.body());
                        Type type = new TypeToken<List<MultiDepotBean>>() {
                        }.getType();
                        List<MultiDepotBean> list = new Gson().fromJson(dataJson, type);
                        callBack.onSuccess(list);
                    }

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

    /**
     * 保存所选的库
     */
    public void saveSelectDepot(MultiDepotBean bean) {
        SPTool.saveString(Constant.KEY_SELECT_DEPOT, new Gson().toJson(bean));
    }

    /**
     * 获取所选的库
     */
    public MultiDepotBean getSelectDepot() {
        String json = SPTool.getString(Constant.KEY_SELECT_DEPOT, null);
        if (json == null)
            return null;
        MultiDepotBean bean = new Gson().fromJson(json, MultiDepotBean.class);
        return bean;
    }

}
