package com.gitee.sop.admin.common.support;

import com.gitee.fastmybatis.core.mapper.BaseMapper;
import com.gitee.fastmybatis.core.query.LambdaQuery;
import com.gitee.fastmybatis.core.support.Getter;
import com.gitee.fastmybatis.core.support.LambdaService;
import com.gitee.sop.admin.common.context.UserContext;
import com.gitee.sop.admin.common.enums.IEnum;
import com.gitee.sop.admin.common.util.DateUtil;

import java.time.LocalDateTime;

/**
 * @param <E>      实体类
 * @param <Mapper> Mapper
 * @author 六如
 */
public interface ServiceSupport<E, Mapper extends BaseMapper<E>> extends LambdaService<E, Mapper> {

    @Override
    default LambdaQuery<E> query() {
        return new MyLambdaQuery<>(this.getEntityClass());
    }

    class MyLambdaQuery<E> extends LambdaQuery<E> {
        private static final long serialVersionUID = 5232128649485429495L;

        private static final String UPDATE_BY_FORMAT = "update_by = %s";
        private static final String UPDATE_TIME_FORMAT = "update_time = '%s'";

        public MyLambdaQuery(Class<E> entityClass) {
            super(entityClass);
        }

        @Override
        public LambdaQuery<E> eq(Getter<E, ?> getter, Object value) {
            if (value instanceof IEnum<?>) {
                return super.eq(getter, ((IEnum<?>) value).getValue());
            }
            return super.eq(getter, value);
        }

        @Override
        public LambdaQuery<E> notEq(Getter<E, ?> getter, Object value) {
            if (value instanceof IEnum<?>) {
                return super.notEq(getter, ((IEnum<?>) value).getValue());
            }
            return super.notEq(getter, value);
        }

        @Override
        public int update() {
            this.appendUpdate();
            return super.update();
        }

        @Override
        public int delete() {
            this.appendUpdate();
            return super.delete();
        }

        private void appendUpdate() {
            Long userId = UserContext.getUserId();
            if (userId != null) {
                this.setExpression(String.format(UPDATE_BY_FORMAT, userId));
            }
            this.setExpression(String.format(UPDATE_TIME_FORMAT, DateUtil.formatYmdhms(LocalDateTime.now())));
        }

    }
}
