package com.ruoyi.ss.businessRecord.service;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.ss.businessRecord.domain.SmBusinessRecord;
import com.ruoyi.ss.businessRecord.domain.SmBusinessRecordQuery;
import com.ruoyi.ss.businessRecord.domain.SmBusinessRecordVo;
import com.ruoyi.ss.businessRecord.mapper.SmBusinessRecordMapper;
import com.ruoyi.dashboard.domain.vo.BillCountVo;
import com.ruoyi.dashboard.domain.vo.BriefVo;
import com.ruoyi.ss.device.domain.DeviceQuery;
import com.ruoyi.ss.device.domain.enums.DeviceOnlineStatus;
import com.ruoyi.ss.device.service.DeviceService;
import com.ruoyi.ss.receiveBill.domain.ReceiveBillQuery;
import com.ruoyi.ss.receiveBill.domain.enums.ReceiveBillType;
import com.ruoyi.ss.receiveBill.service.ReceiveBillService;
import com.ruoyi.ss.transactionBill.domain.TransactionBillQuery;
import com.ruoyi.ss.transactionBill.domain.enums.TransactionBillStatus;
import com.ruoyi.ss.transactionBill.domain.enums.TransactionBillType;
import com.ruoyi.ss.transactionBill.service.TransactionBillService;
import com.ruoyi.ss.user.domain.SmUserQuery;
import com.ruoyi.ss.user.service.ISmUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 经营记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-19
 */
@Service
public class SmBusinessRecordServiceImpl implements ISmBusinessRecordService
{
    @Autowired
    private SmBusinessRecordMapper smBusinessRecordMapper;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ISmUserService userService;

    @Autowired
    private ReceiveBillService receiveBillService;

    @Autowired
    private TransactionBillService transactionBillService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询经营记录
     *
     * @param id 经营记录主键
     * @return 经营记录
     */
    @Override
    public SmBusinessRecordVo selectSmBusinessRecordById(Long id)
    {
        return smBusinessRecordMapper.selectSmBusinessRecordById(id);
    }

    /**
     * 查询经营记录列表
     *
     * @param smBusinessRecord 经营记录
     * @return 经营记录
     */
    @Override
    public List<SmBusinessRecordVo> selectSmBusinessRecordList(SmBusinessRecordQuery smBusinessRecord)
    {
        return smBusinessRecordMapper.selectSmBusinessRecordList(smBusinessRecord);
    }

    /**
     * 新增经营记录
     *
     * @param smBusinessRecord 经营记录
     * @return 结果
     */
    @Override
    public int insertSmBusinessRecord(SmBusinessRecord smBusinessRecord)
    {
        smBusinessRecord.setCreateTime(DateUtils.getNowDate());
        return smBusinessRecordMapper.insertSmBusinessRecord(smBusinessRecord);
    }

    /**
     * 修改经营记录
     *
     * @param smBusinessRecord 经营记录d
     * @return 结果
     */
    @Override
    public int updateSmBusinessRecord(SmBusinessRecord smBusinessRecord)
    {
        return smBusinessRecordMapper.updateSmBusinessRecord(smBusinessRecord);
    }

    /**
     * 批量删除经营记录
     *
     * @param ids 需要删除的经营记录主键
     * @return 结果
     */
    @Override
    public int deleteSmBusinessRecordByIds(Long[] ids)
    {
        return smBusinessRecordMapper.deleteSmBusinessRecordByIds(ids);
    }

    /**
     * 删除经营记录信息
     *
     * @param id 经营记录主键
     * @return 结果
     */
    @Override
    public int deleteSmBusinessRecordById(Long id)
    {
        return smBusinessRecordMapper.deleteSmBusinessRecordById(id);
    }

    @Override
    public SmBusinessRecordVo selectLatestByDate(Date date) {
        SmBusinessRecordQuery dto = new SmBusinessRecordQuery();
        dto.setCreateDate(date);
        return smBusinessRecordMapper.selectLatest(dto);
    }

    @Override
    public List<SmBusinessRecordVo> selectDailyLatest(Date startDate, Date endDate) {
        SmBusinessRecordQuery dto = new SmBusinessRecordQuery();
        dto.setStartDate(startDate);
        dto.setEndDate(endDate);
        return smBusinessRecordMapper.selectDailyLatest(dto);
    }

