package com.sagacloud.endpoints;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sagacloud.utils.CommonUtil;
import com.sagacloud.utils.Const;
import com.sagacloud.utils.DpUtils;
import com.sagacloud.utils.tables.HBaseTable;
import com.sagacloud.utils.tables.KeyObjRelTable;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ResourceContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Arrays;
import java.util.List;

/**
 * Created by wo on 11/18/19.
 */
@Path("qr_key_obj_rel")
public class QrKeyObjRel {
    @Context
    private ResourceContext resourceContext;

    @Path("/query")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String query(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) throws Exception {
        JSONObject postBody = JSONObject.parseObject(jsonStr);
        String key = postBody.getString("key");
        if(key == null){
            return DpUtils.errorJsonMsg("缺少key");
        }
        JSONArray arr = CommonUtil.query(false, HBaseTable.key_obj_rel, new JSONObject().fluentPut(KeyObjRelTable.KEY_PJ_ID, projectId.replace("Pj", ""))
                .fluentPut(KeyObjRelTable.KEY_KEY, key)).getJSONArray("Content");
        String objId = null;
        List<String> idPres = Arrays.asList("Pj#Bd#Fl#Sp#Eq#St#Pe#Si#Sh#Co#To".split("#"));
        if(arr.size() == 0){
            if(idPres.contains(key.substring(0, 2))){
                objId = key;
            }
        }else{
            objId = arr.getJSONObject(0).getString(KeyObjRelTable.KEY_OBJ_ID);
        }
        JSONObject reObj = new JSONObject().fluentPut("objId", objId);
        if(objId != null && objId.startsWith("Pe")){
            JSONArray array = JSONObject.parseObject(resourceContext
                    .getResource(Property.class).idQuery(projectId, String.format("{\"criterias\":[{\"id\":\"%s\"}]}", objId))).getJSONArray("Content");
            if(array.size() > 0){
                reObj.put("relation", array.getJSONObject(0).get("relation"));
            }
        }
        return DpUtils.returnJSONArray(new JSONArray().fluentAdd(reObj), "");
    }

    @Path("/b_create")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String batchCreate(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) throws Exception {
        JSONArray arr = JSONObject.parseObject(jsonStr).getJSONArray("criterias");
        JSONArray errs = this.validate(arr);
        if(errs.size() != 0){
            return  DpUtils.errorJson("").fluentPut("Error", errs).toString();
        }
        for (int i = 0; i < arr.size(); i++) {
            JSONObject item = arr.getJSONObject(i);
            item.put(KeyObjRelTable.KEY_PJ_ID, projectId.replace("Pj", ""));
        }
        return CommonUtil.insert(true, HBaseTable.key_obj_rel, arr).toString();
    }

    /**检验输入合法性
     * @param arr
     * @return
     * @throws Exception
     */
    private JSONArray validate(JSONArray arr) throws Exception {
        JSONArray errs = new JSONArray();
        List<String> idPres = Arrays.asList("Pj#Bd#Fl#Sp#Eq#St#Pe#Si#Sh#Co#To".split("#"));
        for(int i = 0; i < arr.size(); i++){
            JSONObject item = arr.getJSONObject(i);
            if(!item.containsKey("key") || !item.containsKey("obj_id")){
                item.put("error", "缺少字段key或者obj_id");
                errs.add(item);
                continue;
            }
            if(idPres.contains(item.getString("obj_id").substring(0, 2))){
                item.put("error", "obj_id非法");
                errs.add(item);
            }
        }
        return errs;
    }

    @Path("/b_delete")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String batchDel(@QueryParam(Const.PROJECT_ID) String projectId, String jsonStr) throws Exception {
        JSONArray arr = JSONObject.parseObject(jsonStr).getJSONArray("criterias");
        JSONArray errs = this.validateDel(arr);
        if(errs.size() != 0){
            return  DpUtils.errorJson("").fluentPut("Error", errs).toString();
        }
        for (int i = 0; i < arr.size(); i++) {
            JSONObject item = arr.getJSONObject(i);
            item.put(KeyObjRelTable.KEY_PJ_ID, projectId.replace("Pj", ""));
        }
        return CommonUtil.delete(true, HBaseTable.key_obj_rel, arr).toString();
    }

    /**检验输入合法性
     * @param arr
     * @return
     * @throws Exception
     */
    private JSONArray validateDel(JSONArray arr) throws Exception {
        JSONArray errs = new JSONArray();
        List<String> idPres = Arrays.asList("Pj#Bd#Fl#Sp#Eq#St#Pe#Si#Sh#Co#To".split("#"));
        for(int i = 0; i < arr.size(); i++){
            JSONObject item = arr.getJSONObject(i);
            if(!item.containsKey("key") && !item.containsKey("obj_id")){
                item.put("error", "字段key和obj_id必须有一个");
                errs.add(item);
                continue;
            }
            if(idPres.contains(item.getString("obj_id").substring(0, 2))){
                item.put("error", "obj_id非法");
                errs.add(item);
            }
        }
        return errs;
    }
}
