package shop.alien.store.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.StoreRenovationRequirementDto;
import shop.alien.entity.store.vo.WebSocketVo;
import shop.alien.mapper.*;
import shop.alien.store.config.WebSocketProcess;
import shop.alien.store.service.StoreRenovationRequirementService;
import shop.alien.store.util.ai.AiContentModerationUtil;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.type.LifeMessageUtil;
import shop.alien.util.type.LifeNoticeUtil;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 装修需求动态表 服务实现类
 *
 * @author auto-generated
 * @since 2025-01-15
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class StoreRenovationRequirementServiceImpl extends ServiceImpl<StoreRenovationRequirementMapper, StoreRenovationRequirement> implements StoreRenovationRequirementService {

    private final StoreInfoMapper storeInfoMapper;

    private final LifeMessageMapper lifeMessageMapper;

    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;

    private final LifeMessageUtil lifeMessageUtil;

    private final WebSocketProcess webSocketProcess;

    private final StoreUserMapper storeUserMapper;

    private final AiContentModerationUtil aiContentModerationUtil;
    // 供 CommonRatingServiceImpl 等复用的 URL 分类；本服务保存需求时不再对图/视频做审核
    // 定义图片后缀常量（不可修改，保证线程安全）
    private static final Set<String> IMAGE_SUFFIXES = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList(".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"))
    );

    // 定义视频后缀常量
    private static final Set<String> VIDEO_SUFFIXES = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList(".mp4", ".avi", ".mov", ".flv", ".mkv", ".wmv", ".mpeg"))
    );

    @Override
    public boolean saveOrUpdateRequirement(StoreRenovationRequirementDto dto) {
        log.info("StoreRenovationRequirementServiceImpl.saveOrUpdateRequirement?dto={}", dto);
        try {
            StoreRenovationRequirement requirement = new StoreRenovationRequirement();
            BeanUtils.copyProperties(dto, requirement);

            // 处理附件URL列表：List转逗号拼接字符串
            if (dto.getAttachmentUrls() != null && !dto.getAttachmentUrls().isEmpty()) {
                String attachmentUrlsStr = String.join(",", dto.getAttachmentUrls());
                requirement.setAttachmentUrls(attachmentUrlsStr);
            }

            // 获取当前登录用户ID
            Integer currentUserId = null;
            try {
                com.alibaba.fastjson.JSONObject userInfo = JwtUtil.getCurrentUserInfo();
                if (userInfo != null) {
                    currentUserId = userInfo.getInteger("userId");
                }
            } catch (Exception e) {
                log.warn("获取当前用户ID失败: {}", e.getMessage());
            }

            if (requirement.getId() == null) {
                // 新增
                requirement.setCreatedUserId(currentUserId);
                requirement.setCreatedTime(new Date());
                if (requirement.getStatus() == null) {
                    requirement.setStatus(0); // 默认草稿
                }
                if (requirement.getViewCount() == null) {
                    requirement.setViewCount(0);
                }
                if (requirement.getInquiryCount() == null) {
                    requirement.setInquiryCount(0);
                }
                if (requirement.getAuditStatus() == null) {
                    requirement.setAuditStatus(0); // 默认待审核
                }
            } else {
                // 更新
                requirement.setUpdatedUserId(currentUserId);
                requirement.setUpdatedTime(new Date());
            }
            StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>().eq(StoreUser::getStoreId, dto.getStoreId()).eq(StoreUser::getDeleteFlag, 0));

            LifeNotice lifeMessage = new LifeNotice();
            lifeMessage.setReceiverId("store_" + storeUser.getPhone());
            String text = "您发布的装修动态已提交审核，请于1-3个工作日进行查看";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", text);
            lifeMessage.setContext(jsonObject.toJSONString());
            lifeMessage.setTitle("审核通知");
            lifeMessage.setSenderId("system");
            lifeMessage.setIsRead(0);
            lifeMessage.setNoticeType(1);
            lifeNoticeUtil.fillUserTypeAndRefId(lifeMessage);
            lifeNoticeMapper.insert(lifeMessage);

            WebSocketVo websocketVo = new WebSocketVo();
            websocketVo.setSenderId("system");
            websocketVo.setReceiverId("store_" + storeUser.getPhone());
            websocketVo.setCategory("notice");
            websocketVo.setNoticeType("1");
            websocketVo.setIsRead(0);
            websocketVo.setText(JSONObject.from(lifeMessage).toJSONString());
            webSocketProcess.sendMessage("store_" + storeUser.getPhone(), JSONObject.from(websocketVo).toJSONString());

            // 仅审核 detailedRequirement 文本；无文字则整体直接审核通过；附件原样存 attachment_urls
            if (!StringUtils.hasText(requirement.getDetailedRequirement())) {
                requirement.setAuditStatus(1);
                requirement.setAuditReason(null);
                if (storeUser != null && storeUser.getPhone() != null) {
                    sendAuditNotification(storeUser.getPhone(), 1, null);
                }
            } else {
                AiContentModerationUtil.AuditResult auditResult = aiContentModerationUtil.auditContent(requirement.getDetailedRequirement(), null);
                if (!auditResult.isPassed()) {
                    requirement.setAuditStatus(2);
                    requirement.setAuditReason(auditResult.getFailureReason());
                    if (storeUser != null && storeUser.getPhone() != null) {
                        sendAuditNotification(storeUser.getPhone(), 2, auditResult.getFailureReason());
                    }
                } else {
                    requirement.setAuditStatus(1);
                    requirement.setAuditReason(null);
                    if (storeUser != null && storeUser.getPhone() != null) {
                        sendAuditNotification(storeUser.getPhone(), 1, null);
                    }
                }
            }
            requirement.setAuditTime(new Date());
            boolean isSuccess  = this.saveOrUpdate(requirement);

            return isSuccess;
        } catch (Exception e) {
            log.error("保存装修需求失败: {}", e.getMessage(), e);
            throw new RuntimeException("保存装修需求失败: " + e.getMessage());
        }
    }

    /**
     * 对URL列表进行分类（图片/视频/其他）
     * @param attachmentUrls 原始URL列表
     * @return 分类后的Map
     */
    public static Map<String, List<String>> classifyUrls(List<String> attachmentUrls) {
        // 初始化分类容器
        List<String> imageUrls = new ArrayList<>();
        List<String> videoUrls = new ArrayList<>();
        List<String> otherUrls = new ArrayList<>();

        if (Objects.isNull(attachmentUrls) || attachmentUrls.isEmpty()) {
            return buildResultMap(imageUrls, videoUrls, otherUrls);
        }

        for (String url : attachmentUrls) {
            // 空URL直接归为其他
            if (url == null || url.trim().isEmpty()) {
                otherUrls.add(url);
                continue;
            }

            String lowerUrl = url.toLowerCase().trim();
            // 优先判断图片（避免URL中同时包含图片+视频后缀的极端情况）
            boolean isImage = IMAGE_SUFFIXES.stream().anyMatch(lowerUrl::contains);
            if (isImage) {
                imageUrls.add(url); // 保留原始URL，而非小写后的
                continue;
            }

            // 判断是否为视频
            boolean isVideo = VIDEO_SUFFIXES.stream().anyMatch(lowerUrl::contains);
            if (isVideo) {
                videoUrls.add(url);
            } else {
                otherUrls.add(url);
            }
        }

        return buildResultMap(imageUrls, videoUrls, otherUrls);
    }

    /**
     * 构建分类结果Map
     */
    public static Map<String, List<String>> buildResultMap(List<String> imageUrls, List<String> videoUrls, List<String> otherUrls) {
        Map<String, List<String>> resultMap = new HashMap<>(3);
        resultMap.put("image", Collections.unmodifiableList(imageUrls)); // 返回不可修改列表，避免外部篡改
        resultMap.put("video", Collections.unmodifiableList(videoUrls));
        resultMap.put("other", Collections.unmodifiableList(otherUrls));
        return resultMap;
    }

    /**
     * 发送文本审核结果通知（图/视频不参与审核，仅与需求一并保存）
     */
    private void sendAuditNotification(String storePhone, Integer auditStatus, String auditReason) {
        try {
            if (storePhone == null || storePhone.trim().isEmpty()) {
                log.warn("发送审核通知失败，商铺电话为空");
                return;
            }

            String title = "审核通知";
            String message;
            if (auditStatus == 1) {
                message = "您发布的装修需求已通过审核,平台已将此需求发布,有意向的装修公司会与您联系";
            } else {
                message = "您发布的装修需求未通过审核.驳回原因:" + (auditReason != null ? auditReason : "") + "请您重新发布.";
            }

            LifeNotice lifeNotice = new LifeNotice();
            lifeNotice.setReceiverId("store_" + storePhone);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", message);
            lifeNotice.setContext(jsonObject.toJSONString());
            lifeNotice.setTitle(title);
            lifeNotice.setSenderId("system");
            lifeNotice.setIsRead(0);
            lifeNotice.setNoticeType(1);
            lifeNoticeUtil.fillUserTypeAndRefId(lifeNotice);
            lifeNoticeMapper.insert(lifeNotice);

            WebSocketVo websocketVo = new WebSocketVo();
            websocketVo.setSenderId("system");
            websocketVo.setReceiverId("store_" + storePhone);
            websocketVo.setCategory("notice");
            websocketVo.setNoticeType("1");
            websocketVo.setIsRead(0);
            websocketVo.setText(JSONObject.from(lifeNotice).toJSONString());
            webSocketProcess.sendMessage("store_" + storePhone, JSONObject.from(websocketVo).toJSONString());

            log.info("审核通知发送成功，商铺电话：{}，审核状态：{}", storePhone, auditStatus);
        } catch (Exception e) {
            log.error("发送审核通知异常，商铺电话：{}，审核状态：{}", storePhone, auditStatus, e);
        }
    }


    @Override
    public StoreRenovationRequirementDto getRequirementDetail(Integer id) {
        log.info("StoreRenovationRequirementServiceImpl.getRequirementDetail?id={}", id);
        StoreRenovationRequirement requirement = this.getById(id);
        if (requirement == null) {
            return null;
        }

        StoreRenovationRequirementDto dto = new StoreRenovationRequirementDto();
        BeanUtils.copyProperties(requirement, dto);

        // 处理附件URL字符串：逗号拼接转List
        if (StringUtils.hasText(requirement.getAttachmentUrls())) {
            List<String> attachmentUrls = Arrays.asList(requirement.getAttachmentUrls().split(","));
            dto.setAttachmentUrls(attachmentUrls);
        } else {
            dto.setAttachmentUrls(new ArrayList<>());
        }

        // 填充商铺信息和商户头像
        if (requirement.getStoreId() != null) {
            // 查询商铺信息
            StoreInfo storeInfo = storeInfoMapper.selectById(requirement.getStoreId());
            if (storeInfo != null) {
                dto.setStoreName(storeInfo.getStoreName());
                dto.setStoreTel(storeInfo.getStoreTel());
                dto.setStoreAddress(storeInfo.getStoreAddress());
                dto.setStoreBlurb(storeInfo.getStoreBlurb());
            }

            // 查询商户头像（从store_user表获取head_img）
            StoreUser storeUser = storeUserMapper.selectOne(new LambdaQueryWrapper<StoreUser>()
                    .eq(StoreUser::getStoreId, requirement.getStoreId())
                    .eq(StoreUser::getDeleteFlag, 0));
            if (storeUser != null && StringUtils.hasText(storeUser.getHeadImg())) {
                dto.setStoreAvatar(storeUser.getHeadImg());
            }
        }

        return dto;
    }

    @Override
    public IPage<StoreRenovationRequirementDto> getRequirementPage(Page<StoreRenovationRequirementDto> page,
                                                                     Integer storeId,
                                                                     String city,
                                                                     Integer renovationType,
                                                                     Integer status,
                                                                     Integer auditStatus,
                                                                     Integer sortType,
                                                                     String requirementTitle,
                                                                     String startTime,
                                                                     String endTime,
                                                                     Boolean hasCommunicated) {
        log.info("StoreRenovationRequirementServiceImpl.getRequirementPage?storeId={}, city={}, renovationType={}, status={}, auditStatus={}, sortType={}, requirementTitle={}, startTime={}, endTime={}, hasCommunicated={}",
                storeId, city, renovationType, status, auditStatus, sortType, requirementTitle, startTime, endTime, hasCommunicated);

        LambdaQueryWrapper<StoreRenovationRequirement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreRenovationRequirement::getDeleteFlag, 0);

        if (storeId != null) {
            wrapper.eq(StoreRenovationRequirement::getStoreId, storeId);
        }
        if (StringUtils.hasText(city)) {
            wrapper.eq(StoreRenovationRequirement::getCity, city);
        }
        if (renovationType != null) {
            wrapper.eq(StoreRenovationRequirement::getRenovationType, renovationType);
        }
        if (status != null) {
            wrapper.eq(StoreRenovationRequirement::getStatus, status);
        }
        if (auditStatus != null) {
            wrapper.eq(StoreRenovationRequirement::getAuditStatus, auditStatus);
        }
        // 标题模糊查询
        if (StringUtils.hasText(requirementTitle)) {
            wrapper.like(StoreRenovationRequirement::getRequirementTitle, requirementTitle);
        }
        // 时间段查询（根据创建时间）
        if (StringUtils.hasText(startTime)) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date startDate = sdf.parse(startTime);
                wrapper.ge(StoreRenovationRequirement::getCreatedTime, startDate);
            } catch (Exception e) {
                log.error("解析开始时间失败: startTime={}, error={}", startTime, e.getMessage());
            }
        }
        if (StringUtils.hasText(endTime)) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date endDate = sdf.parse(endTime);
                // 结束时间需要包含当天的23:59:59，所以加一天再减1毫秒
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endDate);
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                calendar.add(Calendar.MILLISECOND, -1);
                wrapper.le(StoreRenovationRequirement::getCreatedTime, calendar.getTime());
            } catch (Exception e) {
                log.error("解析结束时间失败: endTime={}, error={}", endTime, e.getMessage());
            }
        }

        // 排序处理：1-最新发布, 2-价格最高, 3-面积最大
        if (sortType == null || sortType == 1) {
            // 默认：最新发布（按创建时间降序）
            wrapper.orderByDesc(StoreRenovationRequirement::getCreatedTime);
        } else if (sortType == 2) {
            // 价格最高（按装修预算降序）
            wrapper.orderByDesc(StoreRenovationRequirement::getRenovationBudget);
            wrapper.orderByDesc(StoreRenovationRequirement::getCreatedTime); // 价格相同则按时间排序
        } else if (sortType == 3) {
            // 面积最大（按房屋面积降序）
            wrapper.orderByDesc(StoreRenovationRequirement::getHouseArea);
            wrapper.orderByDesc(StoreRenovationRequirement::getCreatedTime); // 面积相同则按时间排序
        } else {
            // 无效的排序类型，使用默认排序
            wrapper.orderByDesc(StoreRenovationRequirement::getCreatedTime);
        }

        // 如果传入了 hasCommunicated 参数，需要先查询所有数据（不分页），计算沟通状态后再过滤和分页
        IPage<StoreRenovationRequirement> requirementPage;
        List<StoreRenovationRequirement> requirementList;
        if (hasCommunicated != null) {
            // 查询所有符合条件的数据（不分页）
            requirementList = this.list(wrapper);
            requirementPage = new Page<>(page.getCurrent(), page.getSize());
            requirementPage.setTotal(requirementList.size());
            requirementPage.setRecords(new ArrayList<>());
        } else {
            // 正常分页查询
            requirementPage = this.page(new Page<>(page.getCurrent(), page.getSize()), wrapper);
            requirementList = requirementPage.getRecords();
        }
        
        List<StoreRenovationRequirementDto> dtoList = requirementList.stream().map(requirement -> {
            StoreRenovationRequirementDto dto = new StoreRenovationRequirementDto();
            BeanUtils.copyProperties(requirement, dto);

            // 处理附件URL字符串：逗号拼接转List
            if (StringUtils.hasText(requirement.getAttachmentUrls())) {
                List<String> attachmentUrls = Arrays.asList(requirement.getAttachmentUrls().split(","));
                dto.setAttachmentUrls(attachmentUrls);
            } else {
                dto.setAttachmentUrls(new ArrayList<>());
            }

            return dto;
        }).collect(Collectors.toList());
        
        // 创建分页对象
        IPage<StoreRenovationRequirementDto> dtoPage = new Page<>(page.getCurrent(), page.getSize());
        dtoPage.setRecords(dtoList);
        dtoPage.setTotal(hasCommunicated != null ? dtoList.size() : requirementPage.getTotal());

        // 批量查询商铺信息并填充到DTO
        if (dtoPage.getRecords() != null && !dtoPage.getRecords().isEmpty()) {
            // 收集所有的门店ID
            List<Integer> storeIds = dtoPage.getRecords().stream()
                    .map(StoreRenovationRequirementDto::getStoreId)
                    .filter(id -> id != null)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询商铺信息
            if (!storeIds.isEmpty()) {
                List<StoreInfo> storeInfoList = storeInfoMapper.selectBatchIds(storeIds);
                // 转换为Map，key为storeId，value为StoreInfo
                Map<Integer, StoreInfo> storeInfoMap = storeInfoList.stream()
                        .collect(Collectors.toMap(StoreInfo::getId, storeInfo -> storeInfo, (v1, v2) -> v1));

                // 批量查询商户头像（store_user.head_img）
                LambdaQueryWrapper<StoreUser> userWrapper = new LambdaQueryWrapper<StoreUser>()
                        .in(StoreUser::getStoreId, storeIds)
                        .eq(StoreUser::getDeleteFlag, 0);
                List<StoreUser> storeUserList = storeUserMapper.selectList(userWrapper);
                Map<Integer, String> storeAvatarMap = storeUserList.stream()
                        .filter(u -> u.getStoreId() != null && u.getHeadImg() != null)
                        .collect(Collectors.toMap(StoreUser::getStoreId, StoreUser::getHeadImg, (v1, v2) -> v1));

                // 填充商铺信息（含头像）到DTO
                dtoPage.getRecords().forEach(dto -> {
                    StoreInfo storeInfo = storeInfoMap.get(dto.getStoreId());
                    if (storeInfo != null) {
                        dto.setStoreName(storeInfo.getStoreName());
                        dto.setStoreTel(storeInfo.getStoreTel());
                        dto.setStoreAddress(storeInfo.getStoreAddress());
                        dto.setStoreBlurb(storeInfo.getStoreBlurb());
                    }
                    dto.setStoreAvatar(storeAvatarMap.get(dto.getStoreId()));
                });
            }

            // 检查是否已与发布商铺发生沟通
            String currentUserPhone = null;
            try {
                com.alibaba.fastjson.JSONObject userInfo = JwtUtil.getCurrentUserInfo();
                if (userInfo != null) {
                    currentUserPhone = userInfo.getString("phone");
                }
            } catch (Exception e) {
                log.debug("获取当前用户手机号失败（用户可能未登录）: {}", e.getMessage());
            }

            if (currentUserPhone != null && StringUtils.hasText(currentUserPhone)) {
                String currentUserPhoneId = "store_" + currentUserPhone;

                // 批量查询沟通状态（优化：使用Map缓存结果，避免重复查询）
                Map<String, Boolean> communicationStatusMap = new HashMap<>();

                dtoPage.getRecords().forEach(dto -> {
                    String storeTel = dto.getStoreTel();
                    if (storeTel != null && StringUtils.hasText(storeTel)) {
                        String publishingShopPhoneId = "store_" + storeTel;

                        // 检查是否已查询过该商铺的沟通状态
                        String communicationKey = currentUserPhoneId + "_" + publishingShopPhoneId;
                        Boolean communicated = communicationStatusMap.get(communicationKey);

                        if (communicated == null) {
                            // 判断互相都发送过消息才算沟通过
                            // 检查 currentUserPhoneId 是否给 publishingShopPhoneId 发送过消息
                            LambdaQueryWrapper<LifeMessage> messageWrapper1 = new LambdaQueryWrapper<>();
                            messageWrapper1.eq(LifeMessage::getDeleteFlag, 0);
                            lifeMessageUtil.applySenderReceiverPairQuery(messageWrapper1, currentUserPhoneId, publishingShopPhoneId);
                            Integer messageCount1 = lifeMessageMapper.selectCount(messageWrapper1);
                            boolean hasSentMessage1 = messageCount1 != null && messageCount1 > 0;

                            LambdaQueryWrapper<LifeMessage> messageWrapper2 = new LambdaQueryWrapper<>();
                            messageWrapper2.eq(LifeMessage::getDeleteFlag, 0);
                            lifeMessageUtil.applySenderReceiverPairQuery(messageWrapper2, publishingShopPhoneId, currentUserPhoneId);
                            Integer messageCount2 = lifeMessageMapper.selectCount(messageWrapper2);
                            boolean hasSentMessage2 = messageCount2 != null && messageCount2 > 0;

                            // 只有双方都发送过消息才算沟通过
                            communicated = hasSentMessage1 && hasSentMessage2;
                            communicationStatusMap.put(communicationKey, communicated);
                        }

                        dto.setHasCommunicated(communicated);
                    } else {
                        dto.setHasCommunicated(false);
                    }
                });
            } else {
                // 用户未登录，所有记录都设为未沟通
                dtoPage.getRecords().forEach(dto -> dto.setHasCommunicated(false));
            }
        }

        // 如果传入了 hasCommunicated 参数，根据沟通状态进行过滤
        if (hasCommunicated != null) {
            List<StoreRenovationRequirementDto> filteredList = dtoPage.getRecords().stream()
                    .filter(dto -> hasCommunicated.equals(dto.getHasCommunicated()))
                    .collect(Collectors.toList());
            
            // 更新总数
            dtoPage.setTotal(filteredList.size());
            
            // 手动分页
            int current = (int) page.getCurrent();
            int size = (int) page.getSize();
            int start = (current - 1) * size;
            int end = Math.min(start + size, filteredList.size());
            
            if (start < filteredList.size()) {
                dtoPage.setRecords(filteredList.subList(start, end));
            } else {
                dtoPage.setRecords(new ArrayList<>());
            }
        }

        return dtoPage;
    }

    @Override
    public void incrementViewCount(Integer id) {
        log.info("StoreRenovationRequirementServiceImpl.incrementViewCount?id={}", id);
        LambdaUpdateWrapper<StoreRenovationRequirement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StoreRenovationRequirement::getId, id);
        wrapper.setSql("view_count = view_count + 1");
        this.update(wrapper);
    }

    @Override
    public void incrementInquiryCount(Integer id) {
        log.info("StoreRenovationRequirementServiceImpl.incrementInquiryCount?id={}", id);
        LambdaUpdateWrapper<StoreRenovationRequirement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StoreRenovationRequirement::getId, id);
        wrapper.setSql("inquiry_count = inquiry_count + 1");
        this.update(wrapper);
    }

    @Override
    public boolean updateStatus(Integer id, Integer status) {
        log.info("StoreRenovationRequirementServiceImpl.updateStatus?id={}, status={}", id, status);
        LambdaUpdateWrapper<StoreRenovationRequirement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StoreRenovationRequirement::getId, id);
        wrapper.set(StoreRenovationRequirement::getStatus, status);
        wrapper.set(StoreRenovationRequirement::getUpdatedTime, new Date());

        try {
            com.alibaba.fastjson.JSONObject userInfo = JwtUtil.getCurrentUserInfo();
            if (userInfo != null) {
                wrapper.set(StoreRenovationRequirement::getUpdatedUserId, userInfo.getInteger("userId"));
            }
        } catch (Exception e) {
            log.warn("获取当前用户ID失败: {}", e.getMessage());
        }

        return this.update(wrapper);
    }

    @Override
    public boolean auditRequirement(Integer id, Integer auditStatus, String auditReason, Integer auditUserId) {
        log.info("StoreRenovationRequirementServiceImpl.auditRequirement?id={}, auditStatus={}, auditReason={}, auditUserId={}",
                id, auditStatus, auditReason, auditUserId);

        if (auditStatus == 2 && !StringUtils.hasText(auditReason)) {
            throw new RuntimeException("审核失败时必须填写审核原因");
        }

        LambdaUpdateWrapper<StoreRenovationRequirement> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(StoreRenovationRequirement::getId, id);
        wrapper.set(StoreRenovationRequirement::getAuditStatus, auditStatus);
        wrapper.set(StoreRenovationRequirement::getAuditTime, new Date());
        wrapper.set(StoreRenovationRequirement::getAuditUserId, auditUserId);
        wrapper.set(StoreRenovationRequirement::getUpdatedTime, new Date());

        if (auditStatus == 2) {
            wrapper.set(StoreRenovationRequirement::getAuditReason, auditReason);
        } else {
            wrapper.set(StoreRenovationRequirement::getAuditReason, null);
        }

        return this.update(wrapper);
    }

    @Override
    public boolean deleteRequirement(Integer id) {
        log.info("StoreRenovationRequirementServiceImpl.deleteRequirement?id={}", id);
        return this.removeById(id);
    }

    @Override
    public List<StoreRenovationRequirementDto> getRequirementListByStoreId(Integer storeId) {
        log.info("StoreRenovationRequirementServiceImpl.getRequirementListByStoreId?storeId={}", storeId);
        LambdaQueryWrapper<StoreRenovationRequirement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreRenovationRequirement::getStoreId, storeId);
        wrapper.eq(StoreRenovationRequirement::getDeleteFlag, 0);
        wrapper.orderByDesc(StoreRenovationRequirement::getCreatedTime);

        List<StoreRenovationRequirement> requirements = this.list(wrapper);

        return requirements.stream().map(requirement -> {
            StoreRenovationRequirementDto dto = new StoreRenovationRequirementDto();
            BeanUtils.copyProperties(requirement, dto);

            // 处理附件URL字符串：逗号拼接转List
            if (StringUtils.hasText(requirement.getAttachmentUrls())) {
                List<String> attachmentUrls = Arrays.asList(requirement.getAttachmentUrls().split(","));
                dto.setAttachmentUrls(attachmentUrls);
            } else {
                dto.setAttachmentUrls(new ArrayList<>());
            }

            return dto;
        }).collect(Collectors.toList());
    }
}

