package com.sagacloud.endpoints.mng;
/*
 * Author: Jxing
 * Create Time: 2017/10/16
 */

import com.sagacloud.dict.InfosUtil;
import com.sagacloud.dict.TypeToInfosMap;
//import com.sagacloud.json.JSONArray;
//import com.sagacloud.json.JSONObject;
//import com.sagacloud.json.JSONValue;
import com.alibaba.fastjson.*;
import com.sagacloud.utils.CommonUtil;
import com.sagacloud.utils.DpUtils;
import com.sagacloud.utils.objects.CommonQueryCriteria;
import com.sagacloud.utils.tables.ActivityLogTable;
import com.sagacloud.utils.tables.HBaseTable;
import com.sagacloud.utils.tables.ObjInfosTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;

@Path("mng/activity")
public class ActivityMonitor {

    private static final Logger log = LoggerFactory.getLogger(ActivityMonitor.class);
    @Path("/select")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    public String select(String jsonStr) {
        try {
            JSONObject criteria = JSONObject.parseObject(jsonStr);
            CommonQueryCriteria cqc = CommonUtil.generateCommonQueryCriteria(criteria);
            if(criteria.containsKey("project_id"))
            {
                String id = criteria.get("project_id").toString();
                criteria.put("project_id", id.substring(2));
            }
            criteria.remove("limit");
            JSONObject object = CommonUtil.query(false, HBaseTable.activity_log, criteria);
            if(object.get("Result").equals("success"))
            {
                HashMap<String, ArrayList<JSONObject>> objectHashMap = new HashMap<>(); //  id  -->  JSONObject
                JSONArray arr = (JSONArray) object.get("Content");
                if(arr.size() == 0) {
                    if(cqc.getSkip() == null)
                        return DpUtils.returnJSONArray(arr, "");
                    return DpUtils.returnJSONArray(arr, "", (long) arr.size(), 0L);  // 查出来没有数据
                }
                JSONArray batchInfo_LocalName = new JSONArray();
                JSONObject timeRange = new JSONObject();
                timeRange.put("$lte", CommonUtil.getTime());
                if(TypeToInfosMap.typeToInfo.isEmpty())
                    TypeToInfosMap.synCache();
                // 分页
                long from = 0;
                int count = arr.size();
                if(cqc.getSkip() != null)
                {
                    from = cqc.getSkip() == null? 0:cqc.getSkip();
                    count = (cqc.getSkip_count() == null) ? arr.size() : cqc.getSkip_count();
                }
                cqc.setSkip_totalCount((long)arr.size());
                JSONArray retDataArray = new JSONArray();
                for(int i = arr.size() - (int)from - 1; (i > -1) && (count > 0); --i, --count)
                {
                    JSONObject localNameCriteria = new JSONObject();
                    JSONObject obj = (JSONObject) arr.get(i);
                    String projectId = obj.get(ActivityLogTable.KEY_PJ_ID).toString();
                    String obj_type = obj.get(ActivityLogTable.KEY_OBJ_TYPE).toString();
                    String obj_id = obj.get(ActivityLogTable.KEY_OBJ_ID)==null? "":obj.get(ActivityLogTable.KEY_OBJ_ID).toString();

                    localNameCriteria.put(ObjInfosTable.KEY_PJ_ID, projectId);
                    localNameCriteria.put(ObjInfosTable.KEY_OBJ_TYPE, obj_type);
                    localNameCriteria.put(ObjInfosTable.KEY_OBJ_ID, obj_id);
//                    try {
                    localNameCriteria.put(ObjInfosTable.KEY_INFO_ID, InfosUtil.getInfoLocalName(obj_type));
//                    }catch (Exception ex)
//                    {
//                        arr.remove(i);
//                        ++count;
//                        continue;
//                    }
                    localNameCriteria.put(ObjInfosTable.KEY_TIME, timeRange);
                    batchInfo_LocalName.add(localNameCriteria);
                    // -----
                    StringBuilder fakeId = new StringBuilder();
                    fakeId.append(obj.get(ActivityLogTable.KEY_PJ_ID)).append(obj.get(ActivityLogTable.KEY_OBJ_TYPE)).append(obj.get(ActivityLogTable.KEY_OBJ_ID));
                    ArrayList<JSONObject> obj_arr = null;
                    if(!objectHashMap.containsKey(fakeId.toString()))
                    {
                        obj_arr = new ArrayList<>();
                        objectHashMap.put(fakeId.toString(), obj_arr);
                    }else
                        obj_arr = objectHashMap.get(fakeId.toString());
                    obj_arr.add(obj);
                    // --------
                    obj.remove(ActivityLogTable.KEY_PJ_ID);
                    obj.remove(ActivityLogTable.KEY_OBJ_TYPE);
                    obj.remove(ActivityLogTable.KEY_OBJ_ID);
                    obj.put("id", CommonUtil.combineId(projectId,obj_type, obj_id));
                    if(obj.get(ActivityLogTable.KEY_INFO_ID) != null )
                    {
                        String name = TypeToInfosMap.getInfoName(obj_type, obj.get(ActivityLogTable.KEY_INFO_ID).toString());
                        if(name.length() > 0)
                        {
                            obj.put(ActivityLogTable.KEY_INFO_ID, name);
                        }
                    }
                    retDataArray.add(obj);
                }
                if(batchInfo_LocalName.size() == 0) {
                    if(cqc.getSkip() == null)
                        return DpUtils.returnJSONArray(batchInfo_LocalName, "");
                    return DpUtils.returnJSONArray(batchInfo_LocalName, "", (long) batchInfo_LocalName.size(), cqc.getSkip_totalCount());// 按skip来找, 没有数据
                }
                JSONObject infosValueResult = CommonUtil.combine_query(HBaseTable.obj_infos, batchInfo_LocalName);
                if(infosValueResult.get("Result").equals("success"))
                {
                    JSONArray array_infos = (JSONArray) infosValueResult.get("Content");
                    for(int i =0; i < array_infos.size(); ++i)
                    {
                        JSONObject object1 = (JSONObject) array_infos.get(i);
                        StringBuilder fakeId = new StringBuilder();
                        fakeId.append(object1.get(ActivityLogTable.KEY_PJ_ID)).append(object1.get(ActivityLogTable.KEY_OBJ_TYPE)).append(object1.get(ActivityLogTable.KEY_OBJ_ID));
                        ArrayList<JSONObject> objects_arr = objectHashMap.get(fakeId.toString());
                        Object value =  CommonUtil.getValue(object1);
                        if(objects_arr != null)
                        {
                            for(JSONObject single : objects_arr)
                                single.put("name", value);
                        }
                    }
                }
                //CommonUtil.reverseJSONArray(retDataArray);
                if(cqc.getSkip() == null)
                    return DpUtils.returnJSONArray(retDataArray, "");
                return DpUtils.returnJSONArray(retDataArray, "", (long)retDataArray.size(), cqc.getSkip_totalCount());
            }else
            {
                return DpUtils.errorJsonMsg("读取行为日志失败.");
            }
        }catch (Exception ex)
        {
            ex.printStackTrace();
            return DpUtils.errorJsonMsg(ex.getMessage());
        }
    }
}
