package shop.alien.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.StoreIncomeDetailsRecordVo;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.mapper.*;
import shop.alien.store.config.WebSocketProcess;
import shop.alien.store.service.StoreDictService;
import shop.alien.store.service.StoreIncomeDetailsRecordService;
import shop.alien.store.service.StoreUserService;
import shop.alien.store.util.ali.AliApi;
import shop.alien.util.common.DateUtils;
import shop.alien.util.common.ListToPage;
import shop.alien.util.common.constant.CouponTypeEnum;
import shop.alien.util.common.constant.OrderStatusEnum;
import shop.alien.util.type.LifeNoticeUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商户收入明细表 服务实现类
 *
 * @author ssk
 * @since 2025-02-25
 */
@Service
@RequiredArgsConstructor
public class StoreIncomeDetailsRecordServiceImpl extends ServiceImpl<StoreIncomeDetailsRecordMapper, StoreIncomeDetailsRecord> implements StoreIncomeDetailsRecordService {

    private final StoreUserMapper storeUserMapper;

    private final StoreCashOutRecordMapper storeCashOutRecordMapper;

    private final StoreDictService storeDictService;

    private final StoreUserService storeUserService;

    private final AliApi aliApi;

    private final StoreIncomeDetailsRecordMapper storeIncomeDetailsRecordMapper;
    private final LifeUserOrderMapper lifeUserOrderMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final WebSocketProcess webSocketProcess;
    private final StoreInfoMapper storeInfoMapper;

