package shop.alien.store.service;

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.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.*;
import shop.alien.entity.store.vo.LifeUserDynamicsVo;
import shop.alien.entity.store.vo.StoreInfoVo;
import shop.alien.mapper.*;
import shop.alien.store.util.LifeDynamicsIdentityHelper;
import shop.alien.store.util.LifeDynamicsIdentityHelper.PublisherScope;
import shop.alien.store.config.GaoDeMapUtil;
import shop.alien.util.common.DistanceUtil;
import shop.alien.util.common.ListToPage;
import shop.alien.util.common.UniqueRandomNumGenerator;
import shop.alien.util.common.UniqueRandomNumGenerator;
import shop.alien.util.common.constant.DiscountCouponEnum;
import shop.alien.util.type.LifeCollectIdentityQuery;
import shop.alien.util.type.TypeUtil;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class LifeUserStoreService {

    private final LifeCouponMapper lifeCouponMapper;

    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;

    private final LifeUserOrderMapper lifeUserOrderMapper;

    private final LifeCollectMapper lifeCollectMapper;

    private final StoreInfoMapper storeInfoMapper;

    private final StoreImgService storeImgService;

    private final StoreStaffConfigMapper storeStaffConfigMapper;

    private final StoreClockInMapper storeClockInMapper;

    private final StoreEvaluationMapper storeEvaluationMapper;

    private final LifeUserDynamicsMapper lifeUserDynamicsMapper;

    private final LifeDynamicsIdentityHelper dynamicsIdentityHelper;

    private final GaoDeMapUtil gaoDeMapUtil;

    private final TypeUtil typeUtil;

    private final StoreClockInService storeClockInService;

    private final StoreBusinessInfoMapper storeBusinessInfoMapper;

    /**
     * 门店列表
     *
     * @param storeType 门店类型
     * @param storeName 门店名称
     * @param distance  距离
     * @param jingdu    经度
     * @param weidu     纬度
     * @param page      页数
     * @param size      页容
     * @return 门店列表
     */
    public List<Map<String, Object>> getStoreList(String storeType, String storeName, Integer distance, String jingdu, String weidu, int page, int size) {
        try {
            // 初始化返回结果列表
            List<Map<String, Object>> returnMaps = new ArrayList<>();
            // 构建查询条件对象
            QueryWrapper<StoreInfoVo> wrapper = new QueryWrapper<>();
            // 添加门店类型筛选条件（）
//            wrapper.in(null != storeType, "a.business_section", storeType);
            // 添加门店名称或相关菜品名称模糊搜索条件
            wrapper.like(!storeName.isEmpty(), "a.store_name", storeName).or().like(!storeName.isEmpty(), "c.dish_name", storeName);
            // 过滤已删除的门店
            wrapper.eq("a.delete_flag", 0);
            // 过滤非营业中的门店
            wrapper.in(null != storeType && !"".equals(storeType), "a.business_types", Arrays.asList(storeType.split(",")));
            // 过滤掉永久关门的店铺
            wrapper.ne("a.business_status", 99);

            // 过滤掉禁用的店铺
            wrapper.eq("a.store_status", 1);
            wrapper.orderByDesc("a.score_avg");

            // 根据构建的条件查询门店信息
            List<StoreInfoVo> storeInfoVoList = storeInfoMapper.getStoreInfoVoListNew(wrapper,jingdu + "," + weidu);
            // 如果查询结果为空，则直接返回空列表
            if (storeInfoVoList.isEmpty()) {
                return returnMaps;
            }
            // 提取所有符合条件的门店ID
            List<Integer> storeIds = storeInfoVoList.stream().map(StoreInfoVo::getId).collect(Collectors.toList());
            // 构建查询优惠券的条件对象
            LambdaUpdateWrapper<LifeCoupon> quanWrapper = new LambdaUpdateWrapper<>();
            // 添加门店ID筛选条件
            quanWrapper.in(LifeCoupon::getStoreId, storeIds)
                    // 添加优惠券状态筛选条件
                    .eq(LifeCoupon::getStatus, 1)
                    // 按照创建时间降序排序
                    .orderByDesc(LifeCoupon::getCreatedTime);
            // 查询符合条件的优惠券列表
            List<LifeCoupon> quanList = lifeCouponMapper.selectList(quanWrapper);
            // 获取全部店铺的评分与平均花销
            Map<String, List<Map<String, Object>>> avgScoreMap = storeEvaluationMapper.allStoreAvgScore().stream().collect(Collectors.groupingBy(o -> o.get("store_id").toString()));
            // 获取用户订单信息，用于计算平均消费
            Map<String, List<Map<String, Object>>> avgPriceMap = lifeUserOrderMapper.allStoreAvgPrice().stream().collect(Collectors.groupingBy(o -> o.get("store_id").toString()));
            // 获取所有店铺的打卡次数
            List<Map<Integer, Integer>> storeClockInCountList = storeClockInService.getStoreClockInCount();
            // 获取所有店铺打卡次数（有图片并且设置为可见的）
            List<Map<Integer, Integer>> storeClockInCountMapList = storeClockInService.getStoreClockInWithCanLookCount();
            // 遍历所有门店信息，构造返回结果
            for (StoreInfoVo store : storeInfoVoList) {

                //门店营业时间信息 Fixme 流式处理，或用 <assiociate>一次性查询
                StoreBusinessInfo storeBusinessInfo = storeBusinessInfoMapper.selectOne(new QueryWrapper<StoreBusinessInfo>().eq("store_id", store.getId()).eq("delete_flag", 0).last("limit 1"));

                Map<String, Object> storeMap = new HashMap<>();
                // 如果用户提供了经纬度信息，则计算并添加门店到用户的距离
                /*if ((jingdu != null && !jingdu.isEmpty()) && (weidu != null && !weidu.isEmpty())) {
                    double storeJing = Double.parseDouble(store.getStorePosition().split(",")[0]);
                    double storeWei = Double.parseDouble(store.getStorePosition().split(",")[1]);
                    double storeDistance = DistanceUtil.haversineCalculateDistance(Double.parseDouble(jingdu), Double.parseDouble(weidu), storeJing, storeWei);
                    storeMap.put("distance", storeDistance);
                } else {
                    // 否则，返回提示信息
                    storeMap.put("distance", "没有位置信息");
                }*/
                storeMap.put("distance", store.getDist());
                // 添加门店的业务状态及其描述
                storeMap.put("businessStatus", store.getBusinessStatus());
                storeMap.put("businessStatusStr", store.getBusinessStatusStr());

                String businessSectionName = store.getBusinessSectionName();
                if(Arrays.asList("酒吧", "KTV", "洗浴汗蒸", "按摩足疗").contains(businessSectionName)){
                    storeMap.put("storeTypeNew", 1);
                } else if (Arrays.asList("丽人美发", "运动健身").contains(businessSectionName)){
                    storeMap.put("storeTypeNew", 2);
                } else if (Arrays.asList("特色美食").contains(businessSectionName)){
                    storeMap.put("storeTypeNew", 3);
                }
                //474bug
                storeMap.put("businessSection", store.getBusinessSection());
                storeMap.put("businessSectionName", store.getBusinessSectionName());
                storeMap.put("businessTypes", store.getBusinessTypes());
                storeMap.put("businessTypesName", store.getBusinessTypesName());
                storeMap.put("businessClassify", store.getBusinessClassify());
                storeMap.put("businessClassifyName", store.getBusinessClassifyName());
                storeMap.put("storeBusinessInfo", storeBusinessInfo);
                // 添加门店ID
                storeMap.put("storeId", store.getId());
                // 如果存在评分数据，则添加评分、平均消费及评价总数
                if (avgScoreMap.containsKey(String.valueOf(store.getId()))) {
                    storeMap.put("avgScore", avgScoreMap.get(String.valueOf(store.getId())).get(0).get("avg_score"));
                    //storeMap.put("avgPrice", avgPriceMap.get(String.valueOf(store.getId())).get(0).get("avg_price"));
                    // 条数
                    storeMap.put("totalNum", avgScoreMap.get(String.valueOf(store.getId())).get(0).get("total_num"));
                } else {
                    // 否则，设置默认值
                    storeMap.put("avgScore", 0);
                    //storeMap.put("avgPrice", 0);
                    storeMap.put("totalNum", 0);
                }
                if (avgPriceMap.containsKey(String.valueOf(store.getId()))) {
                    //storeMap.put("avgScore", avgScoreMap.get(String.valueOf(store.getId())).get(0).get("avg_score"));
                    storeMap.put("avgPrice", avgPriceMap.get(String.valueOf(store.getId())).get(0).get("avg_price"));
                    // 条数
                    //storeMap.put("totalNum", avgScoreMap.get(String.valueOf(store.getId())).get(0).get("total_num"));
                } else {
                    // 否则，设置默认值
                    //storeMap.put("avgScore", 0);
                    storeMap.put("avgPrice", 0);
                    //storeMap.put("totalNum", 0);
                }
                // 添加门店名称
                storeMap.put("storeName", store.getStoreName());
                // 添加门店地址
                storeMap.put("storeAddress", store.getStoreAddress());
                // 添加门店类型
                storeMap.put("storeType", store.getStoreType());
                // 添加门店入口图片
                storeMap.put("entranceImage", store.getEntranceImage());
                // 添加门店图片
                storeMap.put("storeImage", store.getImgUrl());
                // 添加门店简介
                storeMap.put("storeBlurb",store.getStoreBlurb());
                // 解析并添加门店经纬度
                String[] position = store.getStorePosition().split(",");
                storeMap.put("longitude", position.length == 2 ? position[0] : "");
                storeMap.put("latitude", position.length == 2 ? position[1] : "");
                // 构造该门店的优惠券列表
                List<Map<String, Object>> quanMapList = new ArrayList<>();
                if (!quanList.isEmpty()) {
                    for (LifeCoupon quan : quanList) {
                        // 如果优惠券的门店ID与当前门店ID匹配，则添加到优惠券列表中
                        if (store.getId().toString().equals(quan.getStoreId())) {
                            Map<String, Object> quanMap = new HashMap<>();
                            quanMap.put("quanType", quan.getType());
                            quanMap.put("name", quan.getName());
                            quanMap.put("price", quan.getPrice());
                            // 折扣价
                            quanMap.put("offprice", quan.getOffprice());
                            quanMap.put("quanId", quan.getId());
                            quanMapList.add(quanMap);
                        }
                    }
                    // 将优惠券列表添加到门店信息中
                    storeMap.put("quanList", quanMapList);
                }
                // 添加门店类型的描述
                storeMap.put("storeTypeStr", store.getStoreTypeStr());
                // 遍历打卡次数列表，找到当前门店的打卡次数并添加到门店信息中
                storeClockInCountList.forEach(b -> {
                    Integer storeId = b.get("storeId");
                    if (Objects.equals(storeId, store.getId())) {
                        storeMap.put("storeClockInCount", b.get("count"));
                    }
                });

                storeClockInCountMapList.forEach(b -> {
                    Integer storeId = b.get("storeId");
                    if (Objects.equals(storeId, store.getId())) {
                        storeMap.put("storeClockInCountWithCanLook", b.get("count"));
                    }
                });

                // 如果未找到打卡次数，则设置为0
                if (null == storeMap.get("storeClockInCount")) {
                    storeMap.put("storeClockInCount", 0);
                }
                // 如果未找到打卡次数（有图片并且设置为可见的），则设置为0
                if (null == storeMap.get("storeClockInCountWithCanLook")) {
                    storeMap.put("storeClockInCountWithCanLook", 0);
                    continue;
                }
                // 将当前门店的信息添加到返回结果列表中
                returnMaps.add(storeMap);
            }
            // 如果用户提供了距离阈值，则根据距离过滤结果，并按距离升序排序
            if (distance != null) {
                double maxDistance = distance;
                returnMaps = returnMaps.stream().filter(storeMap -> {
                            Object distanceObj = storeMap.get("distance");
                            if (distanceObj == null) {
                                return false; // 排除 null
                            }
                            double distanceValue;
                            try {
                                // 先尝试直接转换为数值类型（如果本身是 Double/Integer 等）
                                if (distanceObj instanceof Number) {
                                    distanceValue = ((Number) distanceObj).doubleValue();
                                }
                                // 再处理字符串类型（如 "100.5"）
                                else if (distanceObj instanceof String) {
                                    // 将字符串解析为 double（注意处理非数字格式的字符串）
                                    distanceValue = Double.parseDouble((String) distanceObj);
                                }
                                // 其他类型视为无效
                                else {
                                    return false;
                                }
                            } catch (NumberFormatException e) {
                                // 字符串无法解析为数字（如 "abc"），视为无效
                                return false;
                            }
                            return distanceValue < maxDistance;
                        })
                        .sorted((map1, map2) -> {
                            double d1 = getDistanceValue(map1.get("distance"));
                            double d2 = getDistanceValue(map2.get("distance"));
                            return Double.compare(d1, d2);
                        })
                        .collect(Collectors.toList());
            }

            returnMaps = returnMaps.stream().sorted(Comparator.comparingDouble(storeMap -> Double.parseDouble( storeMap.get("avgScore").toString()) * -1)).collect(Collectors.toList());
            //returnMaps.sort(Collections.reverseOrder());
            IPage<Map<String, Object>> mapIPage = ListToPage.setPage(returnMaps, page, size);
            // 返回最终结果列表
            return mapIPage.getRecords();
        } catch (Exception e) {
            // 捕获并抛出运行时异常
            throw new RuntimeException(e);
        }
    }
    // 提取一个工具方法，统一处理距离值的转换
    private double getDistanceValue(Object distanceObj) {
        if (distanceObj instanceof Number) {
            return ((Number) distanceObj).doubleValue();
        } else if (distanceObj instanceof String) {
            try {
                return Double.parseDouble((String) distanceObj);
            } catch (NumberFormatException e) {
                return Double.MAX_VALUE; // 无效值排序时放最后
            }
        }
        return Double.MAX_VALUE;
    }

    public Map<String, Object> getStoreDetailById(String storeId, String userId, String jingdu, String weidu) {
        Map<String, Object> returnMap = new HashMap<>();
        QueryWrapper<StoreInfoVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.id", storeId).eq("a.delete_flag", 0);
        StoreInfoVo storeInfoVoOne = storeInfoMapper.getStoreInfoVoOne(queryWrapper);
        Map<String, Object> storeMap = new HashMap<>();
        storeMap.put("storeName", storeInfoVoOne.getStoreName());
        storeMap.put("storeType", storeInfoVoOne.getStoreType());
        storeMap.put("storeLocation", storeInfoVoOne.getStoreAddress());
        storeMap.put("openTime", "10:00-21:30");
        storeMap.put("phoneNum", storeInfoVoOne.getStorePhone());
        storeMap.put("entranceImage", storeInfoVoOne.getEntranceImage());
        storeMap.put("score", storeInfoVoOne.getScore());
        LambdaQueryWrapper<StoreImg> imgWrapper = new LambdaQueryWrapper<>();
        imgWrapper.eq(StoreImg::getStoreId, storeId);
        imgWrapper.eq(StoreImg::getImgType, 10);
        StoreImg one = storeImgService.getOne(imgWrapper);
        if (null != one) {
            storeMap.put("storeImage", one.getImgUrl());
        }
        storeMap.put("jingdu", storeInfoVoOne.getStorePosition().split(",")[0]);
        storeMap.put("weidu", storeInfoVoOne.getStorePosition().split(",")[1]);

        if ((jingdu != null && !jingdu.isEmpty()) && (weidu != null && !weidu.isEmpty())) {
            double storeJing = Double.parseDouble(storeInfoVoOne.getStorePosition().split(",")[0]);
            double storeWei = Double.parseDouble(storeInfoVoOne.getStorePosition().split(",")[1]);
            double storeDistance = DistanceUtil.haversineCalculateDistance(Double.parseDouble(jingdu), Double.parseDouble(weidu), storeJing, storeWei);
            storeMap.put("distance", storeDistance);
        } else {
            storeMap.put("distance", "没有位置信息");
        }

        // 计算店铺到最近地铁站的距离
        JSONObject nearbySubway = gaoDeMapUtil.getNearbySubway(storeInfoVoOne.getStorePosition().split(",")[0], storeInfoVoOne.getStorePosition().split(",")[1]);
        // 地铁名
        String subWayName = nearbySubway.getString("name");
        storeMap.put("subwayName", subWayName);
        // 地铁站经纬度
        String subWayJing = nearbySubway.getString("location").split(",")[0];
        String subWayWei = nearbySubway.getString("location").split(",")[1];

        if ((subWayJing != null && !subWayJing.isEmpty()) && (subWayWei != null && !subWayWei.isEmpty())) {
            double storeJing = Double.parseDouble(storeInfoVoOne.getStorePosition().split(",")[0]);
            double storeWei = Double.parseDouble(storeInfoVoOne.getStorePosition().split(",")[1]);
            double storeDistance2 = DistanceUtil.haversineCalculateDistance(Double.parseDouble(subWayJing), Double.parseDouble(subWayWei), storeJing, storeWei);
            storeMap.put("distance2", storeDistance2);
        } else {
            storeMap.put("distance2", "没有位置信息");
        }

        LambdaUpdateWrapper<LifeCollect> shouCangWrapper = new LambdaUpdateWrapper<>();
        LifeCollectIdentityQuery.applyUserSide(shouCangWrapper, LifeCollectIdentityQuery.resolve(userId, typeUtil));
        shouCangWrapper.eq(LifeCollect::getStoreId, storeId);
        LifeCollect shouCang = lifeCollectMapper.selectOne(shouCangWrapper);
        if (shouCang == null) {
            storeMap.put("collection", 0);
        } else {
            storeMap.put("collection", 1);
        }
        storeMap.put("storeTypeStr", storeInfoVoOne.getStoreTypeStr());
        returnMap.put("storeInfo", storeMap);
        LambdaUpdateWrapper<LifeCoupon> quanWrapper = new LambdaUpdateWrapper<>();
        quanWrapper.eq(LifeCoupon::getStoreId, storeId)
                .eq(LifeCoupon::getStatus, 1)
                .eq(LifeCoupon::getType, 1);
        List<LifeCoupon> quanList = lifeCouponMapper.selectList(quanWrapper);
        List<Map<String, Object>> quanMapList = new ArrayList<>();
        if (!quanList.isEmpty()) {
            for (LifeCoupon quan : quanList) {
                Map<String, Object> quanMap = new HashMap<>();
                quanMap.put("quanId", quan.getId());
                quanMap.put("quanName", quan.getName());
                quanMap.put("unusedDate", quan.getUnusedDate());
                quanMap.put("buyLimit", quan.getBuyLimit());
                quanMap.put("useRule", quan.getUseRule());
                quanMap.put("price", quan.getPrice());
                quanMapList.add(quanMap);
            }
        }
        returnMap.put("quanList", quanMapList);
        LambdaUpdateWrapper<LifeCoupon> tuangouWrapper = new LambdaUpdateWrapper<>();
        tuangouWrapper.eq(LifeCoupon::getStoreId, storeId)
                .eq(LifeCoupon::getStatus, 1)
                .eq(LifeCoupon::getType, 2).orderByDesc(LifeCoupon::getCreatedTime);
        List<LifeCoupon> tuangouList = lifeCouponMapper.selectList(tuangouWrapper);
        List<Map<String, Object>> tuangouMapList = new ArrayList<>();
        if (!tuangouList.isEmpty()) {
            for (LifeCoupon tuangou : tuangouList) {
                Map<String, Object> tuangouMap = new HashMap<>();
                tuangouMap.put("quanId", tuangou.getId());
                tuangouMap.put("quanName", tuangou.getName());
                tuangouMap.put("unusedDate", tuangou.getUnusedDate());
                tuangouMap.put("storeService", tuangou.getStoreService());
                tuangouMap.put("price", tuangou.getPrice());
                tuangouMap.put("image", tuangou.getImagePath());
                tuangouMapList.add(tuangouMap);
            }
        }
        returnMap.put("tuangouList", tuangouMapList);
        LambdaQueryWrapper<StoreStaffConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StoreStaffConfig::getStoreId, storeId);
        List<StoreStaffConfig> storeStaffConfigs = storeStaffConfigMapper.selectList(lambdaQueryWrapper);
        List<Map<String, Object>> employeeList = new ArrayList<>();
        if (!storeStaffConfigs.isEmpty()) {
            for (StoreStaffConfig storeStaffConfig : storeStaffConfigs) {
                Map<String, Object> employeeMap = new HashMap<>();
                employeeMap.put("employeeId", storeStaffConfig.getId());
                employeeMap.put("staffPosition", storeStaffConfig.getStaffPosition());
                employeeMap.put("name", storeStaffConfig.getName());
                employeeMap.put("staffImage", storeStaffConfig.getStaffImage());
                employeeMap.put("proficientProjects", storeStaffConfig.getProficientProjects());
                employeeMap.put("tag", storeStaffConfig.getTag());
                employeeMap.put("personalIntroduction", storeStaffConfig.getPersonalIntroduction());
                employeeList.add(employeeMap);
            }
        }
        // 员工
        returnMap.put("employeeList", employeeList);

        // 该用户的打卡记录（仅审核通过 check_flag=2）
        LambdaQueryWrapper<StoreClockIn> clockInWrapper = new LambdaQueryWrapper<>();
        clockInWrapper.eq(StoreClockIn::getUserId, userId);
        clockInWrapper.eq(StoreClockIn::getCheckFlag, 2);
        List<StoreClockIn> clockInList = storeClockInMapper.selectList(clockInWrapper);

        List<StoreClockIn> clockStoreList = clockInList.stream().filter(item -> item.getStoreId() == Integer.parseInt(storeId)).collect(Collectors.toList());
        // 该用户是否在该店铺打过卡
        if (!clockStoreList.isEmpty()) {
            returnMap.put("clockInStore", 1);
        } else {
            returnMap.put("clockInStore", 0);
        }

        // 今天在该店铺是否打过卡
        int today = (int) clockStoreList.stream().filter(item -> item.getCreatedTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate().equals(LocalDate.now())).count();
        if (today > 0) {
            returnMap.put("clockInStoreToday", 1);
        } else {
            returnMap.put("clockInStoreToday", 0);
        }

        // 在该店铺的打卡次数
        returnMap.put("clockInStoreNum", clockStoreList.size());

        // 该用户打卡的所有店铺次数（一个店铺只算一次）
        int clockInNum = (int) clockInList.stream().map(StoreClockIn::getStoreId).distinct().count();
        returnMap.put("clockInNum", clockInNum);

        // 获取店铺动态列表
        PublisherScope storePublisher = dynamicsIdentityHelper.resolveStorePublisherByStorePhone(storeInfoVoOne.getStorePhone());
        QueryWrapper<LifeUserDynamics> dynamicsWrapper = new QueryWrapper<>();
        dynamicsIdentityHelper.applyPublisherFilter(dynamicsWrapper, storePublisher, "lud");
        dynamicsWrapper.orderByDesc("lud.created_time");
        List<LifeUserDynamicsVo> storeDynamicslist = lifeUserDynamicsMapper.getStoreDynamicslistWithWrapper(userId, dynamicsWrapper);
        List<Map<String, Object>> dynamicsList = new ArrayList<>();
        List<LifeUserDynamicsVo> storeDynamicslist2 = storeDynamicslist.stream().limit(10).collect(Collectors.toList());
        for (LifeUserDynamicsVo lifeUserDynamicsVo : storeDynamicslist2) {
            Map<String, Object> dynamicsMap = new HashMap<>();
            dynamicsMap.put("id", lifeUserDynamicsVo.getId());
            dynamicsMap.put("imagePath", lifeUserDynamicsVo.getImagePath());
            dynamicsMap.put("context", lifeUserDynamicsVo.getContext());
            dynamicsMap.put("userName", lifeUserDynamicsVo.getUserName());
            dynamicsMap.put("userImage", lifeUserDynamicsVo.getUserImage() != null ? lifeUserDynamicsVo.getUserImage() : "null");
            dynamicsMap.put("isLike", lifeUserDynamicsVo.getIsLike());
            dynamicsList.add(dynamicsMap);
        }
        returnMap.put("dynamicsList", dynamicsList);
        returnMap.put("totalDynamicsNum", storeDynamicslist.size());

        return returnMap;
    }

    public Map<String, Object> buyQuan(String quanId, String couponId, String userId, int cnt, String payPrice, String orderNo) {
        Map<String, Object> returnMap = new HashMap<>();
        LifeCoupon quan = lifeCouponMapper.selectById(quanId);
        Date now = new Date();
        List<String> quanCodeList = new ArrayList<>();
        // 添加标识，标记多个quan_code关联一个订单
        String quanAssociationOrderCode = UniqueRandomNumGenerator.generateUniqueCode(12);
        for (int i = 1; i <= cnt; i++) {
            LifeUserOrder userOrder = new LifeUserOrder();
            userOrder.setUserId(userId);
            userOrder.setStoreId(quan.getStoreId());
            userOrder.setQuanId(quanId);
            String code = UniqueRandomNumGenerator.generateUniqueCode(12);
            userOrder.setQuanCode(code);
            quanCodeList.add(code);
            userOrder.setOrderNo(orderNo);
            userOrder.setStatus(0);
            userOrder.setPrice(quan.getPrice());
            String finalPrice = "";
            if (cnt == 1) {
                finalPrice = payPrice;
            } else {
                double price = Double.parseDouble(payPrice);
                double finalPriceValue = price / cnt;
                finalPrice = String.valueOf(finalPriceValue);
            }
            userOrder.setFinalPrice(finalPrice);
            userOrder.setBuyTime(now);
            userOrder.setPayTime(now);
            userOrder.setPayMethod("支付宝支付");
            userOrder.setCreatedTime(now);
            userOrder.setUpdatedTime(now);
            lifeUserOrderMapper.insert(userOrder);
        }
        quan.setStockQty(quan.getStockQty() - cnt);
        if ("1".equals(quan.getSaleTimeEndType())) {
            if (quan.getStockQty() == 0) {
                quan.setEndDate(new Date());
            }
        }
        lifeCouponMapper.updateById(quan);

        //查询优惠券信息
        if (StringUtils.isNotEmpty(couponId)) {
            LifeDiscountCouponUser lifeDiscountCouponUser = lifeDiscountCouponUserMapper.selectById(couponId);
            //将优惠券状态变更为已使用
            lifeDiscountCouponUser.setStatus(Integer.parseInt(DiscountCouponEnum.HAVE_BEEN_USED.getValue()));
            //将优惠券使用时间存入
            lifeDiscountCouponUser.setUseTime(new Date());
            lifeDiscountCouponUserMapper.updateById(lifeDiscountCouponUser);
        }

        returnMap.put("success", "购买成功");
        returnMap.put("orderNo", orderNo);
        returnMap.put("quanCodeList", quanCodeList);
        return returnMap;
    }

    public Map<String, Object> buyQuanCheck(String quanId, String userId, int cnt, String payPrice) {
        Map<String, Object> returnMap = new HashMap<>();
        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();
        LifeCoupon quan = lifeCouponMapper.selectById(quanId);
        int status = quan.getStatus();
        if (status != 1) {
            returnMap.put("success", false);
            returnMap.put("reason", "券的状态不在进行中");
            return returnMap;
        }
        int limitBuyQty = quan.getBuyLimit();
        LambdaUpdateWrapper<LifeUserOrder> orderWrapper = new LambdaUpdateWrapper<>();
        orderWrapper.eq(LifeUserOrder::getUserId, userId)
                .eq(LifeUserOrder::getQuanId, quanId);
        List<LifeUserOrder> BuyedQuanList = lifeUserOrderMapper.selectList(orderWrapper);
        int buyedCnt = BuyedQuanList.size();
        if (cnt + buyedCnt > limitBuyQty) {
            returnMap.put("success", false);
            returnMap.put("reason", "购买数量大于限购数量");
            return returnMap;
        }
        int stockQty = quan.getStockQty();
        if (cnt > stockQty) {
            returnMap.put("success", false);
            returnMap.put("reason", "购买数量大于库存数量");
            return returnMap;
        }
        Date endTime = quan.getEndDate();
        if (nowDay.compareTo(endTime) > 0) {
            quan.setStatus(3);
            lifeCouponMapper.updateById(quan);
            returnMap.put("success", false);
            returnMap.put("reason", "活动已结束");
            return returnMap;
        }
        returnMap.put("success", true);
        returnMap.put("reason", "可以支付");
        return returnMap;
    }
}