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 ExperienceGiftProductDaoImpl implements ExperienceGiftProductDaoCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Page<Map> pageQuery(String name, Integer status, Integer grantType, int pageNo, int pageSize) {
        StringBuilder where = new StringBuilder(" WHERE 1=1");
        if (StringUtils.isNotBlank(name)) {
            where.append(" AND p.name LIKE '%").append(name.replace("'", "''")).append("%'");
        }
        if (status != null) {
            where.append(" AND p.status = ").append(status);
        }
        if (grantType != null) {
            where.append(" AND p.grant_type = ").append(grantType);
        }

        String countSql = "SELECT COUNT(1) FROM experience_gift_product p" + where;
        String dataSql  = "SELECT p.id, p.name, p.amount, p.validity_days validityDays," +
                " p.total_quantity totalQuantity, p.per_user_limit perUserLimit," +
                " p.max_profit_per_card maxProfitPerCard," +
                " p.grant_type grantType, p.trigger_type triggerType," +
                " p.issued_count issuedCount, p.status," +
                " p.created_at createdAt, p.updated_at updatedAt," +
                " MIN(pc.leverage) leverage," +
                " GROUP_CONCAT(pc.coin_symbol ORDER BY pc.coin_symbol SEPARATOR ',') coins" +
                " FROM experience_gift_product p" +
                " LEFT JOIN experience_gift_product_coin pc ON pc.product_id = p.id" +
                where +
                " GROUP BY p.id" +
                " ORDER BY p.created_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);
    }
}