    /**
     * 提现-提现全部-手续费一单一算
     *
     * @param storeId         门店id
     * @param payPassword     支付密码
     * @param withdrawalMoney 提现金额
     * @return 是否成功
     */
    @Transactional
    @Override
    public R cashOut(Integer storeId, String payPassword, Integer withdrawalMoney) {
        StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, storeId).eq(StoreUser::getPayPassword, payPassword));
        /*if (storeUser != null) {
            //查询可用账单(大于创建时间3天)
            LambdaQueryWrapper<StoreIncomeDetailsRecord> wrapper = new LambdaQueryWrapper<>();
            //当前时间-3天大于创建时间
            wrapper.lt(StoreIncomeDetailsRecord::getCreatedTime, DateUtils.calcDays(new Date(), -3))
                    //未绑定提现记录的
                    .isNull(StoreIncomeDetailsRecord::getCashOutId);
            List<StoreIncomeDetailsRecord> list = this.list(wrapper);
            if (!list.isEmpty()) {
                //总金额
                Integer availableAmount = 0;
                //手续费
                Integer commission = 0;
                for (StoreIncomeDetailsRecord record : list) {
                    availableAmount += record.getMoney();
                    commission += record.getCommission();
                }
                int money = availableAmount - commission;
                //调用支付宝转账
                BigDecimal decimal = new BigDecimal(money);
                BigDecimal divide = decimal.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                if (Double.parseDouble(divide.toString()) < 0.10) {
                    return "金额不能小于0.1元";
                }
                StoreAliPayLog pay = aliApi.pay(storeUser.getName(), storeUser.getIdCard(), storeUser.getPhone(), divide.toString());
                if (null != pay) {
                    list = list.stream().sorted(Comparator.comparing(StoreIncomeDetailsRecord::getCreatedTime)).collect(Collectors.toList());
                    Date startDate = list.get(0).getCreatedTime();
                    Date endDate = list.get(list.size() - 1).getCreatedTime();
                    //增加提现记录
                    StoreCashOutRecord storeCashOutRecord = new StoreCashOutRecord();
                    storeCashOutRecord.setOrderNo(pay.getOutBizNo());
                    storeCashOutRecord.setStoreId(storeId);
                    storeCashOutRecord.setMoney(money);
                    storeCashOutRecord.setCommission(commission);
                    storeCashOutRecord.setCashOutType(0);
                    storeCashOutRecord.setAliOrderNo(pay.getOrderId());
                    storeCashOutRecord.setPaymentDate(new Date());
                    storeCashOutRecord.setPaymentStatus(1);
                    storeCashOutRecord.setDeleteFlag(0);
                    storeCashOutRecord.setIncomeStartTime(startDate);
                    storeCashOutRecord.setIncomeEndTime(endDate);
                    storeCashOutRecordMapper.insert(storeCashOutRecord);
                    //关联提现记录
                    list.forEach(record -> record.setCashOutId(storeCashOutRecord.getId()));
                    this.saveOrUpdateBatch(list);
                    //减少账户余额
                    storeUserMapper.updateById(new StoreUser(storeId, storeUser.getMoney() - availableAmount));
                    return "success";
                }
                return "支付宝转账失败";
            }
            return "账单未到可提现时间";
        }*/
        if (null != storeUser) {
            if (storeUser.getMoney() >= withdrawalMoney) {
                //调用支付宝转账
                BigDecimal decimal = new BigDecimal(withdrawalMoney);
                BigDecimal divide = decimal.divide(new BigDecimal(100), 2, RoundingMode.DOWN);
                if (Double.parseDouble(divide.toString()) < 0.1) {
                    return R.fail("金额不能小于0.1元");
                }
                StoreAliPayLog pay = aliApi.payAccount(storeUser.getName(), storeUser.getIdCard(), storeUser.getAlipayAccount(), divide.toString(), storeUser.getPhone());
                //增加提现记录
                StoreCashOutRecord storeCashOutRecord = new StoreCashOutRecord();
                if (null == pay) {
                    return R.fail("支付宝转账失败");
                }
                if (pay.getStoreAliPayErrorLog() == null) {
                    storeCashOutRecord.setStoreId(storeId);
                    storeCashOutRecord.setOrderNo(pay.getOutBizNo());
                    storeCashOutRecord.setMoney(withdrawalMoney);
                    // 手续费不是减过了吗
//                storeCashOutRecord.setCommission(commission);
                    storeCashOutRecord.setCashOutType(0);
                    storeCashOutRecord.setAliOrderNo(pay.getOrderId());
                    storeCashOutRecord.setPaymentDate(new Date());
                    storeCashOutRecord.setPaymentStatus(1);
                    storeCashOutRecord.setDeleteFlag(0);
                    storeCashOutRecord.setStoreUserId(storeUser.getId());
//                storeCashOutRecord.setIncomeStartTime(startDate);
//                storeCashOutRecord.setIncomeEndTime(endDate);
                    storeCashOutRecordMapper.insert(storeCashOutRecord);
                    //减少账户余额
                    storeUserMapper.updateById(new StoreUser(storeUser.getId(), storeUser.getMoney() - withdrawalMoney));
                    return R.data(storeCashOutRecord);
                } else {
                    // 提现失败
                    storeCashOutRecord.setStoreId(storeId);
                    storeCashOutRecord.setPaymentStatus(2);
                    storeCashOutRecord.setCashOutType(0);
                    storeCashOutRecord.setDeleteFlag(0);
                    storeCashOutRecord.setMoney(withdrawalMoney);
                    storeCashOutRecord.setFailReason("支付失败");
                    storeCashOutRecord.setPayDate(new Date());//支付时间
                    storeCashOutRecord.setStoreUserId(storeUser.getId());
                    storeCashOutRecordMapper.insert(storeCashOutRecord);
                    return R.fail(pay.getStoreAliPayErrorLog().getInformation());
                }
            }
            return R.fail("余额不足");
        }
        return R.fail("支付密码错误");
    }

    /**
     * 提现申请-提现全部-手续费一单一算
     *
     * @param storeId 门店id
     * @return 是否成功
     */
    @Transactional
    @Override
    public R applyCashOut(Integer storeId, String payPassword, Integer withdrawalMoney) {
        StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, storeId).eq(StoreUser::getPayPassword, payPassword));
        if (storeUser != null) {
            if (storeUser.getMoney() <= withdrawalMoney) {
                return R.fail("余额不足");
            }
            //调用支付宝转账
            BigDecimal decimal = new BigDecimal(withdrawalMoney);
            BigDecimal divide = decimal.divide(new BigDecimal(100), 2, RoundingMode.DOWN);
            if (Double.parseDouble(divide.toString()) < 0.1) {
                return R.fail("金额不能小于0.1元");
            }
            /*int freeze = 0;
            //查询冻结配置
            SystemConfigVo systemConfigVo = storeDictService.getConfig("freeze");
            if (systemConfigVo != null) {
                String freezeFlag = systemConfigVo.getConfigValue1();
                String freezeDay = systemConfigVo.getConfigValue2();
                if (StringUtils.isNotBlank(freezeFlag) && freezeFlag.equals("1") && StringUtils.isNotBlank(freezeDay)) {
                    freeze = Integer.parseInt(freezeDay);
                }
            }

            //查询可用账单
            LambdaQueryWrapper<StoreIncomeDetailsRecord> wrapper = new LambdaQueryWrapper<>();
            //当前时间-3天大于创建时间
            if (freeze > 0) {
                wrapper.lt(StoreIncomeDetailsRecord::getCreatedTime, DateUtils.calcDays(new Date(), -freeze));
            }*/
            //增加提现申请记录
            StoreCashOutRecord storeCashOutRecord = new StoreCashOutRecord();
            storeCashOutRecord.setStoreId(storeId);
            storeCashOutRecord.setMoney(withdrawalMoney);
//            storeCashOutRecord.setCommission(commission);
            storeCashOutRecord.setCashOutType(0);
            storeCashOutRecord.setPaymentStatus(3);
            storeCashOutRecord.setDeleteFlag(0);
            storeCashOutRecord.setIncomeStartTime(new Date());
            storeCashOutRecord.setIncomeEndTime(new Date());
            storeCashOutRecord.setStoreUserId(storeUser.getId());
            storeCashOutRecordMapper.insert(storeCashOutRecord);
            return R.data(storeCashOutRecord);
        }
        return R.fail("支付密码错误");
    }

    @Transactional
    @Override
    public String approveCashOut(Integer cashOutId, String approveStatus, String failReason) {
        if (cashOutId != null && cashOutId > 0 && StringUtils.isNotBlank(approveStatus)) {
            StoreCashOutRecord storeCashOutRecord = storeCashOutRecordMapper.selectById(cashOutId);
            if (!(storeCashOutRecord.getPaymentStatus() == 3)) {
                return "付款状态异常";
            }
            Integer storeUserId = storeCashOutRecord.getStoreUserId();
            StoreUser storeUser = storeUserMapper.selectById(storeUserId);

            if (approveStatus.equals("0")) {
                //同意提现通知
                cashOutSendNotice(storeCashOutRecord, storeUser, failReason, "1");

                //同意，开始提现
                int money = storeCashOutRecord.getMoney();
                if (money > storeUser.getMoney()) {
                    money = storeUser.getMoney();
                }
                BigDecimal decimal = new BigDecimal(money);
                BigDecimal divide = decimal.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
                if (Double.parseDouble(divide.toString()) < 0.10) {
                    return "金额不能小于0.1元";
                }
                StoreAliPayLog pay = aliApi.payAccount(storeUser.getName(), storeUser.getIdCard(), storeUser.getAlipayAccount(), divide.toString(), storeUser.getPhone());
                if (null != pay) {
                    // 提现成功，更新提现申请相关状态
                    storeCashOutRecord.setOrderNo(pay.getOutBizNo());
                    storeCashOutRecord.setAliOrderNo(pay.getOrderId());
                    storeCashOutRecord.setPaymentStatus(1);//提现成功
                    storeCashOutRecord.setApproveTime(new Date());// 审批时间
                    storeCashOutRecord.setPayDate(new Date());//支付时间
                    storeCashOutRecord.setPaymentDate(new Date());//支付到账时间
                    storeCashOutRecordMapper.updateById(storeCashOutRecord);
                    // 在存钱包的时候已经去掉了手续费
                    storeUserMapper.updateById(new StoreUser(storeUserId, storeUser.getMoney() - storeCashOutRecord.getMoney()));
                    // 提现成功通知
                    cashOutSendNotice(storeCashOutRecord, storeUser, failReason, "3");
                    return "付款成功";
                } else {
                    // 提现失败
                    storeCashOutRecord.setPaymentStatus(2);
                    storeCashOutRecord.setApproveTime(new Date());// 审批时间
                    storeCashOutRecord.setFailReason("支付宝回传异常情况");
                    storeCashOutRecord.setPayDate(new Date());//支付时间
                    storeCashOutRecordMapper.updateById(storeCashOutRecord);
                    // 提现失败通知
                    cashOutSendNotice(storeCashOutRecord, storeUser, failReason, "4");
                    return "付款失败";
                }
            } else {
                storeCashOutRecord.setPaymentStatus(4);
                storeCashOutRecord.setApproveFailReason(failReason);
                storeCashOutRecord.setApproveTime(new Date());// 审批时间
                storeCashOutRecordMapper.updateById(storeCashOutRecord);
                // 拒绝将账单中的提现记录置空
                LambdaUpdateWrapper<StoreIncomeDetailsRecord> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(StoreIncomeDetailsRecord::getStoreId, storeCashOutRecord.getStoreId())
                        .eq(StoreIncomeDetailsRecord::getCashOutId, storeCashOutRecord.getId())
                        .set(StoreIncomeDetailsRecord::getCashOutId, "");
                int result = storeIncomeDetailsRecordMapper.updateByCashOutId(storeCashOutRecord.getStoreId(), storeCashOutRecord.getId());

                //驳回提现申请通知
                cashOutSendNotice(storeCashOutRecord, storeUser, failReason, "2");
                return "已拒绝";
            }
        }
        return "审批成功";
    }

    private void cashOutSendNotice(StoreCashOutRecord storeCashOutRecord, StoreUser storeUser, String failReason, String noticeType) {

        //同意提现通知
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String commonDate = simpleDateFormat.format(storeCashOutRecord.getCreatedTime());
        String moneyStr = String.format("%.2f", storeCashOutRecord.getMoney() / 100.0);
        LifeNotice lifeMessage = new LifeNotice();
        lifeMessage.setReceiverId("store_" + storeUser.getPhone());
        com.alibaba.fastjson2.JSONObject jsonObject = new com.alibaba.fastjson2.JSONObject();
        String text = "";
        if (noticeType.equals("1")) {
            text = "您在" + commonDate + "申请提现" + moneyStr + "元，已审核成功，提现中，请耐心等待。";
            lifeMessage.setTitle("提现审核");
        } else if (noticeType.equals("2")) {
            text = "您在" + commonDate + "申请提现" + moneyStr + "元，审核失败。失败原因：" + failReason;
            lifeMessage.setTitle("提现审核");
        } else if (noticeType.equals("3")) {
            text = "您在" + commonDate + "申请提现" + moneyStr + "元，已成功到达您的支付宝账号，请注意查收。";
            lifeMessage.setTitle("提现到账");
        } else {
            text = "您在" + commonDate + "申请提现" + moneyStr + "元，到账失败，请重新申请或联系客服。";
            lifeMessage.setTitle("提现到账");
        }
        jsonObject.put("message", text);
        lifeMessage.setContext(jsonObject.toJSONString());
        lifeMessage.setSenderId("system");
        lifeMessage.setIsRead(0);
        lifeMessage.setNoticeType(1);
        lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
        lifeNoticeMapper.insert(lifeMessage);

        WebSocketVo websocketVo = new WebSocketVo();
        websocketVo.setSenderId("system");
        websocketVo.setReceiverId("store_" + storeUser.getPhone());
        websocketVo.setCategory("notice");
        websocketVo.setNoticeType("1");
        websocketVo.setIsRead(0);
        websocketVo.setText(com.alibaba.fastjson2.JSONObject.from(lifeMessage).toJSONString());
        try {
            webSocketProcess.sendMessage("store_" + storeUser.getPhone(), com.alibaba.fastjson2.JSONObject.from(websocketVo).toJSONString());
        } catch (Exception e) {
            log.error("StoreIncomeDetailsRecordsServiceImpl approveCashOut  Stack={}", e);
        }
    }


    /**
     * 今日收益
     *
     * @param storeId 门店id
     * @return 收益
     */
    @Override
    public String todayIncome(Integer storeId) {
        LambdaQueryWrapper<StoreIncomeDetailsRecord> wrapper = new LambdaQueryWrapper<>();
        LocalDate now = LocalDate.now();
        wrapper.eq(StoreIncomeDetailsRecord::getStoreId, storeId)
                .ge(StoreIncomeDetailsRecord::getCreatedTime, now + " 00:00:00")
                .le(StoreIncomeDetailsRecord::getCreatedTime, now + " 23:59:59");
        List<StoreIncomeDetailsRecord> list = this.list(wrapper);
        int income = 0;
        income += list.stream().mapToInt(StoreIncomeDetailsRecord::getMoney).sum();
        return new BigDecimal(income).divide(new BigDecimal(100), 2, RoundingMode.DOWN).toString();
    }

    /**
     * 账期
     *
     * @param storeId     门店id
     * @param incomeType  收入类型, 0:主页, 1:优惠券, 2:代金券, 3:套餐, 4:联名卡
     * @param paymentType 账期类型,0:未到,1:已到
     * @return 未到账期
     */
    @Override
    public JSONObject noYetPayment(Integer storeId, Integer incomeType, Integer paymentType, String startTime, String endTime, int page, int size) {
        QueryWrapper<StoreIncomeDetailsRecord> wrapper = new QueryWrapper<StoreIncomeDetailsRecord>();
        JSONObject jsonObject = new JSONObject();
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        if (paymentType == 0) {
            wrapper.isNull("sidr.cash_out_id");
            //未到账期, 当前时间-3天大于创建时间
            wrapper.gt("sidr.created_time", DateUtils.calcDays(new Date(), -3));
            Date startDate = DateUtils.calcDays(now, -3);
            jsonObject.put("date", df.format(startDate) + " ~ " + df.format(now));
        } else {
//            wrapper.isNotNull("sidr.cash_out_id");
            //已到账期, 当前时间-4~27天大于创建时间
            wrapper.between("sidr.created_time", DateUtils.calcDays(new Date(), -27), DateUtils.calcDays(new Date(), -4));
            Date startDate = DateUtils.calcDays(now, -27);
            Date endDate = DateUtils.calcDays(now, -4);
            jsonObject.put("date", df.format(startDate) + " ~ " + df.format(endDate));
        }
        if (storeId != null) {
            wrapper.eq("sidr.store_id", storeId);
        }
        //未绑定提现记录的
        LocalDate startDate = LocalDate.parse(startTime);
        LocalDate endDate = LocalDate.parse(endTime);
        // 创建当天的开始和结束时间点
        LocalDateTime startOfDay = startDate.atStartOfDay();
        LocalDateTime endOfDay = endDate.atTime(LocalTime.MAX);
        wrapper.between("sidr.created_time", startOfDay, endOfDay)
                .orderByDesc("sidr.created_time");
        if (null != incomeType) {
            if (0 == incomeType) {
                wrapper.in("sidr.income_type", CouponTypeEnum.COUPON.getCode(), CouponTypeEnum.GROUP_BUY.getCode());
            } else {
                wrapper.eq("sidr.income_type", incomeType);
            }
        }
        // 计算总钱数
        List<StoreIncomeDetailsRecordVo> list = storeIncomeDetailsRecordMapper.selectRecordList(wrapper);
        StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
        for (StoreIncomeDetailsRecordVo storeIncomeDetailsRecord : list) {
            StoreIncomeDetailsRecordVo vo = new StoreIncomeDetailsRecordVo();
            BeanUtils.copyProperties(storeIncomeDetailsRecord, vo);
            storeIncomeDetailsRecord.setMoneyStr(new BigDecimal(vo.getMoney()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
            String format = df.format(storeIncomeDetailsRecord.getCreatedTime());
            storeIncomeDetailsRecord.setDate(format);
            storeIncomeDetailsRecord.setCommissionRate(storeInfo.getCommissionRate());
            storeIncomeDetailsRecord.setIncomeMoney(new BigDecimal(vo.getMoney()).add(new BigDecimal(vo.getCommission())).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
            storeIncomeDetailsRecord.setCommissionStr(new BigDecimal(vo.getCommission()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
            vo.setCommissionRate(storeInfo.getCommissionRate());
        }
        jsonObject.put("data", ListToPage.setPage(list, page, size));
        jsonObject.put("money", new BigDecimal(list.stream().mapToInt(StoreIncomeDetailsRecord::getMoney).sum()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        return jsonObject;
    }

    /**
     * 账户余额
     *
     * @param storeId 门店id
     * @return 账户余额
     */
    @Override
    public Map<String, Object> accountBalance(Integer storeId) {
        // TODO 可提现金额 - cashout表里的已提现和待审核的
        Map<String, Object> map = new HashMap<>();
        LambdaQueryWrapper<StoreUser> storeUserWrapper = new LambdaQueryWrapper<>();
        storeUserWrapper.eq(StoreUser::getStoreId, storeId);
        StoreUser storeUser = storeUserService.getOne(storeUserWrapper);
        //余额 门店用户表
        map.put("balance", new BigDecimal(storeUser.getMoney()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        LambdaQueryWrapper<StoreIncomeDetailsRecord> wrapper = new LambdaQueryWrapper<>();
        //当前时间-3天大于创建时间
        wrapper.between(StoreIncomeDetailsRecord::getCreatedTime, DateUtils.calcDays(new Date(), -27), DateUtils.calcDays(new Date(), -4))
                //未绑定提现记录的
                .isNull(StoreIncomeDetailsRecord::getCashOutId)
                .eq(StoreIncomeDetailsRecord::getStoreId, storeId);
        List<StoreIncomeDetailsRecord> list = this.list(wrapper);
        int cashOutMoney = 0;
        cashOutMoney += list.stream().mapToInt(StoreIncomeDetailsRecord::getMoney).sum();
        List<StoreCashOutRecord> storeCashOutRecords = storeCashOutRecordMapper.selectList(new QueryWrapper<StoreCashOutRecord>().eq("store_id", storeId).in("payment_status", "1", "3").eq("delete_flag", "0"));
        int totalAmount = storeCashOutRecords.stream().collect(Collectors.summingInt(StoreCashOutRecord::getMoney));
        //可提现金额 4~27天
        map.put("cashOutMoney", new BigDecimal(cashOutMoney).subtract(BigDecimal.valueOf(totalAmount)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        return map;
    }

    /**
     * 团购收益
     *
     * @param storeId    门店id
     * @param date       日期
     * @param incomeType 收入类型, 0:主页, 1:优惠券, 2:代金券, 3:套餐, 4:联名卡
     * @return 团购收益
     */
    @Override
    public StoreIncomeDetailsRecordVo groupIncome(Integer storeId, String date, Integer incomeType, Integer page, Integer size) {
        LambdaQueryWrapper<StoreIncomeDetailsRecord> wrapper = new LambdaQueryWrapper<>();
        //当前时间-3天大于创建时间
        wrapper.between(StoreIncomeDetailsRecord::getCreatedTime, date + " 00:00:00", date + " 23:59:59")
                //未绑定提现记录的
                .isNull(StoreIncomeDetailsRecord::getCashOutId)
                .eq(StoreIncomeDetailsRecord::getStoreId, storeId);
        if (null != incomeType && 0 == incomeType) {
            wrapper.in(StoreIncomeDetailsRecord::getIncomeType, CouponTypeEnum.COUPON.getCode(), CouponTypeEnum.GROUP_BUY.getCode());
        } else {
            wrapper.eq(StoreIncomeDetailsRecord::getIncomeType, incomeType);
        }
        // 查询店铺信息
        StoreInfo storeInfo = storeInfoMapper.selectById(storeId);

        List<StoreIncomeDetailsRecord> list = this.list(wrapper);
        Integer allIncome = 0;
        Integer commission = 0;
        for (StoreIncomeDetailsRecord storeIncomeDetailsRecord : list) {
            allIncome += storeIncomeDetailsRecord.getMoney();
            commission += storeIncomeDetailsRecord.getCommission();
        }
        StoreIncomeDetailsRecordVo vo = new StoreIncomeDetailsRecordVo();
        vo.setCommissionRate(storeInfo.getCommissionRate());
        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        jsonArray.forEach(item -> {
            JSONObject jsonObject = (JSONObject) item;
            jsonObject.put("moneyStr", new BigDecimal(jsonObject.getString("money")).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        });
        vo.setDate(date);
        // 售价
        vo.setIncomeMoney(new BigDecimal(allIncome).add(new BigDecimal(commission)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        // 手续费
        vo.setCommissionStr(new BigDecimal(commission).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        // 收益(售价-手续费  存入的时候已经减完了)
        vo.setNoYetPaymentMoney(new BigDecimal(allIncome).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).toString());
        // 设置店铺名称
        vo.setStoreName(storeInfo.getStoreName());
        vo.setStoreId(storeId);

        JSONObject jsonObject = new JSONObject();
        //收益
        //售价
        //服务费
        //退款
        //明细list

        QueryWrapper<StoreIncomeDetailsRecordVo> incomeWrapper = new QueryWrapper<>();
        incomeWrapper.eq("income.delete_flag", 0)
                .eq("income.store_id", storeId)
                .between("income.created_time", date + " 00:00:00", date + " 23:59:59")
                .orderByDesc("income.created_time");
        if (null != incomeType) {
            if (0 == incomeType) {
                incomeWrapper.in("income_type", CouponTypeEnum.COUPON.getCode(), CouponTypeEnum.GROUP_BUY.getCode());
            } else {
                incomeWrapper.eq("income_type", incomeType);
            }
        }
        List<StoreIncomeDetailsRecordVo> incomeDetailsRecordVoList = storeIncomeDetailsRecordMapper.getIncomeList(incomeWrapper);
        Map<String, List<StoreIncomeDetailsRecordVo>> collect = incomeDetailsRecordVoList.stream().collect(Collectors.groupingBy(x -> x.getRefundType()));

        vo.setIncomeDetailsRecordVoList(new ArrayList<>());
        vo.setRefundMoney(new BigDecimal(0));
        vo.setCouponCount(0);
        if (collect.containsKey("false")) {
            vo.setIncomeDetailsRecordVoList(ListToPage.setPage(incomeDetailsRecordVoList, page, size).getRecords());
//                    ListToPage.setPage(
//                            collect.get("false")
//                                    .stream()
//                                    .sorted(Comparator.comparing(StoreIncomeDetailsRecordVo::getCheckTime)
//                                            .reversed()).collect(Collectors.toList()), page, size).getRecords());
            vo.setCouponCount(collect.get("false").size() - (collect.containsKey("true") ? collect.get("true").size() : 0));
        }
        if (collect.containsKey("true")) {
            vo.setRefundMoney(new BigDecimal(collect.get("true").stream().mapToInt(StoreIncomeDetailsRecordVo::getMoney).sum()).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP));
        }
        return vo;
    }

    @Override
    public Integer todayOrderCount(Integer storeId) {
        LambdaQueryWrapper<LifeUserOrder> wrapper = new LambdaQueryWrapper<>();
        LocalDate now = LocalDate.now();
        wrapper.eq(LifeUserOrder::getStoreId, storeId)
                .in(LifeUserOrder::getStatus, OrderStatusEnum.WAIT_USE.getStatus(), OrderStatusEnum.USED.getStatus(),OrderStatusEnum.COMPLETE.getStatus())
                .between(LifeUserOrder::getBuyTime, now + " 00:00:00", now + " 23:59:59");
        return lifeUserOrderMapper.selectCount(wrapper);
    }
}
