package com.jeequan.jeepay.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.config.dynamic.DataSourceSwitch;
import com.jeequan.jeepay.db.config.dynamic.DynamicDataSource;
import com.jeequan.jeepay.db.entity.StatsTransferEntity;
import com.jeequan.jeepay.service.mapper.StatsTransferMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 代付转账交易数据统计表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2024-05-22
 */
@Service
public class StatsTransferService extends ServiceImpl<StatsTransferMapper, StatsTransferEntity> {

    @Autowired
    private TransferInterfaceDefineService interfaceDefineService;

    /**
     * 统计数据入库
     */
    @Transactional(rollbackFor = Exception.class)
    public void handleStats(Date beginDate, Date endDate) {
        handleStats(beginDate, endDate, null);
    }

    /**
     * 统计数据入库
     */
    public void handleStats(Date beginDate, Date endDate, String mchNo) {
        // 统计beginDate数据
        Page<StatsTransferEntity> page = new Page<>(1, 2000);

        // 入库前清空数据，防止重复，  统计条件和删除条件一致
        delStats(beginDate, mchNo);

        do {
            List<StatsTransferEntity> statsTrades = getStatsData(beginDate, endDate, mchNo, page);
            if (CollUtil.isEmpty(statsTrades)) {
                return;
            }

            boolean result = this.saveBatch(statsTrades);
            if (!result) {
                throw new BizException(ApiCodeEnum.SYS_OPERATION_FAIL_CREATE);
            }
        } while (page.getRecords().size() >= page.getSize());

    }


    @DataSourceSwitch(DynamicDataSource.DataSourceTypeEnum.SLAVE)
    private List<StatsTransferEntity> getStatsData(Date beginDate, Date endDate, String mchNo, Page<StatsTransferEntity> page) {
        Map<String, Object> params = new HashMap<>();
        params.put("beginDate", beginDate);
        params.put("endDate", endDate);

        if (StringUtils.isNotBlank(mchNo)) {
            params.put("mchNo", mchNo);
        }

        // 查询数据集合
        Page<StatsTransferEntity> pageResult = baseMapper.selectTransferStats(page, params, false);
        if (CollUtil.isEmpty(pageResult.getRecords())) {
            return null;
        }

        pageResult.getRecords().forEach(it -> {
            it.setState(CS.YES);
        });

        return pageResult.getRecords();
    }

    private void delStats(Date beginDate, String mchNo) {
        LambdaQueryWrapper<StatsTransferEntity> queryWrapper = Wrappers.<StatsTransferEntity>lambdaQuery()
                .eq(StatsTransferEntity::getStatsDate, DateUtil.formatDate(beginDate));
        queryWrapper.eq(StringUtils.isNotBlank(mchNo), StatsTransferEntity::getMchNo, mchNo);

        this.remove(queryWrapper);
    }

    /**
     * 实时统计，主要用于历史当前数据统计
     *
     * @param page
     * @param condition
     * @param date
     * @return
     */
    public Page<StatsTransferEntity> pageRealTimeStat(Page<StatsTransferEntity> page, StatsTransferEntity condition, Date date) {
        Map<String, Object> param = new HashMap<>();
        param.put("beginDate", DateUtil.beginOfDay(date));
        param.put("endDate", DateUtil.endOfDay(date));
        param.put("mchNo", condition.getMchNo());
        param.put("agentNo", condition.getAgentNo());
        param.put("isvNo", condition.getIsvNo());
        param.put("ifCode", condition.getIfCode());
        param.put("subjectId", condition.getSubjectId());
        return baseMapper.selectTransferStats(page, param, true);
    }

    /**
     * 实时统计，主要用于历史当前数据统计
     *
     * @param page
     * @param condition
     * @param dateRange 时间区间搜索
     * @return
     */
    public Page<StatsTransferEntity> pageHistoryStat(Page<StatsTransferEntity> page, StatsTransferEntity condition, Date[] dateRange) {
        Map<String, Object> param = new HashMap<>();
        param.put("beginDate", dateRange[0]);
        param.put("endDate", dateRange[1]);
        param.put("mchNo", condition.getMchNo());
        param.put("agentNo", condition.getAgentNo());
        param.put("isvNo", condition.getIsvNo());
        param.put("ifCode", condition.getIfCode());
        param.put("subjectId", condition.getSubjectId());
        return baseMapper.selectHistoryTransferStats(page, param, true);
    }
}
