/**
* 文件：OperLogServiceImpl.java
* 版本：1.0.0
* 日期：
* Copyright &reg; 
* All right reserved.
*/

package com.mortals.xhx.base.system.oper.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.model.BaseEntity;
import com.mortals.framework.service.IUser;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseController;
import com.mortals.xhx.base.system.oper.dao.OperLogDao;
import com.mortals.xhx.base.system.oper.model.OperLogEntity;
import com.mortals.xhx.base.system.oper.service.OperLogService;
import com.mortals.xhx.common.code.OperTypeEnum;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: 操作日志</p>
 * <p>Description: OperLogServiceImpl service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 * @author 
 * @version 1.0.0
 */
@Service("operLogService")
public class OperLogServiceImpl extends AbstractCRUDServiceImpl<OperLogDao,OperLogEntity,Long> implements OperLogService {

    @Override
    public void saveCreateOperLog(HttpServletRequest request, IUser user, String result) {
        JSONObject jsonObject = JSONObject.parseObject(result);
        Map<String, Object> model = jsonObject.get(BaseController.KEY_RESULT_DATA) == null ? new HashMap<>() : (Map<String, Object>) jsonObject.get(BaseController.KEY_RESULT_DATA);
        this.insertOperLog(request, user, null, null, OperTypeEnum.SAVE, jsonObject.get(BaseController.KEY_RESULT_MSG).toString(), model.get("id") == null ? "" : model.get("id").toString());
    }

    @Override
    public void saveUpdateOperLog(HttpServletRequest request, IUser user, BaseEntity oldEntity, BaseEntity newEntity) {
        this.insertOperLog(request, user, oldEntity, newEntity, OperTypeEnum.UPDATE, null, null);
    }

    @Override
    public void saveDeleteOperLog(HttpServletRequest request, IUser user, String result, String id) {
        JSONObject jsonObject = JSONObject.parseObject(result);
        Map<String, Object> model = (Map<String, Object>) jsonObject.get(BaseController.KEY_RESULT_DATA);
        this.insertOperLog(request, user, null, null, OperTypeEnum.DELETE, jsonObject.get(BaseController.KEY_RESULT_MSG).toString(), id);
    }

    @Override
    public void saveOperLog(HttpServletRequest request, IUser user, String content, String id) {
        this.insertOperLog(request, user, null, null, OperTypeEnum.OTHER, content, id);
    }

    @Override
    public void insertOperLog(HttpServletRequest request, IUser user, BaseEntity oldEntity, BaseEntity newEntity, OperTypeEnum operType, String content, String id) {
        OperLogEntity operLogEntity = new OperLogEntity();
        operLogEntity.setIp(HttpUtil.getRequestIP(request));
        operLogEntity.setLogDate(new Date());

        operLogEntity.setPlatformMark(GlobalSysInfo.getPropertyValue(SysConstains.PROP_PLATFORM_MARK));
        operLogEntity.setOperType(operType.getValue());
        operLogEntity.setRequestUrl(request.getRequestURI());
        if (user != null) {
            operLogEntity.setLoginName(user.getLoginName());
            operLogEntity.setUserId(user.getId());
            operLogEntity.setUserName(user.getRealName());
        }

        switch (operType) {
            case SAVE:
                formatterLogContent(operLogEntity, content, id, operType);
                break;
            case UPDATE:
                formatterLogContent(operLogEntity, oldEntity, newEntity);
                break;
            case DELETE:
                formatterLogContent(operLogEntity, content, id, operType);
                break;
            default:
                operLogEntity.setOperType(OperTypeEnum.UPDATE.getValue());
                operLogEntity.setContent(StringUtils.isBlank(id) ? content : content + "id:" + id);
                break;
        }

        super.save(operLogEntity, null);
    }

    @Override
    public void insertOperLog(String ip,String requestUrl,Long userId, String userName, String loginName,String content){
        OperLogEntity operLogEntity = new OperLogEntity();
        operLogEntity.setIp(ip);
        operLogEntity.setLogDate(new Date());
        operLogEntity.setPlatformMark(GlobalSysInfo.getPropertyValue(SysConstains.PROP_PLATFORM_MARK)==null?"unknow":GlobalSysInfo.getPropertyValue(SysConstains.PROP_PLATFORM_MARK));
        operLogEntity.setRequestUrl(requestUrl);
        operLogEntity.setLoginName(loginName);
        operLogEntity.setUserId(userId);
        operLogEntity.setUserName(userName);
        operLogEntity.setContent(content);
        save(operLogEntity, null);
    }
    private void formatterLogContent(OperLogEntity operLogEntity, String content, String id, OperTypeEnum operType) {
        if (operType == OperTypeEnum.SAVE) {
            content = operLogEntity.getUserName() + "在" + content + "中新增一条数据" ;
        } else if (operType == OperTypeEnum.DELETE) {
            content = operLogEntity.getUserName() + "在" + content + "，id为:" + id;
        }
        content += StringUtils.isBlank("id") ? "":"，id为:" + id;
        operLogEntity.setContent(content);

    }

    private void formatterLogContent(OperLogEntity operLogEntity, BaseEntity oldEntity, BaseEntity newEntity) {
        if (oldEntity == null || newEntity == null) {
            return;
        }

        StringBuilder content = new StringBuilder();
        Class clazz = oldEntity.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object oldValue = field.get(oldEntity);
                Object newValue = field.get(newEntity);
                if (String.valueOf(oldValue).equals(String.valueOf(newValue))) {
                    continue;
                }
                content.append(field.getName() + "由:" + oldValue + "变更为:" + newValue + ";");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        if (content.length() == 0) {
            content.append("无内容变更");
        }
        operLogEntity.setContent(content.toString());
    }
	
}