package com.zanxiang.game.data.serve.service.impl;

import com.github.sd4324530.jtuple.Tuple2;
import com.google.common.base.CaseFormat;
import com.zanxiang.game.data.serve.component.DataPowerComponent;
import com.zanxiang.game.data.serve.pojo.dto.AdsAgentRechargeRankingListDTO;
import com.zanxiang.game.data.serve.pojo.vo.AdsAgentRechargeRankingVO;
import com.zanxiang.game.data.serve.service.IAdsAgentRechargeRankingService;
import com.zanxiang.game.data.serve.utils.Page;
import com.zanxiang.module.util.NumberUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.Daos;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.List;

@Slf4j
@Service
public class AdsAgentRechargeRankingServiceImpl implements IAdsAgentRechargeRankingService {

    @Autowired
    private Dao dao;
    @Autowired
    private DataPowerComponent dataPowerComponent;

    public Page<AdsAgentRechargeRankingVO> listOfPage(AdsAgentRechargeRankingListDTO dto) {
        Tuple2<List<Long>, List<Long>> poerInfo = dataPowerComponent.getPowerInfo();
        List<Long> userIds = dto.getPitcherId() == null ? poerInfo.first : Collections.singletonList(dto.getPitcherId());
        if (StringUtils.isBlank(dto.getSortFiled())) {
            dto.setSortFiled("today_amount");
        }
        if (StringUtils.isBlank(dto.getSortType())) {
            dto.setSortType("desc");
        }
        Pager pager = dto.toPage();
        String sqlStr = """
                select agent_id, max(agent_name) as agent_name, pitcher_id, max(pitcher) as pitcher, `type`,
                sum(today_amount) as today_amount,
                max(total_recharge_amount) as total_recharge_amount,
                max(total_recharge_num) as total_recharge_num,
                max(total_recharge_count) as total_recharge_count,
                max(total_cost) as total_cost,
                max(total_recharge_amount) / max(total_recharge_count) as avg_amount,
                if (max(total_cost) > 0, max(total_recharge_amount) / max(total_cost), '0') as roi
                from ads_agent_recharge_ranking
                """;
        Criteria cri = Cnd.cri();
        if (null != dto.getBeginDay() && null != dto.getEndDay()) {
            cri.where().and("dt", ">=", dto.getBeginDay()).and("dt", "<=", dto.getEndDay());
        }
        if (CollectionUtils.isNotEmpty(dto.getAgentId())) {
            cri.where().andIn("agent_id", dto.getAgentId().toArray(String[]::new));
        }
        if (userIds != null) {
            cri.where().andInList("pitcher_id", userIds);
        }
        if (StringUtils.isNotBlank(dto.getType())) {
            cri.where().and("type", "=", dto.getType());
        }
        if (StringUtils.isNotBlank(dto.getSourceSystem())) {
            cri.where().and("source_system", "=", dto.getSourceSystem());
        }
        cri.getGroupBy().groupBy("agent_id", "pitcher_id", "type");
        cri.getOrderBy().orderBy(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, dto.getSortFiled()), dto.getSortType());
        Sql sql = Sqls.queryEntity(sqlStr + "$condition");

        Entity<AdsAgentRechargeRankingVO> entity = dao.getEntity(AdsAgentRechargeRankingVO.class);
        sql.setEntity(entity).setCondition(cri);
        // 查询分页总数据
        pager.setRecordCount(((Long) Daos.queryCount(dao, sql)).intValue());
        // 分页查询数据
        sql.setPager(pager);
        dao.execute(sql);

        List<AdsAgentRechargeRankingVO> result = sql.getList(AdsAgentRechargeRankingVO.class);
        if (CollectionUtils.isNotEmpty(result)) {
            result.forEach(vo -> {
                if (vo.getAvgAmount() != null) {
                    vo.setAvgAmount(vo.getAvgAmount().setScale(2, RoundingMode.HALF_UP));
                } else {
                    vo.setAvgAmount(BigDecimal.ZERO);
                }
                if (vo.getRoi() != null) {
                    vo.setRoi(NumberUtil.multiply100(vo.getRoi()).setScale(2, RoundingMode.HALF_UP));
                } else {
                    vo.setRoi(BigDecimal.ZERO);
                }
            });
            int beginIndex = (dto.getPageNum() - 1) * dto.getPageSize();
            int size = result.size();
            while (--size >= 0) {
                result.get(size).setIndex(beginIndex + size);
            }
        }
        return new Page<>(result, pager);
    }
}
