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.AnnounceBean;

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

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


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

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

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

    /**
     * 获取公告列表
     */
    public void getList(int page, final DataCallback<List<AnnounceBean>> callback) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page);
        map.put("pageSize", 10);
        OkGo.<String>post(UrlPath.announce_list)
                .upJson(new Gson().toJson(map))
                .execute(new MyStringCallback() {
                    @Override
                    protected void onSuccessResult(Response<String> response) throws JSONException {
                        String json = getDataJson(response);
                        JSONObject object = new JSONObject(json);
                        JSONArray jsonArray = object.getJSONArray("records");
                        if (jsonArray == null || jsonArray.length() == 0) {
                            callback.onSuccess(new ArrayList<AnnounceBean>());
                            return;
                        }
                        List<AnnounceBean> list =
                                new Gson().fromJson(jsonArray.toString(),
                                        new TypeToken<List<AnnounceBean>>() {
                                        }.getType());
                        callback.onSuccess(list);
                    }

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

    /**
     *  公告已读
     * @param id
     */
    public void read(String id) {
        OkGo.<String>post(UrlPath.announce_read + "/" + id).execute(new MyStringCallback() {
            @Override
            protected void onSuccessResult(Response<String> response) throws JSONException {
            }

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

}
