package com.zhangmeng.online.exam.ui.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zhangmeng.online.exam.ui.module.Subject;
import com.zhangmeng.online.exam.ui.utils.ApiUtils;
import com.zhangmeng.online.exam.ui.module.SubjectType;
import com.zhangmeng.online.exam.ui.utils.HttpUtils;

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

/**
 * @author zm
 * @date 2025/4/1 14:37
 * @version: 1.0
 */
public class SubjectService {

    public static List<SubjectType> getALLSubjectType() {
        Map<String, Object> params = new HashMap<>();
        params.put("token", UserService.getCurrentUser().getToken());
//        params.put("token", HttpUtils.Token);
        String response = HttpUtils.GET(ApiUtils.API_URL + "/subject/getALLSubjectType", params);
        JSONObject jsonObject = JSONObject.parseObject(response);
        List<SubjectType> questionTypes = new ArrayList<>();
        if (jsonObject.getIntValue("code") == 200) {
            questionTypes = JSONArray.parseArray(jsonObject.getString("data"), SubjectType.class);
        }
        return questionTypes;
    }

    public static boolean saveSubject(Subject subject) {

        Map<String, Object> map = new HashMap<>();
        map.put("id", subject.getId() == null? "" : subject.getId());
        map.put("name", subject.getName());
        map.put("desc", subject.getDesc());
        map.put("code", subject.getCode());
        String result = HttpUtils.POST(ApiUtils.API_URL + "/subject/saveSubject", map);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject.getIntValue("code") == 200;
    }

    public static Subject getSubjectById(String id) {

        Subject subject = null  ;
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        String result = HttpUtils.GET(ApiUtils.API_URL + "/subject/getSubjectById",params);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getIntValue("code") == 200) {
            subject = new Subject();
            JSONObject data = jsonObject.getJSONObject("data");
            subject.setId(data.getString("id"));
            subject.setName(data.getString("name"));
            subject.setCode(data.getString("code"));
            subject.setDesc(data.getString("desc"));
        }
        return subject;
    }
}
