package cn.com.capcloud.api.action.service;

import cn.com.capcloud.api.KHCResponseEntity;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONArray;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.noentitydb.BaseDao;
import cn.com.capcloud.core.noentitydb.BaseService;
import cn.com.capcloud.core.noentitydb.DBCheck;
import cn.com.capcloud.core.system.user.User;
import cn.com.capcloud.core.system.user.UserService;
import cn.com.capcloud.core.util.IPUtil;
import cn.com.capcloud.core.util.TblLogNames;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class LogService {

    @Autowired
    private UserService userService;
    @Autowired
    private MongoService mongoService;
    @Autowired
    private BaseService baseService;

    /**
     *
     * @param cudType 操作类型
     * @param ids 操作对象id
     * @param dsMap 数据源Map
     * @param request
     * @param newSaveData 保存或修改后的数据对象
     * @param oldSaveData 修改前的数据对象
     */
    public void cudLogSave(String cudType, String ids, Map<String, Object> dsMap, HttpServletRequest request, JackJSONArray newSaveData, JackJSONArray oldSaveData) {
        User user=userService.getUser(request);
        Map<String, Object> map=new HashMap<>();
        BaseDao.setDefaultValue(map,user);
        map.put("ds_code",dsMap.get("ds_code"));
        map.put("ds_table_name",dsMap.get("ds_table_name"));
        map.put("type",cudType);
        map.put("data",ids);
        if(cudType.equals("create")&&newSaveData.size()==1){
            map.put("new_data",newSaveData.getJackJSONObject(0).toString());
        }
        if(cudType.equals("update")&&newSaveData.size()==1){
            map.put("new_data",newSaveData.getJackJSONObject(0).toString());
            map.put("old_data",oldSaveData.getJackJSONObject(0).toString());
        }
        if(cudType.equals("delete")&&oldSaveData.size()==1){
            map.put("old_data",oldSaveData.getJackJSONObject(0).toString());
        }
        if(DBCheck.isMongoDB()){
            mongoService.save(TblLogNames.TBL_LOG_CUD,map);
        }else{
            baseService.save(TblLogNames.TBL_LOG_CUD,map);
        }
    }

    public void fileLogSave(Map<String, Object> data, HttpServletRequest request) {
        Map<String,Object> fileInfo= (Map<String, Object>) data.get("fileInfo");
        User user=userService.getUser(request);
        Map<String, Object> map=new HashMap<>();
        BaseDao.setDefaultValue(map,user);
        map.put("upload_file_to_type",fileInfo.get("source"));
        map.put("real_file_name",fileInfo.get("realFileName"));
        map.put("suffix",fileInfo.get("suffix"));
        map.put("disk_file_name",fileInfo.get("diskFileName"));
        map.put("file_size",fileInfo.get("fileSize"));
        map.put("file_show_size",fileInfo.get("fileShowSize"));
        List<Map<String,Object>> fileList=new ArrayList<>();
        fileList.add(fileInfo);
        map.put("file", JackJSON.toJSONString(fileList));
        if(DBCheck.isMongoDB()){
            mongoService.save(TblLogNames.TBL_LOG_FILE,map);
        }else{
            baseService.save(TblLogNames.TBL_LOG_FILE,map);
        }
    }

    public void apiLogSave(String  jsonStr, HttpServletRequest request, KHCResponseEntity khcResponseEntity, long startTime) {
        JackJSONObject jsonObject=JackJSONObject.fromObject(jsonStr);
        String apiPath = request.getRequestURI().replace(request.getContextPath(), "");
        // 不需要存储日志的方法
        Set<String> validLogSaveMethodName = new HashSet<>(Arrays.asList("getSystemNotifyList", "getMenu","getSimpleCardInfo"));
        if(apiPath.equals("/api/data/myAction")&&validLogSaveMethodName.contains(String.valueOf(jsonObject.get("methodName")))){
            return;
        }
        User user=userService.getUser(request);
        Map<String, Object> map=new HashMap<>();
        if(apiPath.equals("/api/data/myAction")){
            map.put("api_log_method_name",jsonObject.get("methodName"));
        }else{
            // 获取最后一部分
            String methodName = apiPath.substring(apiPath.lastIndexOf("/") + 1);
            map.put("api_log_method_name",methodName);
        }
        BaseDao.setDefaultValue(map,user);
        map.put("api_action_code",jsonObject.get("dsCode"));
        map.put("api_action_name",jsonObject.get("dsCode"));
        map.put("api_log_url",apiPath);
        map.put("api_log_request_json",jsonStr);
        map.put("api_log_response_json", JackJSON.toJSONString(khcResponseEntity));
        map.put("api_log_response_status",khcResponseEntity.getStatus());
        map.put("api_log_response_uuid",khcResponseEntity.getUuid());//String method = request.getMethod();
        map.put("api_log_usage_time",System.currentTimeMillis() - startTime);
        String ip= IPUtil.getIpAddress(request);
        map.put("ip",ip);
        if(DBCheck.isMongoDB()){
            mongoService.save(TblLogNames.TBL_LOG_API,map);
        }else{
            baseService.save(TblLogNames.TBL_LOG_API,map);
        }
    }

}

