/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.consumptionrecord.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.consumptionrecord.param.*;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.result.BizMemberUserResult;
import vip.xiaonuo.biz.modular.user.service.BizUserService;
import vip.xiaonuo.biz.modular.userfundchangerecord.entity.BizUserFundChangeRecord;
import vip.xiaonuo.biz.modular.userfundchangerecord.service.BizUserFundChangeRecordService;
import vip.xiaonuo.biz.modular.utils.CommonExportUtil;
import vip.xiaonuo.common.cache.CommonCacheOperator;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.consumptionrecord.entity.ConsumptionRecord;
import vip.xiaonuo.biz.modular.consumptionrecord.mapper.ConsumptionRecordMapper;
import vip.xiaonuo.biz.modular.consumptionrecord.service.ConsumptionRecordService;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.dev.api.DevConfigApi;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 消费记录Service接口实现类
 *
 * @author fanzherong
 * @date  2025/02/06 08:56
 **/
@Service
public class ConsumptionRecordServiceImpl extends ServiceImpl<ConsumptionRecordMapper, ConsumptionRecord> implements ConsumptionRecordService {

    @Resource
    private BizUserService bizUserService;

    @Resource
    private CommonCacheOperator commonCacheOperator;

    @Resource
    private BizUserFundChangeRecordService bizUserFundChangeRecordService;

    @Resource
    private DevConfigApi devConfigApi;