    /**
     * 查询实时数据
     */
    @Override
    public BriefVo selectBrief() {
        BriefVo brief = redisCache.getCacheObject(CacheConstants.BRIEF);
        if (brief == null ) {
            brief = new BriefVo();
            Date now = DateUtils.getNowDate();

            // 总订单数
            TransactionBillQuery rechargeQuery = new TransactionBillQuery();
            rechargeQuery.setType(TransactionBillType.RECHARGE.getType());
            brief.setRechargeCount(transactionBillService.selectSimpleCount(rechargeQuery));

            // 今日订单数
            TransactionBillQuery todayQuery = new TransactionBillQuery();
            todayQuery.setType(TransactionBillType.RECHARGE.getType());
            todayQuery.setCreateDate(now);
            brief.setTodayRechargeCount(transactionBillService.selectSimpleCount(todayQuery));

            // 用户设备总数
            DeviceQuery deviceDto = new DeviceQuery();
            deviceDto.setDeleted(false);
            deviceDto.setIsBind(true);
            brief.setDeviceCount(deviceService.selectCount(deviceDto));
            // 用户在线设备总数
            deviceDto.setOnlineStatus(DeviceOnlineStatus.ONLINE.getStatus());
            brief.setOnlineCount(deviceService.selectCount(deviceDto));

            // 总设备数量
            DeviceQuery totalDeviceQuery = new DeviceQuery();
            brief.setTotalDeviceCount(deviceService.selectCount(totalDeviceQuery));
            // 总设备在线数量
            totalDeviceQuery.setOnlineStatus(DeviceOnlineStatus.ONLINE.getStatus());
            brief.setTotalOnlineCount(deviceService.selectCount(totalDeviceQuery));

            // 商户总数
            SmUserQuery userDto = new SmUserQuery();
            userDto.setType(UserType.MCH.getType());
            brief.setUserCount(userService.selectCount(userDto));

            // 普通用户总数
            SmUserQuery tenantDto = new SmUserQuery();
            userDto.setType(UserType.USER.getType());
            brief.setTenantCount(userService.selectCount(tenantDto));

            // 代理商总数
            SmUserQuery agentQuery = new SmUserQuery();
            agentQuery.setType(UserType.AGENT.getType());
            brief.setAgentCount(userService.selectCount(agentQuery));

            // 充值金额总数
            TransactionBillQuery billQuery = new TransactionBillQuery();
            billQuery.setStatusList(TransactionBillStatus.payedOrder());
            billQuery.setType(TransactionBillType.RECHARGE.getType());
            BigDecimal rechargeAmount = transactionBillService.selectSumOfMoneyWithoutRefund(billQuery);
            if (rechargeAmount == null) {
                rechargeAmount = BigDecimal.ZERO;
            }
            brief.setRechargeAmount(rechargeAmount);

            // 今日充值金额总数
            billQuery.setCreateDate(now);
            BigDecimal todayRechargeAmount = transactionBillService.selectSumOfMoneyWithoutRefund(billQuery);
            if (todayRechargeAmount == null) {
                todayRechargeAmount = BigDecimal.ZERO;
            }
            brief.setTodayRechargeAmount(todayRechargeAmount);

            // 用户总余额
            brief.setTotalUserBalance(userService.selectSumOfBalance(new SmUserQuery()));

            // 总月费
            ReceiveBillQuery monthQuery = new ReceiveBillQuery();
            monthQuery.setType(ReceiveBillType.MONTH.getType());
            brief.setTotalMonthAmount(receiveBillService.selectSumOfAmount(monthQuery));

            // 今日月费
            monthQuery.setBillDate(LocalDate.now());
            BigDecimal todayMonthAmount = receiveBillService.selectSumOfAmount(monthQuery);
            brief.setTodayMonthAmount(todayMonthAmount == null ? BigDecimal.ZERO : todayMonthAmount);

            redisCache.setCacheObject(CacheConstants.BRIEF, brief, 30, TimeUnit.MINUTES);
        }

        return brief;
    }

    /**
     * 记录数据
     */
    @Override
    public void record() {
        BriefVo brief = this.selectBrief();
        SmBusinessRecord data = new SmBusinessRecord();
        data.setTotalDevice(brief.getDeviceCount());
        data.setTotalOnline(brief.getOnlineCount());
        data.setTotalUser(brief.getUserCount() + brief.getTenantCount());
        data.setTotalRecharge(brief.getRechargeAmount());
        data.setRechargeCount(brief.getRechargeCount());
        data.setTotalMonth(brief.getTotalMonthAmount());
        data.setUserBalance(brief.getTotalUserBalance());
        data.setTodayRechargeAmount(brief.getTodayRechargeAmount());
        data.setTodayRechargeCount(brief.getTodayRechargeCount());
        data.setDeviceCount(brief.getTotalDeviceCount());
        this.insertSmBusinessRecord(data);
    }
}
