package com.huatek.busi.service.impl.log;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

import com.huatek.busi.common.annotation.OpChangeLogColumn;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Objects;
import com.huatek.busi.common.util.DateUtil;
import com.huatek.busi.common.util.FieldUtil;
import com.huatek.busi.dao.OpChangeLogEntityDao;
import com.huatek.busi.dto.OpChangeLogEntityDto;
import com.huatek.busi.entity.OpChangeLogEntity;
import com.huatek.busi.mapper.OpChangeLogEntityMapper;
import com.huatek.busi.service.log.OpChangeLogService;
import com.huatek.busi.vo.OpChangeLogEntityVo;
import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.sql.beans.Pojo;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;

import lombok.extern.slf4j.Slf4j;

/**
 * 记录变更操作日志ServiceImpl
 * 
 * @author anker_cheng
 * @date 2019/07/11
 */
@Slf4j
@Component
@Service(interfaceClass = OpChangeLogService.class)
public class OpChangeLogServiceImpl implements OpChangeLogService {

    @Autowired
    private OpChangeLogEntityDao opChangeLogEntityDao;
    @Autowired
    private OpChangeLogEntityMapper opChangeLogEntityMapper;

    @Override
    public PageInfo<OpChangeLogEntityVo> findOpChangeLogPage(OpChangeLogEntityDto opChangeLogEntityDto) {
        return PageHelper.startPage(opChangeLogEntityDto.getPage(), opChangeLogEntityDto.getLimit())
            .doSelectPageInfo(() -> opChangeLogEntityMapper.findOpChangeLogPage(opChangeLogEntityDto));
    }

    @Override
    public <T extends Pojo> void saveOpLog(String token, T mainEntity) {
        saveOpLog(token, mainEntity, null);
    }

    @Override
    public <T extends Pojo> void saveOpLog(String token, T newEntity, T oldEntity) {
        OpChangeLogEntity opChangeLogEntity = new OpChangeLogEntity();
        opChangeLogEntity.setId(Uuid.getUUID());
        opChangeLogEntity.setEntityClass(newEntity.getClass().getSimpleName());
        opChangeLogEntity.setOpType("UPDATE");
        if (oldEntity == null) {
            opChangeLogEntity.setOpType("ADD");
        }
        opChangeLogEntity.setObjectId((String)FieldUtil.getFieldValue(newEntity, "id"));
        opChangeLogEntity.setCreatedTime(LocalDateTime.now());
        opChangeLogEntity.setOpContent(getOpContent(newEntity, oldEntity));

        LocalUser user = UserUtil.getLocalUser(token);
        if (user != null) {
            opChangeLogEntity.setCreator(user.getUid());
        }

        opChangeLogEntityDao.add(opChangeLogEntity);
    }

    private final String PATTERN_ADD_MSG = "{} : {}";
    private final String PATTERN_UPDATE_MSG = "{} : {} -> {}";

    private String getOpContent(Object newEntity, Object oldEntity) {
        List<Field> logFieldList =
            FieldUtils.getFieldsListWithAnnotation(newEntity.getClass(), OpChangeLogColumn.class);
        if (CollectionUtils.isEmpty(logFieldList)) {
            log.debug("log field list is empty!");
            return null;
        }
        StringBuilder opContent = new StringBuilder();
        for (Field field : logFieldList) {
            OpChangeLogColumn ann = field.getAnnotation(OpChangeLogColumn.class);
            String newLogVal = getLogVal(newEntity, field, ann);
            if (oldEntity == null) {
                if (!StringUtils.isEmpty(newLogVal)) {
                    append(opContent, format(PATTERN_ADD_MSG, ann.recordName(), newLogVal));
                }
            } else {
                String oldLogVal = getLogVal(oldEntity, field, ann);
                if (!Objects.equal(newLogVal, oldLogVal)) {
                    append(opContent, format(PATTERN_UPDATE_MSG, ann.recordName(), oldLogVal, newLogVal));
                }
            }
        }
        return opContent.toString();
    }

    private static void append(StringBuilder opContent, String msg) {
        if (opContent.length() > 0) {
            opContent.append("; ");
        }
        opContent.append(msg);
    }

    private static String getLogVal(Object target, Field field, OpChangeLogColumn ann) {
        Object fieldValue = FieldUtil.getFieldValue(target, field);
        if (fieldValue == null) {
            return "";
        }
        if (Date.class.equals(field.getType())) {
            return format((Date)fieldValue, ann.format());
        }
        if (LocalDate.class.equals(field.getType())) {
            return format((LocalDate)fieldValue, ann.format());
        }
        if (LocalDateTime.class.equals(field.getType())) {
            return format((LocalDateTime)fieldValue, ann.format());
        }
        if (BigDecimal.class.equals(field.getType())) {
            return ((BigDecimal)fieldValue).toPlainString();
        }
        return fieldValue.toString();
    }

    private static String format(Date date, String pattern) {
        if (StringUtils.isEmpty(pattern)) {
            return DateFormatUtils.format(date, DateUtil.PATTERN_DATE_TIME);
        }
        return DateFormatUtils.format(date, pattern);
    }

    private static String format(LocalDate date, String pattern) {
        if (StringUtils.isEmpty(pattern)) {
            return date.format(DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE));
        }
        return date.format(DateTimeFormatter.ofPattern(pattern));
    }

    private static String format(LocalDateTime date, String pattern) {
        if (StringUtils.isEmpty(pattern)) {
            return date.format(DateTimeFormatter.ofPattern(DateUtil.PATTERN_DATE_TIME));
        }
        return date.format(DateTimeFormatter.ofPattern(pattern));
    }

    private static String format(String format, Object... argArray) {
        FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray);
        return ft.getMessage();
    }
}
