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 ExperienceGiftRiskAlertDaoImpl implements ExperienceGiftRiskAlertDaoCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Page<Map> pageQuery(Long memberId, String startTime, String endTime,
                               Integer status, int pageNo, int pageSize) {
        StringBuilder where = new StringBuilder(" WHERE 1=1");
        if (memberId != null) {
            where.append(" AND a.member_id = ").append(memberId);
        }
        if (StringUtils.isNotBlank(startTime)) {
            where.append(" AND a.created_at >= '").append(startTime).append(" 00:00:00'");
        }
        if (StringUtils.isNotBlank(endTime)) {
            where.append(" AND a.created_at <= '").append(endTime).append(" 23:59:59'");
        }
        if (status != null) {
            where.append(" AND a.status = ").append(status);
        }

        String countSql = "SELECT COUNT(1) FROM experience_gift_risk_alert a" + where;
        String dataSql  = "SELECT a.id, a.member_id memberId, a.receipt_count receiptCount," +
                " a.profit_amount profitAmount, a.status," +
                " a.created_at createdAt, a.handled_at handledAt, a.handled_by handledBy" +
                " FROM experience_gift_risk_alert a" +
                where +
                " ORDER BY a.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);
    }

    @Override
    public List<Map> findRiskStats(String startStr) {
        String sql =
            "SELECT r.member_id AS memberId," +
            " COUNT(DISTINCT CASE WHEN r.created_at >= '" + startStr + "' THEN r.id END) AS receiptCount," +
            " COALESCE(SUM(CASE WHEN r.closed_at >= '" + startStr + "' AND r.status = 2 AND r.pnl > 0 THEN r.pnl ELSE 0 END), 0) AS profitAmount" +
            " FROM experience_gift_record r" +
            " WHERE r.created_at >= '" + startStr + "' OR (r.closed_at >= '" + startStr + "' AND r.status = 2)" +
            " GROUP BY r.member_id" +
            " HAVING COUNT(DISTINCT CASE WHEN r.created_at >= '" + startStr + "' THEN r.id END) >= 5" +
            "     OR SUM(CASE WHEN r.closed_at >= '" + startStr + "' AND r.status = 2 AND r.pnl > 0 THEN r.pnl ELSE 0 END) >= 100";

        Query query = entityManager.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }
}
