package com.lsw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.core.Controller;
import com.jfinal.json.FastJson;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Record;

import java.util.Iterator;
import java.util.Map;

public class BaseController extends Controller {

    /**
     * 这个主要用于get请求的传递参数
     *
     * @return
     */
    protected Kv getParam() {
        Kv kv =Kv.create();
        Map<String, String[]> paraMap = getRequest().getParameterMap();
        Iterator var3 = paraMap.entrySet().iterator();
        while (var3.hasNext()) {
            Map.Entry<String, String[]> entry = (Map.Entry) var3.next();
            String[] values = (String[]) entry.getValue();
            String value = values != null && values.length > 0 ? values[0] : null;
            kv.set(entry.getKey(), "".equals(value) ? null : value);
        }
        return kv;
    }

    /**
     * 这个主要用于post请求的传递参数
     *
     * @return
     */
    protected Record getData() {
        return new Record().setColumns(FastJson.getJson().parse(getRawData(), Map.class));
    }

    protected JSONArray getArray() {
        return JSON.parseArray(getRawData());
    }

    /**
     * 成功并携带数据
     *
     * @param data
     */
    public void renderSuccess(Object data) {
        Record record = new Record();
        record.set("code", 200);
        record.set("data", data);
        record.set("msg", "操作成功");
        renderJson(record);
    }

    /**
     * 成功并自定义提示消息
     *
     * @param string
     */
    public void renderSuccess(String string) {
        Record record = new Record();
        record.set("code", 200);
        record.set("msg", string);
        renderJson(record);
    }

    /**
     * 成功
     *
     * @param
     */
    public void renderSuccess() {
        Record record = new Record();
        record.set("code", 200);
        record.set("msg", "操作成功");
        renderJson(record);
    }

    /**
     * 失败信息
     *
     * @param string
     */
    public void renderError(String string) {
        Record record = new Record();
        record.set("code", 500);
        record.set("msg", string);
        renderJson(record);
    }
}
