package com.bizzan.bitrade.dao;

import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

public class ExperienceGiftWithdrawDaoImpl implements ExperienceGiftWithdrawDaoCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Page<Map> pageQuery(Long memberId, Integer status,
                               String applyStartTime, String applyEndTime,
                               String reviewStartTime, String reviewEndTime,
                               int pageNo, int pageSize) {
        StringBuilder where = new StringBuilder(" WHERE 1=1");
        if (memberId != null) {
            where.append(" AND w.member_id = ").append(memberId);
        }
        if (status != null) {
            where.append(" AND w.status = ").append(status);
        }
        if (StringUtils.isNotBlank(applyStartTime)) {
            where.append(" AND w.apply_at >= '").append(applyStartTime).append(" 00:00:00'");
        }
        if (StringUtils.isNotBlank(applyEndTime)) {
            where.append(" AND w.apply_at <= '").append(applyEndTime).append(" 23:59:59'");
        }
        if (StringUtils.isNotBlank(reviewStartTime)) {
            where.append(" AND w.reviewed_at >= '").append(reviewStartTime).append(" 00:00:00'");
        }
        if (StringUtils.isNotBlank(reviewEndTime)) {
            where.append(" AND w.reviewed_at <= '").append(reviewEndTime).append(" 23:59:59'");
        }

        String countSql = "SELECT COUNT(1) FROM experience_gift_withdraw w" + where;
        String dataSql  = "SELECT w.id, w.member_id memberId, m.username," +
                " w.amount, w.status," +
                " w.apply_at applyAt, w.reviewed_at reviewedAt," +
                " w.reviewed_by reviewedBy, w.review_remark reviewRemark, w.settled_at settledAt" +
                " FROM experience_gift_withdraw w" +
                " LEFT JOIN member m ON m.id = w.member_id" +
                where +
                " ORDER BY w.apply_at DESC" +
                " LIMIT " + (pageSize * (pageNo - 1)) + ", " + pageSize;

        long total = ((BigInteger) entityManager.createNativeQuery(countSql).getSingleResult()).longValue();

        Query dataQuery = entityManager.createNativeQuery(dataSql);
        dataQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> list = dataQuery.getResultList();

        Pageable pageable = new PageRequest(pageNo - 1, pageSize);
        return new PageImpl<>(list, pageable, total);
    }
}