    @Override
    public Page<ConsumptionRecord> page(ConsumptionRecordPageParam consumptionRecordPageParam) {
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<ConsumptionRecord>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getUserName())){
            queryWrapper.like("su.name",consumptionRecordPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionOperate())){
            List<String> list = Arrays.asList(consumptionRecordPageParam.getConsumptionOperate().split(","));
            queryWrapper.in("cr.consumption_operate",list);
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getOrgId())){
            queryWrapper.eq("cr.consumption_org",consumptionRecordPageParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeBegin()) &&
                ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeEnd())){
            queryWrapper.between("cr.consumption_time",consumptionRecordPageParam.getConsumptionTimeBegin()+" 00:00:00",consumptionRecordPageParam.getConsumptionTimeEnd()+" 23:59:59");
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getAdjustType())){
            queryWrapper.eq("cr.adjust_type",consumptionRecordPageParam.getAdjustType());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getRecordId())){
            List<String> idList = Lists.newArrayList();
            bizUserService.list(new QueryWrapper<BizUser>().lambda().
                    eq(BizUser::getReferralUser, consumptionRecordPageParam.getRecordId())).
                    forEach(user->idList.add(user.getId()));
            queryWrapper.in("cr.user_id",idList);
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.in("cr.consumption_org", loginUserDataScope);
        } else {
            queryWrapper.in("cr.user_id", StpLoginUserUtil.getLoginUser().getId());
        }
        queryWrapper.eq("cr.DELETE_FLAG","NOT_DELETE");
        queryWrapper.orderByDesc("cr.create_time");
        Page<ConsumptionRecord> pageList = this.getBaseMapper().getPageList(CommonPageRequest.defaultPage(), queryWrapper);
        for(ConsumptionRecord consumptionRecord : pageList.getRecords()){
            if(ObjectUtil.isNotEmpty(consumptionRecord.getPhone())){
                consumptionRecord.setPhone(CommonCryptogramUtil.doSm4CbcDecrypt(consumptionRecord.getPhone()));
            }
            if(StringUtils.equals(consumptionRecord.getConsumptionOperate(),"3") || StringUtils.equals(consumptionRecord.getConsumptionOperate(),"4")){
                //消费结算，设置下说明
                if(StringUtils.equals(consumptionRecord.getConsumptionType(),"1")){
                    consumptionRecord.setConsumptionRemark("积分消费"+consumptionRecord.getVoucherMoney().stripTrailingZeros().toPlainString()+"个");
                }
                if(StringUtils.equals(consumptionRecord.getConsumptionType(),"2")){
                    consumptionRecord.setConsumptionRemark("糕点消费"+consumptionRecord.getAccountMoney().stripTrailingZeros().toPlainString()+"个");
                }
                if(StringUtils.equals(consumptionRecord.getConsumptionType(),"3")){
                    consumptionRecord.setConsumptionRemark("积分消费"+consumptionRecord.getVoucherMoney().stripTrailingZeros().toPlainString()+"个"+"，糕点消费"+consumptionRecord.getAccountMoney().stripTrailingZeros().toPlainString()+"个");
                }
            }
        }
        return pageList;
    }

    @Override
    public Page<ConsumptionRecord> userPage(ConsumptionRecordPageParam consumptionRecordPageParam) {
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<ConsumptionRecord>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getUserName())){
            queryWrapper.like("su.name",consumptionRecordPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionOperate())){
            List<String> list = Arrays.asList(consumptionRecordPageParam.getConsumptionOperate().split(","));
            queryWrapper.in("cr.consumption_operate",list);
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getOrgId())){
            queryWrapper.eq("cr.consumption_org",consumptionRecordPageParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeBegin()) &&
                ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeEnd())){
            queryWrapper.between("cr.consumption_time",consumptionRecordPageParam.getConsumptionTimeBegin()+" 00:00:00",consumptionRecordPageParam.getConsumptionTimeEnd()+" 23:59:59");
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getAdjustType())){
            queryWrapper.eq("cr.adjust_type",consumptionRecordPageParam.getAdjustType());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getRecordId())){
            List<String> idList = Lists.newArrayList();
            bizUserService.list(new QueryWrapper<BizUser>().lambda().
                            eq(BizUser::getReferralUser, consumptionRecordPageParam.getRecordId())).
                    forEach(user->idList.add(user.getId()));
            queryWrapper.in("cr.user_id",idList);
        }
        // 校验数据范围
        queryWrapper.in("cr.user_id", StpLoginUserUtil.getLoginUser().getId());
        queryWrapper.eq("cr.DELETE_FLAG","NOT_DELETE");
        queryWrapper.orderByDesc("cr.create_time");
        Page<ConsumptionRecord> pageList = this.getBaseMapper().getPageList(CommonPageRequest.defaultPage(), queryWrapper);
        for(ConsumptionRecord consumptionRecord : pageList.getRecords()){
            if(ObjectUtil.isNotEmpty(consumptionRecord.getPhone())){
                consumptionRecord.setPhone(CommonCryptogramUtil.doSm4CbcDecrypt(consumptionRecord.getPhone()));
            }
            if(StringUtils.equals(consumptionRecord.getConsumptionOperate(),"3") || StringUtils.equals(consumptionRecord.getConsumptionOperate(),"4")){
                //消费结算，设置下说明
                if(StringUtils.equals(consumptionRecord.getConsumptionType(),"1")){
                    consumptionRecord.setConsumptionRemark("积分消费"+consumptionRecord.getVoucherMoney().stripTrailingZeros().toPlainString()+"个");
                }
                if(StringUtils.equals(consumptionRecord.getConsumptionType(),"2")){
                    consumptionRecord.setConsumptionRemark("糕点消费"+consumptionRecord.getAccountMoney().stripTrailingZeros().toPlainString()+"个");
                }
                if(StringUtils.equals(consumptionRecord.getConsumptionType(),"3")){
                    consumptionRecord.setConsumptionRemark("积分消费"+consumptionRecord.getVoucherMoney().stripTrailingZeros().toPlainString()+"个"+"，糕点消费"+consumptionRecord.getAccountMoney().stripTrailingZeros().toPlainString()+"个");
                }
            }
        }
        return pageList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(ConsumptionRecordAddParam consumptionRecordAddParam) {
        //前置参数校验
        checkParam(consumptionRecordAddParam);
        ConsumptionRecord consumptionRecord = BeanUtil.toBean(consumptionRecordAddParam, ConsumptionRecord.class);
        //获取用户信息
        BizUser bizUser = bizUserService.getById(consumptionRecordAddParam.getUserId());
        //记录账户变动信息
        BizUserFundChangeRecord bizUserFundChangeRecord = new BizUserFundChangeRecord();
        bizUserFundChangeRecord.setOldAccountBalance(bizUser.getAccountBalance());
        bizUserFundChangeRecord.setOldVoucherBalance(bizUser.getVoucherBalance());
        //消费记录信息
        consumptionRecord.setVoucherBalance(bizUser.getVoucherBalance());
        consumptionRecord.setAccountBalance(bizUser.getAccountBalance());
        if(StringUtils.equals(consumptionRecordAddParam.getConsumptionOperate(),"1")){
            bizUserFundChangeRecord.setChangeType("4");
            //会员赠送
            if(StringUtils.equals(consumptionRecordAddParam.getConsumptionType(),"1")){
                //判断当前选择的是代金券还是余额 1：代金券   2：余额
                //选择代金券，用户原有代金券金额+本地赠送金额
                bizUser.setVoucherBalance(bizUser.getVoucherBalance().add(consumptionRecordAddParam.getConsumptionMoney()));
                consumptionRecord.setVoucherMoney(consumptionRecordAddParam.getConsumptionMoney());
            }else if(StringUtils.equals(consumptionRecordAddParam.getConsumptionType(),"2")){
                //选择余额，用户原有余额+本次赠送余额金额
                bizUser.setAccountBalance(bizUser.getAccountBalance().add(consumptionRecordAddParam.getConsumptionMoney()));
                consumptionRecord.setAccountMoney(consumptionRecordAddParam.getConsumptionMoney());
            }
        }else if(StringUtils.equals(consumptionRecordAddParam.getConsumptionOperate(),"2")){
            bizUserFundChangeRecord.setChangeType("5");
            //会员扣减
            if(StringUtils.equals(consumptionRecordAddParam.getConsumptionType(),"1")){
                //选择代金券，用户原有代金券金额-本次扣减金额
                if(consumptionRecord.getConsumptionMoney().compareTo(bizUser.getVoucherBalance()) > 0){
                    throw new CommonException("会员当前账户积分不足，不可扣减！");
                }
                bizUser.setVoucherBalance(bizUser.getVoucherBalance().subtract(consumptionRecordAddParam.getConsumptionMoney()));
                consumptionRecord.setVoucherMoney(consumptionRecordAddParam.getConsumptionMoney());
            }else if(StringUtils.equals(consumptionRecordAddParam.getConsumptionType(),"2")){
                //选择账户余额，用户原有余额-本次扣减余额
                if(consumptionRecord.getConsumptionMoney().compareTo(bizUser.getAccountBalance()) > 0){
                    throw new CommonException("会员当前账户糕点不足，不可扣减！");
                }
                bizUser.setAccountBalance(bizUser.getAccountBalance().subtract(consumptionRecordAddParam.getConsumptionMoney()));
                consumptionRecord.setAccountMoney(consumptionRecordAddParam.getConsumptionMoney());
            }
        }else{
            bizUserFundChangeRecord.setChangeType("2");
            //正常消费结算
            //人工结算需要短信校验,获取手机验证码
            if(StringUtils.equals(consumptionRecordAddParam.getConsumptionOperate(),"3")){
                Object code = commonCacheOperator.get(consumptionRecordAddParam.getPhoneNumber());
                if(ObjectUtil.isNotEmpty(code)){
                    if(!StringUtils.equals(code.toString(),consumptionRecordAddParam.getPhoneCode())){
                        throw new CommonException("验证码不正确！");
                    }else{
                        commonCacheOperator.remove(consumptionRecordAddParam.getPhoneNumber());
                    }
                }else{
                    throw new CommonException("短信验证码已过期");
                }
            }
            //判断当前消费金额是否大于代金券金额，优先扣减代金券金额
            if(consumptionRecordAddParam.getConsumptionMoney().compareTo(bizUser.getVoucherBalance()) > 0){
                //判断代金券金额是否大于0
                if(bizUser.getVoucherBalance().compareTo(BigDecimal.ZERO) > 0){
                    consumptionRecord.setConsumptionType("3");
                }else{
                    consumptionRecord.setConsumptionType("2");
                }
                //计算本次消费和代金券差额
                BigDecimal subtract = consumptionRecordAddParam.getConsumptionMoney().subtract(bizUser.getVoucherBalance());
                //如果差额大于账户余额，表示账户余额不足
                if(subtract.compareTo(bizUser.getAccountBalance()) > 0){
                    throw new CommonException("账户糕点不足，请先充值！");
                }
                //记录消费信息
                consumptionRecord.setVoucherMoney(bizUser.getVoucherBalance());
                //代金券直接清空
                bizUser.setVoucherBalance(new BigDecimal(0));
                //余额扣去差额
                bizUser.setAccountBalance(bizUser.getAccountBalance().subtract(subtract));
                consumptionRecord.setAccountMoney(subtract);
            }else{
                //直接扣减代金券
                bizUser.setVoucherBalance(bizUser.getVoucherBalance().subtract(consumptionRecordAddParam.getConsumptionMoney()));
                consumptionRecord.setVoucherMoney(consumptionRecordAddParam.getConsumptionMoney());
                consumptionRecord.setConsumptionType("1");
            }
        }
        //保存消费记录
        consumptionRecord.setConsumptionOrg(StpLoginUserUtil.getLoginUser().getOrgId());
        consumptionRecord.setConsumptionTime(new Date());
        consumptionRecord.setNewVoucherBalance(bizUser.getVoucherBalance());
        consumptionRecord.setNewAccountBalance(bizUser.getAccountBalance());
        this.save(consumptionRecord);
        //修改账户余额
        bizUserService.updateById(bizUser);
        //账户变动信息
        bizUserFundChangeRecord.setNewAccountBalance(bizUser.getAccountBalance());
        bizUserFundChangeRecord.setNewVoucherBalance(bizUser.getVoucherBalance());
        bizUserFundChangeRecord.setUserId(bizUser.getId());
        bizUserFundChangeRecordService.save(bizUserFundChangeRecord);
    }

    //会员赠送/扣减
    public void customerConsumption(ConsumptionRecordAddParam consumptionRecordAddParam){

    }

    //参数校验
    public void checkParam(ConsumptionRecordAddParam consumptionRecordAddParam){
        //判断当前操作consumptionOperate  1：会员赠送  2：会员扣减  3：消费结算
        if(ObjectUtil.isEmpty(consumptionRecordAddParam.getConsumptionOperate())){
            throw new CommonException("消费操作consumptionOperate不能为空！");
        }
        if(StringUtils.equals(consumptionRecordAddParam.getConsumptionOperate(),"1") || StringUtils.equals(consumptionRecordAddParam.getConsumptionOperate(),"2")){
            //会员操作填写说明
            if(ObjectUtil.isEmpty(consumptionRecordAddParam.getConsumptionRemark())){
                throw new CommonException("消费说明consumptionRemark不能为空！");
            }
            //选择赠送和扣减操作时要选择代金券还是账户余额
            if(ObjectUtil.isEmpty(consumptionRecordAddParam.getConsumptionType())){
                throw new CommonException("消费方式consumptionType不能为空！");
            }
        }
        if(StringUtils.equals(consumptionRecordAddParam.getConsumptionOperate(),"3")){
            //人工结算，手机号，短信验证码校验
            if(ObjectUtil.isEmpty(consumptionRecordAddParam.getPhoneNumber())){
                throw new CommonException("手机号phoneNumber不能为空！");
            }
            if(ObjectUtil.isEmpty(consumptionRecordAddParam.getPhoneCode())){
                throw new CommonException("短信验证码phoneCode不能为空！");
            }
        }
        if(ObjectUtil.isEmpty(consumptionRecordAddParam.getUserId())){
            throw new CommonException("用户userId不能为空！");
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordAddParam.getPhoneNumber())){
            if (!PhoneUtil.isMobile(consumptionRecordAddParam.getPhoneNumber())) {
                throw new CommonException("手机号码：{}格式错误", consumptionRecordAddParam.getPhoneNumber());
            }
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordAddParam.getUserId())){
            BizUser bizUser = bizUserService.getById(consumptionRecordAddParam.getUserId());
            if(ObjectUtil.isEmpty(bizUser)){
                throw new CommonException("用户不存在!");
            }
            if(StringUtils.equals(bizUser.getUserStatus(),"DISABLED")){
                throw new CommonException("用户账号冻结，不可消费！");
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(ConsumptionRecordEditParam consumptionRecordEditParam) {
        ConsumptionRecord consumptionRecord = this.queryEntity(consumptionRecordEditParam.getId());
        BeanUtil.copyProperties(consumptionRecordEditParam, consumptionRecord);
        this.updateById(consumptionRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<ConsumptionRecordIdParam> consumptionRecordIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(consumptionRecordIdParamList, ConsumptionRecordIdParam::getId));
    }

    @Override
    public ConsumptionRecord detail(ConsumptionRecordIdParam consumptionRecordIdParam) {
        return this.queryEntity(consumptionRecordIdParam.getId());
    }

    @Override
    public ConsumptionRecord queryEntity(String id) {
        ConsumptionRecord consumptionRecord = this.getById(id);
        if(ObjectUtil.isEmpty(consumptionRecord)) {
            throw new CommonException("消费记录不存在，id值为：{}", id);
        }
        return consumptionRecord;
    }

    @Override
    public ConsumptionResult getRecordTotal() {
        String format = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.in("bcr.consumption_org", loginUserDataScope);
        }else{
            ConsumptionResult consumptionResult = new ConsumptionResult();
            consumptionResult.setOrderCount(0);
            consumptionResult.setOrderMoney(new BigDecimal(0));
            return consumptionResult;
        }
        queryWrapper.eq("bcr.DELETE_FLAG","NOT_DELETE");
        queryWrapper.in("bcr.consumption_operate",'3','4');
        queryWrapper.between("bcr.consumption_time", format+" 00:00:00",format+" 23:59:59");
        return this.getBaseMapper().getRecordTotal(queryWrapper);
    }

    @Override
    public Map<String, Object> queryTodayRevenue(ConsumptionRecordPageParam consumptionRecordPageParam) {
        if(ObjectUtil.isEmpty(consumptionRecordPageParam.getConsumptionTime())){
            throw new CommonException("时间不能为空！");
        }
        Map<String,Object> map = Maps.newHashMap();
        QueryWrapper<ConsumptionRecord> todayQuery = getQueryWrapper(consumptionRecordPageParam);
        ConsumptionResult todayTotal = this.getBaseMapper().getRecordTotal(todayQuery);
        map.put("orderTotal",todayTotal.getOrderCount());
        map.put("accountTotal",todayTotal.getOrderMoney());
        String format = DateUtil.format(DateUtil.offsetDay(DateUtil.parseDate(consumptionRecordPageParam.getConsumptionTime()), -1), "yyyy-MM-dd");
        consumptionRecordPageParam.setConsumptionTime(format);
        QueryWrapper<ConsumptionRecord> yesQuery = getQueryWrapper(consumptionRecordPageParam);
        ConsumptionResult yesTotal = this.getBaseMapper().getRecordTotal(yesQuery);
        if(todayTotal.getOrderCount().compareTo(yesTotal.getOrderCount()) >= 0){
            map.put("orderFlag","rise");
            map.put("orderContrast",todayTotal.getOrderCount()-yesTotal.getOrderCount());
            if(todayTotal.getOrderCount()!=0 && yesTotal.getOrderCount()!=0){
                map.put("orderPercent",((todayTotal.getOrderCount()-yesTotal.getOrderCount())/yesTotal.getOrderCount())*100);
            }else{
                map.put("orderPercent",0);
            }
        }else{
            map.put("orderFlag","decline");
            map.put("orderContrast",yesTotal.getOrderCount()-todayTotal.getOrderCount());
            if(todayTotal.getOrderCount()!=0 && yesTotal.getOrderCount()!=0){
                map.put("orderPercent",((yesTotal.getOrderCount()-todayTotal.getOrderCount())/yesTotal.getOrderCount())*100);
            }else{
                map.put("orderPercent",0);
            }
        }

        BigDecimal todayMoney = todayTotal.getOrderMoney();
        BigDecimal yesMoney = yesTotal.getOrderMoney();
        if(todayTotal.getOrderMoney().compareTo(yesTotal.getOrderMoney()) > 0){
            map.put("accountFlag","rise");
            map.put("accountContrast",todayMoney.subtract(yesMoney));

            if(todayMoney.compareTo(BigDecimal.ZERO)!=0 && yesMoney.compareTo(BigDecimal.ZERO) !=0){
                map.put("accountPercent",(todayMoney.subtract(yesMoney)).divide(yesMoney).multiply(new BigDecimal(100)).setScale(1, RoundingMode.HALF_UP));
            }else{
                map.put("accountPercent",0);
            }
        }else{
            map.put("accountFlag","decline");
            map.put("accountContrast",yesMoney.subtract(todayMoney));

            if(todayMoney.compareTo(BigDecimal.ZERO)!=0 && yesMoney.compareTo(BigDecimal.ZERO) !=0){
                map.put("accountPercent",(yesMoney.subtract(todayMoney)).divide(yesMoney).multiply(new BigDecimal(100)).setScale(1,RoundingMode.HALF_UP));
            }else{
                map.put("accountPercent",0);
            }
        }
        return map;
    }

    public QueryWrapper<ConsumptionRecord> getQueryWrapper(ConsumptionRecordPageParam consumptionRecordPageParam){
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTime())){
            queryWrapper.between("bcr.consumption_time",consumptionRecordPageParam.getConsumptionTime()+" 00:00:00",
                    consumptionRecordPageParam.getConsumptionTime()+" 23:59:59");
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.in("bcr.consumption_org", loginUserDataScope);
        }else{
            return null;
        }
        queryWrapper.eq("bcr.DELETE_FLAG","NOT_DELETE");
        queryWrapper.in("bcr.consumption_operate",'3','4');
        return queryWrapper;
    }

    @Override
    public ConsumptionResult getRecordTotal(ConsumptionRecordPageParam consumptionRecordPageParam) {
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getOrgId())){
            queryWrapper.eq("bcr.consumption_org",consumptionRecordPageParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeBegin()) && ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeEnd())){
            queryWrapper.between("bcr.consumption_time",consumptionRecordPageParam.getConsumptionTimeBegin()+" 00:00:00",consumptionRecordPageParam.getConsumptionTimeEnd()+" 23:59:59");
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            queryWrapper.in("bcr.consumption_org", loginUserDataScope);
        }
        queryWrapper.eq("bcr.DELETE_FLAG","NOT_DELETE");
        queryWrapper.in("bcr.consumption_operate","3","4");
        return this.getBaseMapper().getRecordTotal(queryWrapper);
    }



    @Override
    public UserBalanceResult queryBalanceTotal(ConsumptionRecordPageParam consumptionRecordPageParam) {
        QueryWrapper<ConsumptionRecord> queryWrapper = getAccountQueryWrapper(consumptionRecordPageParam);
        UserBalanceResult userBalanceResult = this.getBaseMapper().queryBalanceTotal(queryWrapper);
        QueryWrapper<ConsumptionRecord> customQueryWrapper = getCustomQueryWrapper(consumptionRecordPageParam);
        UserBalanceResult result = this.getBaseMapper().queryBalanceTotal(customQueryWrapper);
        userBalanceResult.setUserCount(result.getUserCount());
        return userBalanceResult;
    }

    public QueryWrapper<ConsumptionRecord> getAccountQueryWrapper(ConsumptionRecordPageParam consumptionRecordPageParam){
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getOrgId())){
            queryWrapper.eq("su.ORG_ID",consumptionRecordPageParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeBegin()) && ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeEnd())){
            queryWrapper.between("su.CREATE_TIME",consumptionRecordPageParam.getConsumptionTimeBegin()+" 00:00:00",consumptionRecordPageParam.getConsumptionTimeEnd()+" 23:59:59");
        }
        queryWrapper.in("su.USER_TYPE","2","3");
        queryWrapper.eq("su.DELETE_FLAG","NOT_DELETE");
        return queryWrapper;
    }

    public QueryWrapper<ConsumptionRecord> getCustomQueryWrapper(ConsumptionRecordPageParam consumptionRecordPageParam){
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeBegin()) && ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeEnd())){
            queryWrapper.between("su.CREATE_TIME",consumptionRecordPageParam.getConsumptionTimeBegin()+" 00:00:00",consumptionRecordPageParam.getConsumptionTimeEnd()+" 23:59:59");
        }
        queryWrapper.in("su.USER_TYPE","2","3");
        queryWrapper.eq("su.DELETE_FLAG","NOT_DELETE");
        return queryWrapper;
    }



    @Override
    public Map<String,Object> queryConsumptionChart(ConsumptionRecordPageParam consumptionRecordPageParam) {
        List<String> timeList = Lists.newArrayList();
        List<BigDecimal> moneyList = Lists.newArrayList();
        List<Integer> orderList = Lists.newArrayList();
        List<Integer> userCountList = Lists.newArrayList();
        Map<String,Object> result = Maps.newHashMap();
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        // 校验数据范围
        List<String> orgList = Lists.newArrayList();
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            orgList = loginUserDataScope;
        }
        List<Map<String, Object>> mapList = this.getBaseMapper().queryConsumptionChart(queryWrapper,orgList);
        for(Map<String,Object> map: mapList){
            timeList.add(MapUtils.getString(map,"dateTime"));
            moneyList.add(new BigDecimal(MapUtils.getString(map,"consumptionMoney")));
            orderList.add(MapUtils.getInteger(map,"consumptionCount"));
            userCountList.add(MapUtils.getInteger(map,"userCount"));
        }
        result.put("dateTime",timeList);
        result.put("consumptionMoney",moneyList);
        result.put("consumptionCount",orderList);
        result.put("userCount",userCountList);
        return result;
    }

    //查询仅七天充值折线图
    @Override
    public Map<String, Object> queryRechargeChar(ConsumptionRecordPageParam consumptionRecordPageParam) {
        Map<String,Object> result = Maps.newHashMap();
        List<BigDecimal> payMoneyList = Lists.newArrayList();
        List<Integer> payCountList = Lists.newArrayList();
        List<String> timeList = Lists.newArrayList();
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        List<Map<String, Object>> mapList = this.getBaseMapper().queryRechargeChar(queryWrapper);
        for(Map<String,Object> map: mapList){
            timeList.add(MapUtils.getString(map,"dateTime"));
            payMoneyList.add(new BigDecimal(MapUtils.getString(map,"payMoney")));
            payCountList.add(MapUtils.getInteger(map,"payCount"));
        }
        result.put("dateTime",timeList);
        result.put("payMoney",payMoneyList);
        result.put("payCount",payCountList);
        return result;
    }


    @Override
    public Map<String, Object> queryRechargeTotal(ConsumptionRecordPageParam consumptionRecordPageParam) {
        Map<String,Object> result = Maps.newHashMap();
        QueryWrapper<ConsumptionRecord> queryWrapperToday = getRechargeQueryWrapper();
        if(ObjectUtil.isEmpty(consumptionRecordPageParam.getConsumptionTime())){
            String format = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");
            queryWrapperToday.between("brr.recharge_time",format+" 00:00:00", format+" 23:59:59");
        }else{
            queryWrapperToday.between("brr.recharge_time",consumptionRecordPageParam.getConsumptionTime()+" 00:00:00",
                    consumptionRecordPageParam.getConsumptionTime()+" 23:59:59");
        }

        //查询当日充值金额和订单数
        ConsumptionResult todayResult = this.getBaseMapper().getRechargeTotal(queryWrapperToday);
        result.put("payMoney",todayResult.getOrderMoney());
        result.put("payCount",todayResult.getOrderCount());
        //查询昨日充值金额和订单数
        String yesTime;
        if(ObjectUtil.isEmpty(consumptionRecordPageParam.getConsumptionTime())){
            yesTime = DateUtil.format(DateUtil.offsetDay(DateUtil.parseDate(DateUtil.format(DateUtil.date(), "yyyy-MM-dd")), -1), "yyyy-MM-dd");
        }else{
            yesTime = DateUtil.format(DateUtil.offsetDay(DateUtil.parseDate(consumptionRecordPageParam.getConsumptionTime()), -1), "yyyy-MM-dd");
        }

        QueryWrapper<ConsumptionRecord> yesWrapper = getRechargeQueryWrapper();
        yesWrapper.between("brr.recharge_time",yesTime+" 00:00:00",yesTime+" 23:59:59");
        ConsumptionResult yesResult = this.getBaseMapper().getRechargeTotal(yesWrapper);
        if(todayResult.getOrderMoney().compareTo(yesResult.getOrderMoney()) >= 0){
            result.put("payMoneyFlag","up");
            result.put("compareMoney",todayResult.getOrderMoney().subtract(yesResult.getOrderMoney()));
        }else{
            result.put("payMoneyFlag","down");
            result.put("compareMoney",yesResult.getOrderMoney().subtract(todayResult.getOrderMoney()));
        }
        if(todayResult.getOrderCount() >= yesResult.getOrderCount()){
            result.put("payOrderFlag","up");
            result.put("compareOrder",todayResult.getOrderCount() - yesResult.getOrderCount());
        }else{
            result.put("payOrderFlag","down");
            result.put("compareOrder",yesResult.getOrderCount() - todayResult.getOrderCount());
        }
        return result;
    }

    public QueryWrapper<ConsumptionRecord> getRechargeQueryWrapper(){
        QueryWrapper<ConsumptionRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brr.delete_flag","NOT_DELETE");
        queryWrapper.eq("brr.is_pay",'1');
        return queryWrapper;
    }

    @Override
    public Map<String, Object> queryEachStore(ConsumptionRecordPageParam consumptionRecordPageParam) {
        Map<String,Object> result = Maps.newHashMap();
        List<Map<String, Object>> mapList = getList(consumptionRecordPageParam);
        result.put("dataList",mapList);
        return result;
    }

    @Override
    public Page<BizMemberUserResult> warnPage(ConsumptionRecordPageParam consumptionRecordPageParam) {
        Page<BizMemberUserResult> warnPageList = new Page();
        String warnSwitch = devConfigApi.getValueByKey("warnSwitch");
        if(ObjectUtil.isNotEmpty(warnSwitch) && StringUtils.equals(warnSwitch,"true")){
            //预警开关开启
            long warnCount = Long.parseLong(devConfigApi.getValueByKey("warnCount"));
            QueryWrapper queryWrapper = new QueryWrapper<ConsumptionRecord>();
            queryWrapper.gt("a.count",warnCount);
            if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getUserName())){
                queryWrapper.like("su.NAME",consumptionRecordPageParam.getUserName());
            }
            warnPageList = this.getBaseMapper().getWarnPageList(CommonPageRequest.defaultPage(), queryWrapper);
            for(BizMemberUserResult bizMemberUserResult : warnPageList.getRecords()){
                if(ObjectUtil.isNotEmpty(bizMemberUserResult.getPhone())){
                    bizMemberUserResult.setPhone(CommonCryptogramUtil.doSm4CbcDecrypt(bizMemberUserResult.getPhone()));
                }
            }
        }
        return warnPageList;
    }


    public List<Map<String, Object>> getList(ConsumptionRecordPageParam consumptionRecordPageParam){
        List<String> orgIds = new ArrayList<>();
        List<String> orgList = Lists.newArrayList();
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isNotEmpty(loginUserDataScope)) {
            orgList = loginUserDataScope;
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getOrgId())){
            orgIds = Arrays.asList(consumptionRecordPageParam.getOrgId().split(","));
        }
        String startTime = null;
        String endTime = null;
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeBegin())){
            startTime=consumptionRecordPageParam.getConsumptionTimeBegin()+" 00:00:00";
        }
        if(ObjectUtil.isNotEmpty(consumptionRecordPageParam.getConsumptionTimeEnd())){
            endTime = consumptionRecordPageParam.getConsumptionTimeEnd()+" 23:59:59";
        }
        List<Map<String, Object>> mapList = this.getBaseMapper().queryEachStore(orgIds, startTime, endTime,orgList);
        return mapList;
    }

    @Override
    public void exportRecord(ConsumptionRecordPageParam consumptionRecordPageParam, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> mapList = getList(consumptionRecordPageParam);
        String fileName = "汇总统计报表.xlsx";
        List<ConsumptionRecordExportResult> list = Lists.newArrayList();
        for(Map<String,Object> map:mapList){
            ConsumptionRecordExportResult consumeRecordExportResult = new ConsumptionRecordExportResult();
            consumeRecordExportResult.setName(MapUtils.getString(map,"name"));
            consumeRecordExportResult.setCode(MapUtils.getString(map,"code"));
            consumeRecordExportResult.setOrderCount(MapUtils.getInteger(map,"orderCount"));
            consumeRecordExportResult.setAccountMoney(new BigDecimal(MapUtils.getString(map,"accountMoney")));
            consumeRecordExportResult.setVoucherMoney(new BigDecimal(MapUtils.getString(map,"voucherMoney")));
            consumeRecordExportResult.setUserCount(MapUtils.getInteger(map,"userCount"));
            list.add(consumeRecordExportResult);
        }
        CommonExportUtil.export(fileName, ConsumptionRecordExportResult.class,list,response,"汇总统计报表");
    }


    public static void main(String[] args) {
        System.out.printf("加密后手机号:"+CommonCryptogramUtil.doSm4CbcEncrypt("15240260262"));
    }
}
