package shop.alien.store.service;

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.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import shop.alien.entity.result.BusinessException;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.LifeUserOrderDto;
import shop.alien.entity.store.excelVo.LifeUserOrderExcelVo;
import shop.alien.entity.store.excelVo.util.ExcelGenerator;
import shop.alien.entity.store.vo.LifeUserOrderVo;
import shop.alien.entity.store.vo.StoreInfoVo;
import shop.alien.mapper.*;
import shop.alien.store.config.GaoDeMapUtil;
import shop.alien.store.util.ali.AliApi;
import shop.alien.util.ali.AliOSSUtil;
import shop.alien.util.common.AlipayTradeRefund;
import shop.alien.util.common.UniqueRandomNumGenerator;
import shop.alien.util.common.constant.CouponStatusEnum;
import shop.alien.util.common.constant.CouponTypeEnum;
import shop.alien.util.common.constant.DiscountCouponEnum;
import shop.alien.util.common.constant.OrderStatusEnum;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class LifeUserOrderService extends ServiceImpl<LifeUserOrderMapper, LifeUserOrder> {

    private final LifeUserOrderMapper lifeUserOrderMapper;

    private final LifeCouponMapper lifeCouponMapper;

    private final LifeRefundOrderMapper lifeRefundOrderMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final AlipayTradeRefund alipayTradeRefund;

    private final LifeUserService lifeUserService;

    private final StoreIncomeDetailsRecordMapper storeIncomeDetailsRecordMapper;

    private final GaoDeMapUtil gaoDeMapUtil;

    private final LifeFansMapper lifeFansMapper;

    private final StoreCommentService storeCommentService;

    private final LifeUserMapper lifeUserMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final StoreImgMapper storeImgMapper;

    private final StoreUserMapper storeUserMapper;
    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;
    private final OrderCouponMiddleService orderCouponMiddleService;

    private final AliOSSUtil aliOSSUtil;
    private final OrderCouponMiddleMapper orderCouponMiddleMapper;
    private final LifeGroupBuyMainMapper lifeGroupBuyMainMapper;
    private final AliApi aliApi;

    @Value("${spring.web.resources.excel-path}")
    private String excelPath;
    @Value("${spring.web.resources.excel-clearing-receipt}")
    private String excelClearingReceipt;
    @Value("${spring.web.resources.excel-generate-path}")
    private String excelGeneratePath;
    @Value("${spring.web.resources.url}")
    private String fileUrl;

    public List<Map<String, Object>> getOrderListByStatus(Integer page, Integer size, String userId, String status,
                                                          String quanNameSearch, Integer storeType, String baojiaStatus, String orderNo, Integer storeId) {
        List<Map<String, Object>> returnList = new ArrayList<>();

        // 构建基础查询条件
        LambdaQueryWrapper<LifeUserOrder> baseWrapper = new LambdaQueryWrapper<>();
        baseWrapper.eq(StringUtils.isNotEmpty(userId), LifeUserOrder::getUserId, userId);
        baseWrapper.eq(StringUtils.isNotEmpty(status), LifeUserOrder::getStatus, status);
        baseWrapper.like(StringUtils.isNotEmpty(orderNo), LifeUserOrder::getOrderNo, orderNo);
        baseWrapper.like(null != storeId, LifeUserOrder::getStoreId, storeId);

        // 先查询符合条件的订单号，并进行分页
        baseWrapper
                .groupBy(LifeUserOrder::getOrderNo)
                .orderByAsc(LifeUserOrder::getStatus)
                .orderByDesc(LifeUserOrder::getUpdatedTime);

        List<LifeUserOrder> orderList = lifeUserOrderMapper.selectList(baseWrapper);
        if (orderList.isEmpty()) {
            return new ArrayList<>();
        }

        //获取所有订单号
        List<String> orderNos = orderList.stream()
                .map(LifeUserOrder::getOrderNo)
                .collect(Collectors.toList());

        // 按订单号分组处理
        Map<String, List<LifeUserOrder>> orderDetailsGrouped = orderList.stream()
                .collect(Collectors.groupingBy(LifeUserOrder::getOrderNo));

        //一次性获取所有优惠券id
        List<String> quanIdList = orderList.stream().map(LifeUserOrder::getQuanId).collect(Collectors.toList());
        //查询所有优惠券
        List<LifeCoupon> lifeCoupons = lifeCouponMapper.getList(new LambdaQueryWrapper<LifeCoupon>().in(!quanIdList.isEmpty(), LifeCoupon::getId, quanIdList));

        //一次性获取所有店铺id
        List<String> storeIdList = orderList.stream().map(LifeUserOrder::getStoreId).collect(Collectors.toList());
        //查询所有店铺
        List<StoreInfo> storeInfoList = storeInfoMapper.getList(new LambdaQueryWrapper<StoreInfo>().in(!storeIdList.isEmpty(), StoreInfo::getId, storeIdList));

        // 查询所有店铺用户
        List<StoreUser> storeUsers = storeUserMapper.selectList(new QueryWrapper<StoreUser>().isNotNull("store_id"));
        Map<Integer, List<StoreUser>> collect1 = storeUsers.stream().collect(Collectors.groupingBy(StoreUser::getStoreId));
        // 遍历每个订单号，处理订单详情
        for (String orderNum : orderNos) {
            List<LifeUserOrder> orderDetails = orderDetailsGrouped.getOrDefault(orderNum, Collections.emptyList());
            if (orderDetails.isEmpty()) {
                continue;
            }
            LifeUserOrder lifeUserOrder = orderDetails.get(0);
            if (StringUtils.isEmpty(lifeUserOrder.getQuanId())) {
                continue;
            }
            LifeCoupon quan = lifeCoupons.stream().filter(a -> a.getId().equals(lifeUserOrder.getQuanId())).collect(Collectors.toList()).get(0);
            if (StringUtils.isEmpty(lifeUserOrder.getStoreId())) {
                continue;
            }
            StoreInfo storeInfo = storeInfoList.stream().filter(a -> lifeUserOrder.getStoreId().equals(a.getId().toString())).collect(Collectors.toList()).get(0);

            Map<String, Object> map = new HashMap<>();
            map.put("orderId", lifeUserOrder.getId());
            map.put("orderNo", lifeUserOrder.getOrderNo());
            Integer deleteFlag = 1;
            Integer storeStatus = 0;
            Integer logoutFlag = 0;
            // 店铺用户状态，注销，删除，禁用;
            if (collect1.containsKey(Integer.parseInt(lifeUserOrder.getStoreId()))) {
                List<StoreUser> storeUsers1 = collect1.get(Integer.parseInt(lifeUserOrder.getStoreId()));
                StoreUser storeUser = storeUsers1.get(0);
                deleteFlag = storeUser.getDeleteFlag();
                storeStatus = storeUser.getStatus();
                logoutFlag = storeUser.getLogoutFlag();
            }
            ;
            map.put("abnormalStateFlag", 0);
            if (deleteFlag == 1 || storeStatus == 1 || logoutFlag == 1) {
                map.put("abnormalStateFlag", 1);
            }
            // 营业状态
            map.put("businessStatus", storeInfo.getBusinessStatus());
            // 计算实付金额
            String finalPrice = new BigDecimal(lifeUserOrder.getFinalPrice())
                    .multiply(new BigDecimal(orderDetails.size()))
                    .toString();
            map.put("price", finalPrice);
            map.put("count", lifeUserOrderMapper.selectCount(new LambdaQueryWrapper<LifeUserOrder>().eq(LifeUserOrder::getOrderNo, lifeUserOrder.getOrderNo())));

            if (lifeUserOrder.getStatus() == 0) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(lifeUserOrder.getBuyTime());
                calendar.add(Calendar.DAY_OF_MONTH, quan.getExpirationDate());
                Date expirationDate = calendar.getTime();
                if (quan.getEndDate() == null) {
                    map.put("youxiaoqiTime", expirationDate);
                } else {
                    Date youxiaoqiTime = expirationDate.compareTo(quan.getEndDate()) > 0 ? quan.getEndDate() : expirationDate;
                    map.put("youxiaoqiTime", youxiaoqiTime);
                }
            } else {
                map.put("xiadanTime", lifeUserOrder.getPayTime());
            }
            map.put("storeName", storeInfo.getStoreName());
            map.put("storeType", storeInfo.getBusinessSection());

            // 计算保价状态
            // 0 未开启 1 生效中 2 已过期
            int priceProtectionStatus = 0;
            if (quan.getOpenPriceProtection() != null && quan.getOpenPriceProtection() != 0) {
                LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
                Date createdTime = lifeUserOrder.getCreatedTime();
                LocalDateTime orderCreatedTime = createdTime.toInstant()
                        .atZone(ZoneId.systemDefault())
                        .toLocalDateTime();
                priceProtectionStatus = orderCreatedTime.isAfter(sevenDaysAgo) ? 1 : 2;
            }
            map.put("baojiaStatus", priceProtectionStatus);

            // 只有当baojiaStatus参数存在且筛选结果不包含当前订单时，跳过该订单
            if (baojiaStatus != null && !baojiaStatus.isEmpty()) {
                try {
                    int targetStatus = Integer.parseInt(baojiaStatus);
                    if (priceProtectionStatus != targetStatus) {
                        continue;
                    }
                } catch (NumberFormatException e) {
                    throw new RuntimeException("保价状态参数格式错误", e);
                }
            }

            // 继续设置其他订单信息
            map.put("storeName", storeInfo.getStoreName());
            map.put("quanName", quan.getName());
            map.put("quanId", quan.getId());
            map.put("status", lifeUserOrder.getStatus());

            //
            String imgs = quan.getImagePath();
            if (imgs != null && !imgs.startsWith("h")) {
                if (StringUtils.isNotEmpty(imgs)) {
                    List<String> collect = Arrays.stream(imgs.split(","))
                            .map(String::trim)
                            .collect(Collectors.toList());
                    List<StoreImg> storeImgs = storeImgMapper.selectList(new LambdaQueryWrapper<StoreImg>().in(StoreImg::getId, collect));
                    if (storeImgs != null) {
                        imgs = storeImgs.stream()
                                .map(StoreImg::getImgUrl)
                                .collect(Collectors.joining(","));
                    }
                }

            }


            map.put("image", imgs);
            map.put("quanType", quan.getType());

            // 获取全部券码
            String quanCode = orderDetails.stream()
                    .filter(o -> o.getStatus() == 0)
                    .map(LifeUserOrder::getQuanCode)
                    .collect(Collectors.joining(","));
            map.put("quanCode", quanCode);
            map.put("storeId", storeInfo.getId());

            // 检查是否已评价
            LambdaQueryWrapper<StoreComment> storeCommentWrapper = new LambdaQueryWrapper<>();
            storeCommentWrapper.eq(StoreComment::getUserId, userId);
            storeCommentWrapper.eq(StoreComment::getStoreId, lifeUserOrder.getStoreId());
            storeCommentWrapper.eq(StoreComment::getBusinessType, 5);
            storeCommentWrapper.eq(StoreComment::getBusinessId, lifeUserOrder.getId());
            int count = storeCommentService.count(storeCommentWrapper);
            map.put("hasComment", count > 0);

            returnList.add(map);
        }

        List<Map<String, Object>> resultList = returnList;
        if (null != storeType) {
            resultList = resultList.stream().filter(a -> a.get("storeType").equals(storeType)).collect(Collectors.toList());
        }
        if (StringUtils.isNotEmpty(quanNameSearch)) {
            resultList = resultList.stream().filter(a -> a.get("quanName").toString().contains(quanNameSearch) || a.get("storeName").toString().contains(quanNameSearch)).collect(Collectors.toList());
        }
        return resultList;
    }

    public Map<String, Object> getOrderByOrderId(String orderId, String jingdu, String weidu) {
        Map<String, Object> returnMap = new HashMap<>();
        LifeUserOrder order = lifeUserOrderMapper.selectById(orderId);
        if (order == null) {
            return null;
        }
        // 获取该订单编号的所有订单
        LambdaQueryWrapper<LifeUserOrder> allOrderWrapper = new LambdaQueryWrapper<>();
        allOrderWrapper.eq(LifeUserOrder::getOrderNo, order.getOrderNo());
        String quanCodes = lifeUserOrderMapper.selectList(allOrderWrapper).stream().filter(o -> o.getStatus() == 0)
                .map(o -> o.getQuanCode())
                .collect(Collectors.joining(","));

        Map<String, Object> orderMap = new HashMap<>();
        String quanPrice = order.getPrice();
        String finalPrice = order.getFinalPrice();
        String unusedDate;
        String useRule;
        String applicableRule;
        int status = order.getStatus();
        String imagePath;
        LifeCoupon quan = lifeCouponMapper.selectById(order.getQuanId());
        if (quan == null) {
            return null;
        }
        unusedDate = quan.getUnusedDate();
        useRule = quan.getUseRule();
        applicableRule = quan.getApplicableRule();
        imagePath = quan.getImagePath();
        orderMap.put("orderId", order.getId());
        orderMap.put("quanName", quan.getName());
        orderMap.put("quanPrice", quanPrice);
        orderMap.put("shifuPrice", finalPrice);
        orderMap.put("unusedDate", unusedDate);
        orderMap.put("useRule", useRule);
        orderMap.put("applicableRule", applicableRule);
        orderMap.put("quanCode", quanCodes);
        orderMap.put("status", status);
        orderMap.put("imagePath", imagePath);
        QueryWrapper<StoreInfoVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.id", order.getStoreId());
        StoreInfoVo store = storeInfoMapper.getStoreInfoVoOne(queryWrapper);
        orderMap.put("storeId", store.getId());
        returnMap.put("order", orderMap);

        // 添加是否关注逻辑
        String userId = order.getUserId();
        LifeUser userById = lifeUserService.getUserById(userId);
        String s = "user_" + userById.getUserPhone();

        String receiverId = "store_" + store.getStorePhone();

        //关注我的
        LambdaQueryWrapper<LifeFans> wrapperOne = new LambdaQueryWrapper<>();
        wrapperOne.eq(LifeFans::getFollowedId, s).eq(LifeFans::getFansId, receiverId);
        List<LifeFans> isFollowMeList = lifeFansMapper.selectList(wrapperOne);

        //我关注的
        LambdaQueryWrapper<LifeFans> wrapperTwo = new LambdaQueryWrapper<>();
        wrapperTwo.eq(LifeFans::getFollowedId, receiverId).eq(LifeFans::getFansId, s);
        List<LifeFans> isFollowThisList = lifeFansMapper.selectList(wrapperTwo);

        Map<String, Object> storeMap = new HashMap<>();
        storeMap.put("storeName", store.getStoreName());
        storeMap.put("openTime", "9:00-22:00");
        if ((jingdu != null && !jingdu.isEmpty()) && (weidu != null && !weidu.isEmpty())) {
            double storeDistance = gaoDeMapUtil.getDistance(jingdu, weidu, store.getStorePosition().split(",")[0], store.getStorePosition().split(",")[1]);
            DecimalFormat df = new DecimalFormat("#.0");
            storeMap.put("distance", Double.parseDouble(df.format(storeDistance / 1000)) + "km");
        } else {
            storeMap.put("distance", "没有位置信息");
        }
        storeMap.put("address", store.getStoreAddress());
        storeMap.put("contactPerson", store.getStoreContact());
        storeMap.put("phoneNum", store.getStorePhone());
        storeMap.put("jingdu", store.getStorePosition().split(",")[0]);
        storeMap.put("weidu", store.getStorePosition().split(",")[1]);
        returnMap.put("store", storeMap);
        Map<String, Object> goumaixuzhiMap = new HashMap<>();
        goumaixuzhiMap.put("expirationDate", "购买后" + quan.getExpirationDate() + "天有效");
        goumaixuzhiMap.put("useTime", "营业时间可用");
        goumaixuzhiMap.put("useRange", quan.getUseRule());
        goumaixuzhiMap.put("applicableRule", quan.getApplicableRule());
        returnMap.put("gouMaiXuZhi", goumaixuzhiMap);
        Map<String, Object> orderInfoMap = new HashMap<>();
        orderInfoMap.put("orderNo", order.getOrderNo());
        orderInfoMap.put("payMethod", order.getPayMethod());
        LifeUser byId = lifeUserService.getById(order.getUserId());
        orderInfoMap.put("phoneNum", byId.getUserPhone());
        orderInfoMap.put("buyTime", order.getBuyTime());
        orderInfoMap.put("payTime", order.getPayTime());
        orderInfoMap.put("isFollowMe", !isFollowMeList.isEmpty() ? 1 : 0);
        orderInfoMap.put("isFollowThis", !isFollowThisList.isEmpty() ? 1 : 0);

        // 判断保价状态
        Date currentDate = new Date();
        Calendar payTimeCal = Calendar.getInstance();
        payTimeCal.setTime(order.getPayTime());
        Calendar currentCal = Calendar.getInstance();
        currentCal.setTime(currentDate);

        long diffInMillis = currentCal.getTimeInMillis() - payTimeCal.getTimeInMillis();
        long diffInDays = diffInMillis / (24 * 60 * 60 * 1000);
        String priceProtectionStatus = diffInDays < 7 ? "1" : "0";
        orderInfoMap.put("priceProtectionStatus", priceProtectionStatus);
        returnMap.put("orderInfo", orderInfoMap);
        return returnMap;
    }

    public int deleteOrdersById(String orderId) {
        return lifeUserOrderMapper.deleteById(orderId);
    }

    public List<String> getQuanCodeList(String orderNo) {
        LambdaUpdateWrapper<LifeUserOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(LifeUserOrder::getOrderNo, orderNo);
        List<LifeUserOrder> orders = lifeUserOrderMapper.selectList(wrapper);
        return orders.stream().map(LifeUserOrder::getQuanCode).collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> requestRefund(LifeRefundOrder refundOrder) {
        Map<String, Object> returnMap = new HashMap<>();
        if (StringUtils.isEmpty(refundOrder.getRefundMoney()) || Double.parseDouble(refundOrder.getRefundMoney()) == 0) {
            returnMap.put("fail", "无需退款或退款金额为0");
            return returnMap;
        }
        List<OrderCouponMiddle> orderCouponMiddles = orderCouponMiddleMapper.selectList(new QueryWrapper<OrderCouponMiddle>()
                .eq("order_id", refundOrder.getOrderId()).eq("delete_flag",0));
        // 待使用的券（可退款的券）
        List<OrderCouponMiddle> orderCouponMiddles1 = orderCouponMiddles.stream().filter(orderCouponMiddle -> orderCouponMiddle.getStatus() == 1).collect(Collectors.toList());
        if (orderCouponMiddles1.size() < refundOrder.getRefundCouponAmount()) {
            returnMap.put("fail", "退款券数不足");
            return returnMap;
        }
        // 判断累计退款金额
        BigDecimal totalRefundMoney = new BigDecimal(refundOrder.getRefundMoney());
        // 累计退款个数
        int refundCouponCount = 0;
        List<LifeRefundOrder> lifeRefundOrderList = lifeRefundOrderMapper.selectList(new QueryWrapper<LifeRefundOrder>().eq("order_id", refundOrder.getOrderId())
                .eq("status", 0));
        for (LifeRefundOrder lifeRefundOrder : lifeRefundOrderList) {
            totalRefundMoney = totalRefundMoney.add(new BigDecimal(lifeRefundOrder.getRefundMoney()));
            refundCouponCount += lifeRefundOrder.getRefundCouponAmount();
        }
        if(totalRefundMoney.compareTo(new BigDecimal(refundOrder.getRefundMoney()))>0){
            returnMap.put("fail","退款金额(已退+当前退)不能大于订单金额");
            return returnMap;
        }
        Date now = new Date();
        LifeUserOrder order = lifeUserOrderMapper.selectById(refundOrder.getOrderId());
        String result = aliApi.processRefund(order.getOrderNo(), refundOrder.getRefundMoney(), refundOrder.getDescription());
        String refundMessage = "";

        // 更新的中间表id
        List<Integer> updateIds = orderCouponMiddles1.stream().limit(refundOrder.getRefundCouponAmount()).map(x -> x.getId()).collect(Collectors.toList());
        if (result.equals("调用失败")) {
            refundMessage = "退款失败";
            orderCouponMiddleMapper.update(null,new UpdateWrapper<OrderCouponMiddle>().in("id",updateIds)
                    .set("status",OrderStatusEnum.REFUND_FAILED.getStatus())
                    .set("refund_time",now)
                    .set("refund_reason",refundOrder.getReason()));
            // 退款记录
            refundOrder.setApplicationTime(now);
            refundOrder.setRefundTime(now);
            refundOrder.setStatus(1);
        } else {
            refundMessage = "退款成功";
            orderCouponMiddleMapper.update(null,new UpdateWrapper<OrderCouponMiddle>().in("id",updateIds)
                    .set("status",OrderStatusEnum.REFUND.getStatus())
                    .set("refund_time",now)
                    .set("refund_reason",refundOrder.getReason()));
            // 退款记录
            refundOrder.setApplicationTime(now);
            refundOrder.setRefundTime(now);
            refundOrder.setStatus(0);
        }
        // 更新数据（中间表数据+订单表数据：当已退款个数+当前退款个数=已使用的券数时，订单状态改为已退款）
        if (refundCouponCount + refundOrder.getRefundCouponAmount() == orderCouponMiddles.size()) {
            lifeUserOrderMapper.update(null,new UpdateWrapper<LifeUserOrder>().eq("id",order.getId())
                    .set("status",OrderStatusEnum.REFUND.getStatus())
                    .set("refund_time",now)
                    .set("finish_time",now));
            if (null != order.getQuanId()) {
                lifeDiscountCouponUserMapper.update(null,new UpdateWrapper<LifeDiscountCouponUser>().eq("id",order.getQuanId())
                        .set("status",DiscountCouponEnum.WAITING_USED.getValue()).set("use_time",null));
            }   else {
                // 处理 quanId 为 null 的情况，例如日志记录
                log.error("更新优惠券状态失败");
            }
        }

        // 中间表数据更新
        returnMap.put("success", refundMessage);
        // 将退款记录插入到数据库中
        if (lifeRefundOrderMapper.insert(refundOrder) > 0) {
            // 发送通知
            LifeNotice lifeMessage = new LifeNotice();
            LifeUser lifeUser = lifeUserMapper.selectById(order.getUserId());
            lifeMessage.setReceiverId("user_" + lifeUser.getUserPhone());
            String text = "您的编号为" + order.getOrderNo() + "的订单"+refundMessage;
            lifeMessage.setContext(text);
            lifeMessage.setSenderId("system");
            lifeMessage.setIsRead(0);
            lifeMessage.setNoticeType(2);
            lifeNoticeMapper.insert(lifeMessage);
        }
        // 券核销完成后，退款的情况下，需要向 store_income_details_record 表插入一条记录
//        if (null != refundOrder.getStoreId()) {
//            BigDecimal amounts = new BigDecimal(refundOrder.getRefundMoney()).multiply(new BigDecimal(100));
//            BigDecimal commission = amounts.multiply(new BigDecimal(0.04)).setScale(0, RoundingMode.HALF_UP);
//            BigDecimal money = amounts.subtract(commission);
//
//            StoreIncomeDetailsRecord record = new StoreIncomeDetailsRecord();
//            record.setStoreId(refundOrder.getStoreId());
//            record.setUserOrderId(Integer.parseInt(refundOrder.getOrderId()));
//            record.setIncomeType(Integer.parseInt(refundOrder.getQuanType()));
//            record.setBusinessId(Integer.parseInt(refundOrder.getQuanId()));
//            record.setCommission(-commission.intValue());
//            record.setMoney(-money.intValue());
//            storeIncomeDetailsRecordMapper.insert(record);
//        }
        return returnMap;
    }

    public Map<String, Object> refundCheck(Map<String,String> refundOrder) {
        Map<String, Object> returnMap = new HashMap<>();
        LifeUserOrder order = lifeUserOrderMapper.selectById(refundOrder.get("orderId"));
        if( null == order){
            returnMap.put("success", "不可退款");
            returnMap.put("reason", "未查询到订单");
            return returnMap;
        }
        if (order.getStatus() != 1) {
            returnMap.put("success", "不可退款");
            returnMap.put("reason", "当前订单状态不是待消费");
            return returnMap;
        }
        if (Double.parseDouble(order.getFinalPrice()) < Double.parseDouble(refundOrder.get("refundMoney"))) {
            returnMap.put("success", "不可退款");
            returnMap.put("reason", "退款金额大于实付款");
            return returnMap;
        }
        returnMap.put("success", "可以退款");
        return returnMap;
    }

    /**
     * 根据订单号获取可用优惠劵数量
     *
     * @param orderNo
     * @return
     */
    public Integer getAvailableOrderNumByOrderNo(String orderNo) {
        // 统计可用优惠劵数量
        return orderCouponMiddleMapper.selectCount(new QueryWrapper<OrderCouponMiddle>().inSql("id","select id from life_user_order where order_no = " + orderNo ));
    }

    public String exportExcel(String orderNo, String storeId, String quanName, String baojiaStatus, String status) throws IOException {
        // 定义格式化模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<LifeUserOrderExcelVo> lifeUserOrderExcelVos = new ArrayList<>();
        LambdaUpdateWrapper<LifeUserOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(status), LifeUserOrder::getStatus, status);
        wrapper.like(StringUtils.isNotEmpty(orderNo), LifeUserOrder::getOrderNo, orderNo);
        wrapper.like(StringUtils.isNotEmpty(storeId), LifeUserOrder::getStoreId, storeId);

        boolean flag = true;
        if (StringUtils.isNotEmpty(quanName)) {
            LambdaUpdateWrapper<LifeCoupon> wrapper1 = new LambdaUpdateWrapper<>();
            wrapper1.like(LifeCoupon::getName, quanName);
            List<LifeCoupon> quanList = lifeCouponMapper.selectList(wrapper1);
            List<String> idList = quanList.stream().map(LifeCoupon::getId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(idList)) {
                wrapper.in(LifeUserOrder::getQuanId, idList);
            } else {
                flag = false;
            }
        }
        if (flag) {
            wrapper.orderByAsc(LifeUserOrder::getStatus).orderByDesc(LifeUserOrder::getUpdatedTime);
        }
        List<Map<String, Object>> orderNoPage = lifeUserOrderMapper.selectMaps(wrapper);
        List<Object> orderNos = orderNoPage.stream()
                .map(record -> record.get("order_no"))
                .collect(Collectors.toList());
        // 根据订单号列表查询所有相关订单明细
        LambdaQueryWrapper<LifeUserOrder> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.in(LifeUserOrder::getOrderNo, orderNos);
        List<LifeUserOrder> allOrderDetails = lifeUserOrderMapper.selectList(detailWrapper);
        // 按订单号分组处理
        Map<String, List<LifeUserOrder>> orderDetailsGrouped = allOrderDetails.stream()
                .collect(Collectors.groupingBy(LifeUserOrder::getOrderNo));
        int serialNumber = 0;
        for (Object orderDetails : orderDetailsGrouped.keySet()) {
            String orderNum = orderDetails.toString();
            List<LifeUserOrder> order = orderDetailsGrouped.getOrDefault(orderNum, Collections.emptyList());
            LifeUserOrder lifeUserOrder = order.get(0);
            LifeCoupon quan = lifeCouponMapper.selectById(lifeUserOrder.getQuanId());
            QueryWrapper<StoreInfoVo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("a.id", lifeUserOrder.getStoreId());
            StoreInfoVo storeInfoVoOne = storeInfoMapper.getStoreInfoVoOne(queryWrapper);
            LifeUserOrderExcelVo lifeUserOrderExcelVo = new LifeUserOrderExcelVo();
            lifeUserOrderExcelVo.setSerialNumber(++serialNumber);
            lifeUserOrderExcelVo.setOrderNo(lifeUserOrder.getOrderNo());
            lifeUserOrderExcelVo.setStoreId(lifeUserOrder.getStoreId());
            lifeUserOrderExcelVo.setCouponName(quan.getName());
            lifeUserOrderExcelVo.setImage(quan.getImagePath());
            lifeUserOrderExcelVo.setPrice("¥" + quan.getPrice());
            lifeUserOrderExcelVo.setStoreContact(storeInfoVoOne.getStoreContact());
            lifeUserOrderExcelVo.setPhone(storeInfoVoOne.getStorePhone());
            Instant instant = lifeUserOrder.getPayTime().toInstant();
            // 格式化时间
            String formattedTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime().format(formatter);
            lifeUserOrderExcelVo.setPayTime(formattedTime);
            lifeUserOrderExcelVo.setFinishTime(formattedTime);
            lifeUserOrderExcelVo.setOrderStatus(String.valueOf(lifeUserOrder.getStatus()));
            // 订单状态转换
            switch (lifeUserOrder.getStatus()) {
                case 0:
                    lifeUserOrderExcelVo.setOrderStatus("待使用");
                    break;
                case 1:
                    lifeUserOrderExcelVo.setOrderStatus("已核销");
                    break;
                case 2:
                    lifeUserOrderExcelVo.setOrderStatus("已过期");
                    break;
                case 3:
                    lifeUserOrderExcelVo.setOrderStatus("待退款");
                    break;
                case 4:
                    lifeUserOrderExcelVo.setOrderStatus("已退款");
                    break;
                case 5:
                    lifeUserOrderExcelVo.setOrderStatus("退款失败");
                    break;
                case 6:
                    lifeUserOrderExcelVo.setOrderStatus("已取消");
                    break;
                default:
                    lifeUserOrderExcelVo.setOrderStatus("未知状态");
            }
            lifeUserOrderExcelVos.add(lifeUserOrderExcelVo);
        }
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String filePath = ExcelGenerator.generateExcel(excelPath + excelGeneratePath + fileName + ".xlsx", lifeUserOrderExcelVos, LifeUserOrderExcelVo.class);
        return aliOSSUtil.uploadFile(new File(filePath), "excel/" + fileName + ".xlsx");
    }

    /**
     * 创建用户订单
     * @param lifeUserOrderDto 构造数据用
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> createUserOrder(LifeUserOrderDto lifeUserOrderDto) {
        Date date = new Date();
        //1.创建订单
        LifeUserOrder lifeUserOrder = new LifeUserOrder();
        // 用户id
        lifeUserOrder.setUserId(lifeUserOrderDto.getUserId());
        // 店铺id
        lifeUserOrder.setStoreId(lifeUserOrderDto.getStoreId());
        // 订单号
        lifeUserOrder.setOrderNo(lifeUserOrderDto.getOrderNo());
        // 优惠券id
        lifeUserOrder.setQuanId(lifeUserOrderDto.getYhquanId());
        // 付款金额
        lifeUserOrder.setPrice(lifeUserOrderDto.getPrice());
        // 订单金额
        lifeUserOrder.setFinalPrice(lifeUserOrderDto.getFinalPrice());
        // 订单类型
        lifeUserOrder.setCouponType(null == lifeUserOrderDto.getCouponType() ? 1 : lifeUserOrderDto.getCouponType());
        // 订单状态
        lifeUserOrder.setStatus(null == lifeUserOrderDto.getStatus() ? 0 : lifeUserOrderDto.getStatus());
        // 购买时间
        lifeUserOrder.setBuyTime(date);
        this.saveOrUpdate(lifeUserOrder);
        //2.判断是否使用优惠券
        //查询优惠券信息
        if (StringUtils.isNotEmpty(lifeUserOrderDto.getYhquanId())) {
            LifeDiscountCouponUser lifeDiscountCouponUser = lifeDiscountCouponUserMapper.selectById(lifeUserOrderDto.getYhquanId());
            //将优惠券状态变更为已使用
            lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.HAVE_BEEN_USED.getValue()));
            //将优惠券使用时间存入
            lifeDiscountCouponUser.setUseTime(date);
            lifeDiscountCouponUserMapper.updateById(lifeDiscountCouponUser);
        }
        //3.根据购买数量增加中间关系 订单id+券编号 确定一条数据
        BigDecimal sumPrice = new BigDecimal(0);
        for (int i = 0; i < lifeUserOrderDto.getCount(); i++) {
            String code = UniqueRandomNumGenerator.generateUniqueCode(12);
            OrderCouponMiddle orderCouponMiddle = new OrderCouponMiddle();
            // 订单id
            orderCouponMiddle.setOrderId(lifeUserOrder.getId());
            // 团购/代金券id
            orderCouponMiddle.setCouponId(lifeUserOrderDto.getCouponId());
            // 团购/代金券 code
            orderCouponMiddle.setCouponCode(code);
            // 团购/代金券价格
            if(i == lifeUserOrderDto.getCount() - 1){
                orderCouponMiddle.setPrice(new BigDecimal(lifeUserOrderDto.getFinalPrice()).subtract(sumPrice).setScale(2,BigDecimal.ROUND_HALF_UP));
            } else {
                BigDecimal divide = new BigDecimal(lifeUserOrderDto.getFinalPrice()).divide(new BigDecimal(lifeUserOrderDto.getCount()), 2, BigDecimal.ROUND_HALF_UP);
                orderCouponMiddle.setPrice(divide);
                sumPrice = sumPrice.add(divide);
            }
            // 订单状态
            orderCouponMiddle.setStatus(0);
            orderCouponMiddleService.save(orderCouponMiddle);
            // 使用时间
            // 退款时间
            // 删除标记
        }
        //4. 代金券/团购库存扣除 coupon_type 1 代金券 2团购
        int successful = 0;
        if(lifeUserOrderDto.getCouponType() == 2){
            // 团购库存扣除
            successful = lifeGroupBuyMainMapper.update(null, new UpdateWrapper<LifeGroupBuyMain>()
                    .eq("id", lifeUserOrderDto.getCouponId()).setSql("inventory_num = inventory_num - " + lifeUserOrderDto.getCount()));
        } else {
            successful = lifeCouponMapper.update(null, new UpdateWrapper<LifeCoupon>()
                    .eq("id", lifeUserOrderDto.getCouponId()).setSql("stock_qty = stock_qty - " + lifeUserOrderDto.getCount()));
        }
        if(successful == 0){
            log.error("库存不足");
            throw new BusinessException("库存不足");
        }
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("success", "下单成功");
        returnMap.put("orderNo", lifeUserOrderDto.getOrderNo());
        returnMap.put("lifeUserOrder", lifeUserOrder);
        return returnMap;
    }

    /**
     * 更新用户订单
     *
     * @param lifeUserOrderDto 构造数据用
     */
    @Transactional
    public boolean updateUserOrder(LifeUserOrderDto lifeUserOrderDto) {
        Date date = new Date();
        LifeUserOrder lifeUserOrder = lifeUserOrderMapper.selectById(lifeUserOrderDto.getId());
        if ( null == lifeUserOrder){
            log.error("updateUserOrder未查询到订单");
            return false;
        }
        UpdateWrapper<OrderCouponMiddle> orderCouponMiddleUpdateWrapper = new UpdateWrapper<>();
        orderCouponMiddleUpdateWrapper.eq("order_id",lifeUserOrderDto.getId());
        // 根据状态判断怎么更新数据 目前只进行已支付，已取消，已过期判断
        // TODO 后续再进行已核销和已退款判断 ()
        switch (lifeUserOrderDto.getStatus()){
            case 1:
                lifeUserOrder.setPayTime(date);
                lifeUserOrder.setPayMethod(lifeUserOrderDto.getPayMethod());
                lifeUserOrder.setStatus(lifeUserOrderDto.getStatus());
                lifeUserOrder.setOrderNo(lifeUserOrderDto.getOrderNo());
                orderCouponMiddleUpdateWrapper.set("status",lifeUserOrderDto.getStatus());
                break;
            case 3:
            case 4:
                lifeUserOrder.setStatus(lifeUserOrderDto.getStatus());
                lifeUserOrder.setCancelTime(date);
                lifeUserOrder.setFinishTime(date);
                orderCouponMiddleUpdateWrapper.set("status",lifeUserOrderDto.getStatus());
                break;
        }
        return this.saveOrUpdate(lifeUserOrder) && orderCouponMiddleService.update(orderCouponMiddleUpdateWrapper);
    }

    /**
     * 删除用户订单,删除需要判断订单状态并且删除中间关系
     * @param orderId 订单id
     */
    @Transactional
    public boolean deleteUserOrder(String orderId) {
        LifeUserOrder lifeUserOrder = lifeUserOrderMapper.selectById(orderId);
        if ( null == lifeUserOrder){
            log.error("deleteUserOrder未查询到订单");
            return false;
        }
        // 判断订单状态
        // 已核销才可以删除和已退款可以核销
        if (lifeUserOrder.getStatus() == OrderStatusEnum.WAIT_USE.getStatus()) {
            log.error("deleteUserOrder订单状态错误,订单完成才可以删除");
            return false;
        }
        // 删除中间关系
        UpdateWrapper<OrderCouponMiddle> orderCouponMiddleUpdateWrapper = new UpdateWrapper<>();
        orderCouponMiddleUpdateWrapper.eq("order_id",orderId);
        return this.removeById(orderId) && orderCouponMiddleService.remove(orderCouponMiddleUpdateWrapper);
    }

    /**
     * 查询用户订单列表
     * @param page 页码
     * @param size 每页数量
     * @param userId 用户id
     * @param couponType 订单类型
     * @param name 店铺名称
     */
    public IPage<LifeUserOrderVo> queryUserOrderList(Integer page, Integer size, String userId, String storeId, String couponType,String orderStatus, String name, String startTime, String endTime) {
        IPage<LifeUserOrderVo> brandedPage = new Page<>(page, size);
        QueryWrapper<LifeUserOrderVo> lifeUserOrderQueryWrapper = new QueryWrapper<>();
        lifeUserOrderQueryWrapper.eq(org.apache.commons.lang3.StringUtils.isNotBlank(userId),"luo.user_id",userId);
        lifeUserOrderQueryWrapper.eq(org.apache.commons.lang3.StringUtils.isNotBlank(storeId),"luo.store_id",storeId);
        lifeUserOrderQueryWrapper.eq(null != couponType && !"-1".equals(couponType),"luo.coupon_type",couponType);

        // 提取SQL基础部分，避免重复定义
        String baseSql = "select DISTINCT ocm1.order_id from order_coupon_middle ocm1 where 1=1";

        if (!"-1".equals(orderStatus)) {
            // 非-1状态：直接添加状态条件
            String sql = baseSql + " and ocm1.status = " + orderStatus;
            lifeUserOrderQueryWrapper.inSql("luo.id", sql);
        } else {
            // -1状态且storeId不为空时添加条件
            if (org.apache.commons.lang3.StringUtils.isNotBlank(storeId)) {
                // 注意：原代码中的concat不会修改原字符串，需要重新赋值
                String sql = baseSql + " and ocm1.status not in  ("+OrderStatusEnum.WAIT_PAY.getStatus()
                        +","+OrderStatusEnum.EXPIRE.getStatus()
                        +","+OrderStatusEnum.CANCEL.getStatus()
                        +")";
                lifeUserOrderQueryWrapper.inSql("luo.id", sql);
            }
        }
        lifeUserOrderQueryWrapper.like(org.apache.commons.lang3.StringUtils.isNotBlank(name),"tc.coupon_name",name);
        lifeUserOrderQueryWrapper.gt(org.apache.commons.lang3.StringUtils.isNotBlank(startTime),"luo.created_time",startTime + " 00:00:00");
        lifeUserOrderQueryWrapper.lt(org.apache.commons.lang3.StringUtils.isNotBlank(endTime),"luo.created_time",endTime + " 23:59:59");
        lifeUserOrderQueryWrapper.eq("luo.delete_flag",0);
        lifeUserOrderQueryWrapper.orderByDesc("luo.created_time");
        lifeUserOrderQueryWrapper.groupBy("luo.coupon_type","luo.id");
        IPage<LifeUserOrderVo> lifeUserOrderVoIPage = lifeUserOrderMapper.queryUserOrderList(brandedPage, lifeUserOrderQueryWrapper);
        if (!"-1".equals(orderStatus)) {
            lifeUserOrderVoIPage.getRecords().forEach(x->x.setStatus(Integer.parseInt(orderStatus)));
        }
        // 计算退款金额
        for (LifeUserOrderVo record : lifeUserOrderVoIPage.getRecords()) {
            record.setOrderCouponMiddleList(orderCouponMiddleMapper.selectList(new QueryWrapper<OrderCouponMiddle>().eq("order_id",record.getId())));
            calcExpectIncome(record);
        }
        return lifeUserOrderVoIPage;
    }

    /**
     * 查询用户订单详情
     * @param orderId
     * @return
     */
    public R<LifeUserOrderVo> queryUserOrderDetail(String orderId,String longitude, String latitude) {
        LifeUserOrderVo lifeUserOrderVo = lifeUserOrderMapper.queryUserOrderDetail(orderId,org.apache.commons.lang3.StringUtils.isNotBlank(longitude) && org.apache.commons.lang3.StringUtils.isNotBlank(latitude)?longitude+","+latitude:"");
        if ( null == lifeUserOrderVo){
            log.error("queryUserOrderDetail未查询到订单");
            return R.fail("未查询到订单");
        }
        calcExpectIncome(lifeUserOrderVo);
        return R.data(lifeUserOrderVo);
    }

    private static void calcExpectIncome(LifeUserOrderVo lifeUserOrderVo) {
        // 退款记录
        List<OrderCouponMiddle> orderCouponMiddleList = lifeUserOrderVo.getOrderCouponMiddleList();
        List<OrderCouponMiddle> refundList = orderCouponMiddleList.stream().filter(x -> x.getStatus() == 5).collect(Collectors.toList());
        lifeUserOrderVo.setRefundList(refundList);
        // 预计收入
        // 退款金额
        BigDecimal refundAmount = new BigDecimal(0);
        if(!CollectionUtils.isEmpty(refundList)){
            refundAmount = refundList.stream().map(OrderCouponMiddle::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        }
        // 预计收入
        BigDecimal expectIncome = new BigDecimal(lifeUserOrderVo.getPrice()).subtract(refundAmount);
        String commissionRateStr = lifeUserOrderVo.getCommissionRate();
        BigDecimal commissionRate = BigDecimal.ZERO;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(commissionRateStr)) {
            try {
                // 将字符串转换为 BigDecimal，并除以 100（转换为小数）
                commissionRate = new BigDecimal(commissionRateStr)
                        .divide(new BigDecimal("100"), 4, RoundingMode.HALF_UP);
                // 保留 4 位小数，四舍五入（确保计算精度）
            } catch (NumberFormatException e) {
                // 处理非数字格式的异常（如 commissionRate 为空或非法字符）
                e.printStackTrace();
                // 可根据业务需求设置默认值或抛出提示
            } catch (ArithmeticException e) {
                // 处理除法异常（理论上除以 100 不会出现，此处为稳妥处理）
                e.printStackTrace();
            }
        }
        expectIncome = expectIncome.subtract(expectIncome.multiply(commissionRate)).setScale(2, RoundingMode.HALF_UP);
        lifeUserOrderVo.setExpectIncome(expectIncome);
    }

    /**
     * 平台端-查询订单列表
     * @param page 页码
     * @param size 每页数量
     * @param orderNo 订单号
     * @param orderStatus 订单状态
     * @param couponName 优惠券名称
     * @param couponType 优惠券类型
     * @param storeName 店铺名称
     * @param buyStartTime 购买时间开始
     * @param buyEndTime 购买时间结束
     * @param payStartTime 支付时间开始
     * @param payEndTime 支付时间结束
     * @param finishStartTime 完成时间开始
     * @param finishEndTime 完成时间结束
     */
    public IPage<LifeUserOrderVo> queryOrderList(Integer page, Integer size, String orderNo, String orderStatus, String couponName, String couponType, String storeName, String buyStartTime, String buyEndTime, String payStartTime, String payEndTime, String finishStartTime, String finishEndTime) {
        IPage<LifeUserOrderVo> brandedPage = new Page<>(page, size);
        QueryWrapper<LifeUserOrderVo> lifeUserOrderQueryWrapper = new QueryWrapper<>();
        lifeUserOrderQueryWrapper.like(org.apache.commons.lang3.StringUtils.isNotBlank(orderNo),"luo.order_no",orderNo);
        lifeUserOrderQueryWrapper.like(org.apache.commons.lang3.StringUtils.isNotBlank(couponName),"tc.coupon_name",couponName);
        lifeUserOrderQueryWrapper.eq(org.apache.commons.lang3.StringUtils.isNotBlank(couponType),"tc.coupon_type",couponType);
        lifeUserOrderQueryWrapper.like(org.apache.commons.lang3.StringUtils.isNotBlank(storeName),"si.store_name",storeName);
        lifeUserOrderQueryWrapper.gt(org.apache.commons.lang3.StringUtils.isNotBlank(buyStartTime),"luo.buy_time",buyStartTime + " 00:00:00");
        lifeUserOrderQueryWrapper.lt(org.apache.commons.lang3.StringUtils.isNotBlank(buyEndTime),"luo.buy_time",buyEndTime + " 23:59:59");
        lifeUserOrderQueryWrapper.gt(org.apache.commons.lang3.StringUtils.isNotBlank(payStartTime),"luo.pay_time",payStartTime + " 00:00:00");
        lifeUserOrderQueryWrapper.lt(org.apache.commons.lang3.StringUtils.isNotBlank(payEndTime),"luo.pay_time",payEndTime + " 23:59:59");
        lifeUserOrderQueryWrapper.gt(org.apache.commons.lang3.StringUtils.isNotBlank(finishStartTime),"luo.finish_time",finishStartTime + " 00:00:00");
        lifeUserOrderQueryWrapper.lt(org.apache.commons.lang3.StringUtils.isNotBlank(finishEndTime),"luo.finish_time",finishEndTime + " 23:59:59");
//            @ApiImplicitParam(name = "orderStatus", value = "订单状态,-1，全部（可以不传）；0，待支付;1，已支付/待使用;2，已核销；3，已过期;4，已取消;5.已退款，全退款了才算", required = false),
        // 提取SQL基础部分，避免重复定义
//        String baseSql = "select DISTINCT ocm1.order_id from order_coupon_middle ocm1 where 1=1";

        if (!"-1".equals(orderStatus)) {
            // 非-1状态：直接添加状态条件
//            String sql = baseSql + " and ocm1.status = " + orderStatus;
//            lifeUserOrderQueryWrapper.inSql("luo.id", sql);
            lifeUserOrderQueryWrapper.eq("ocm.status",orderStatus);
        }
        lifeUserOrderQueryWrapper.groupBy("tc.coupon_type","tc.coupon_id");
        IPage<LifeUserOrderVo> lifeUserOrderVoIPage = lifeUserOrderMapper.queryUserOrderList(brandedPage, lifeUserOrderQueryWrapper);

        if (!"-1".equals(orderStatus)) {
            lifeUserOrderVoIPage.getRecords().forEach(x->x.setStatus(Integer.parseInt(orderStatus)));
        }
        return lifeUserOrderVoIPage;
    }

    /**
     * 平台端-查询订单详情
     * @param orderId
     * @return
     */
    public R queryOrderDetail(String orderId) {
        LifeUserOrderVo lifeUserOrderVo = lifeUserOrderMapper.queryUserOrderDetail(orderId,null);
        if ( null == lifeUserOrderVo){
            log.error("queryUserOrderDetail未查询到订单");
            return R.fail("未查询到订单");
        }
        // 退款记录
        calcExpectIncome(lifeUserOrderVo);
        lifeUserOrderVo.setCouponCount(lifeUserOrderVo.getOrderCouponMiddleList().size());
        return R.data(lifeUserOrderVo);
    }
    /**
     * 团购/代金券-校验用户是否可以购买
     * @param couponId 团购/代金券id
     * @param couponType 团购/代金券类型
     * @param userId 用户id
     * @param count 购买数量
     * @return
     */
    public Map<String, Object> buyCouponCheck(String couponId, Integer couponType, String userId,String storeId, Integer count) {
        Map<String, Object> returnMap = new HashMap<>();
        // 获取团购/代金券信息
        Integer status = 0;
        // 限购数量， 已购数量
        Integer buyLimit = 0;
        Integer buyCount = 0;
        // 库存
        Integer stockQty = 0;
        // 结束时间
        Date endTime = null;
        if (couponType == CouponTypeEnum.GROUP_BUY.getCode()) {
            // 团购
            LifeGroupBuyMain lifeGroupBuyMain = lifeGroupBuyMainMapper.selectById(couponId);
            status = lifeGroupBuyMain.getStatus();
            // 限购类型
            Integer quotaType = lifeGroupBuyMain.getQuotaType();
            if (0 != quotaType) {
                // 限购数量
                buyLimit = Integer.parseInt(lifeGroupBuyMain.getQuotaValue());
                // 已购数量
                buyCount = orderCouponMiddleMapper.selectCount(new QueryWrapper<OrderCouponMiddle>().eq("coupon_id", couponId).notIn("status", OrderStatusEnum.CANCEL.getStatus(), OrderStatusEnum.REFUND.getStatus())
                        .inSql("order_id", "select order_id from life_user_order where user_id = " + userId + " and store_id = " + storeId));
            }
            // 库存 inventory_num
            stockQty = lifeGroupBuyMain.getInventoryNum();
            endTime = lifeGroupBuyMain.getEndTime();
        } else if (couponType == CouponTypeEnum.COUPON.getCode()) {
            // 代金券
            LifeCoupon lifeCoupon = lifeCouponMapper.selectById(couponId);
            status = lifeCoupon.getStatus();
            // 限购数量
            buyLimit = Integer.parseInt(lifeCoupon.getPurchaseLimitCode());
            // 已购数量
            buyCount = orderCouponMiddleMapper.selectCount(new QueryWrapper<OrderCouponMiddle>().eq("coupon_id", couponId).notIn("status", OrderStatusEnum.CANCEL.getStatus(), OrderStatusEnum.REFUND.getStatus())
                    .inSql("order_id", "select order_id from life_user_order where user_id = " + userId + " and store_id = " + storeId));
            stockQty = lifeCoupon.getSingleQty();
            endTime = lifeCoupon.getEndDate();
        } else {
            log.error("buyCouponCheck-团购/代金券类型错误");
            returnMap.put("success", false);
            returnMap.put("reason", "团购/代金券类型错误");
            return returnMap;
        }
        // 状态(0草稿/1待审核/2未开始/3审核拒绝/4已售罄/5进行中/6已下架/7已结束/8=2+手动下架)
        if (status != CouponStatusEnum.ONGOING.getCode()) {
            returnMap.put("success", false);
            returnMap.put("reason", "团购/代金券未开始");
            return returnMap;
        }
        // 限购
        if (0 != buyLimit) {
            if (buyCount + count > buyLimit) {
                returnMap.put("success", false);
                returnMap.put("reason", "购买数量大于限购数量");
                return returnMap;
            }
        }
        // 库存
        if (count > stockQty) {
            returnMap.put("success", false);
            returnMap.put("reason", "购买数量大于库存数量");
            return returnMap;
        }
        // 时间
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date nowDay = calendar.getTime();
        if (nowDay.compareTo(endTime) > 0) {
            if (couponType == CouponTypeEnum.GROUP_BUY.getCode()) {
                lifeGroupBuyMainMapper.update(null, new UpdateWrapper<LifeGroupBuyMain>().set("status", CouponStatusEnum.ENDED.getCode()).eq("id", couponId));
            } else {
                lifeCouponMapper.update(null, new UpdateWrapper<LifeCoupon>().set("status", CouponStatusEnum.ENDED.getCode()).eq("id", couponId));
            }
            returnMap.put("success", false);
            returnMap.put("reason", "活动已结束");
            return returnMap;
        }
        returnMap.put("success", true);
        returnMap.put("reason", "可以支付");
        return returnMap;
    }
}