package shop.alien.lawyer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import shop.alien.entity.result.R;
import shop.alien.entity.store.*;
import shop.alien.entity.store.dto.LawyerUserDto;
import shop.alien.entity.store.excelVo.LawyerUserExcelVo;
import shop.alien.entity.store.vo.LawyerUserVo;
import shop.alien.lawyer.config.BaseRedisService;
import shop.alien.lawyer.service.LawyerLegalProblemScenarioService;
import shop.alien.lawyer.service.LawyerServiceAreaService;
import shop.alien.lawyer.service.LawyerUserSearchHistoryService;
import shop.alien.lawyer.service.LawyerUserService;
import shop.alien.mapper.*;
import shop.alien.util.common.ListToPage;
import shop.alien.util.excel.EasyExcelUtil;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 律师用户 服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Transactional
@Service
@RequiredArgsConstructor
public class LawyerUserServiceImpl extends ServiceImpl<LawyerUserMapper, LawyerUser> implements LawyerUserService {

    private final LawyerUserMapper lawyerUserMapper;
    private final LawyerServiceAreaService lawyerServiceAreaService;
    private final LawyerServiceAreaMapper lawyerServiceAreaMapper;
    private final LawyerUserSearchHistoryService userSearchHistoryService;
    private final LawyerLegalProblemScenarioService lawyerLegalProblemScenarioService;
    private final LawyerConsultationOrderMapper lawyerConsultationOrderMapper;
    private final LawFirmMapper lawFirmMapper;
    private final BaseRedisService baseRedisService;
    private final LawFirmPaymentMapper lawFirmPaymentmapper;
    private final OrderReviewMapper orderReviewMapper;

    @Override
    public R<IPage<LawyerUser>> getLawyerUserList(int pageNum, int pageSize, String name, String phone, Integer status) {
        log.info("LawyerUserServiceImpl.getLawyerUserList?pageNum={},pageSize={},name={},phone={},status={}", pageNum, pageSize, name, phone, status);
        Page<LawyerUser> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<LawyerUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerUser::getDeleteFlag, 0);
        if (StringUtils.hasText(name)) {
            queryWrapper.like(LawyerUser::getName, name);
        }
        if (StringUtils.hasText(phone)) {
            queryWrapper.eq(LawyerUser::getPhone, phone);
        }
        if (status != null) {
            queryWrapper.eq(LawyerUser::getStatus, status);
        }
        queryWrapper.orderByDesc(LawyerUser::getCreatedTime);
        IPage<LawyerUser> pageResult = this.page(page, queryWrapper);
        return R.data(pageResult);
    }

    @Override
    public R<LawyerUser> addLawyerUser(LawyerUser lawyerUser) {
        log.info("LawyerUserServiceImpl.addLawyerUser?lawyerUser={}", lawyerUser);
        boolean result = this.save(lawyerUser);
        if (result) {
            return R.data(lawyerUser);
        }
        return R.fail("新增失败");
    }

    @Override
    public R<LawyerUser> editLawyerUser(LawyerUser lawyerUser) {
        log.info("LawyerUserServiceImpl.editLawyerUser?lawyerUser={}", lawyerUser);
        boolean result = this.updateById(lawyerUser);
        if (result) {
            return R.data(lawyerUser);
        }
        return R.fail("修改失败");
    }

    @Override
    public R<Boolean> deleteLawyerUser(Integer id) {
        log.info("LawyerUserServiceImpl.deleteLawyerUser?id={}", id);
        boolean result = this.removeById(id);
        if (result) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }

    @Override
    public R<Map<String, Object>> getLawyerDetail(Integer lawyerId) {
        log.info("LawyerUserServiceImpl.getLawyerDetail?lawyerId={}", lawyerId);

        LawyerUser lawyer = this.getById(lawyerId);
        if (lawyer == null || lawyer.getDeleteFlag() == 1) {
            return R.fail("律师不存在");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("id", lawyer.getId());
        result.put("name", lawyer.getName());
        result.put("avatar", lawyer.getHeadImg() != null ? lawyer.getHeadImg() : "");
        result.put("intro", lawyer.getPersonalIntroduction() != null ? lawyer.getPersonalIntroduction() :
                (lawyer.getAccountBlurb() != null ? lawyer.getAccountBlurb() : "Ta还没有个人业务介绍"));
        result.put("field", lawyer.getSpecialtyFields() != null ? lawyer.getSpecialtyFields() : "");
        result.put("experience", lawyer.getPracticeYears() != null ? lawyer.getPracticeYears() : 0);
        // 通过firm_id查询律所名称
        String lawFirmName = "";
        if (lawyer.getFirmId() != null) {
            LawFirm lawFirm = lawFirmMapper.selectById(lawyer.getFirmId());
            if (lawFirm != null && (lawFirm.getDeleteFlag() == null || lawFirm.getDeleteFlag() == 0)) {
                lawFirmName = lawFirm.getFirmName() != null ? lawFirm.getFirmName() : "";
            }
        }
        result.put("lawFirm", lawFirmName);
        result.put("online", lawyer.getIsOnline() != null && lawyer.getIsOnline() == 1);
        result.put("price", lawyer.getConsultationFee() != null ? lawyer.getConsultationFee() / 100 : 0);

        // 获取服务标签
        QueryWrapper<LawyerServiceArea> tagQuery = new QueryWrapper<>();
        tagQuery.eq("lawyer_user_id", lawyer.getId())
                .eq("delete_flag", 0)
                .eq("status", 1)
                .orderByAsc("sort_order");
        List<LawyerServiceArea> serviceAreas = lawyerServiceAreaService.list(tagQuery);
        result.put("serviceTags", new ArrayList<>());  // TODO: 需要关联查询问题场景名称

        // 额外字段
        result.put("education", lawyer.getEducationBackground() != null ? lawyer.getEducationBackground() : "");
        result.put("credentials", new ArrayList<>());  // TODO: 需要查询资质证书
        result.put("caseCount", lawyer.getServiceCount() != null ? lawyer.getServiceCount() : 0);
        // 评分：服务评分已经是0-5分（保留一位小数），直接使用
        result.put("rating", lawyer.getServiceScore() != null ? lawyer.getServiceScore() : 0.0);
        result.put("reviewCount", lawyer.getGoodReviewCount() != null ?
                (lawyer.getGoodReviewCount() + (lawyer.getMediumReviewCount() != null ? lawyer.getMediumReviewCount() : 0) +
                        (lawyer.getBadReviewCount() != null ? lawyer.getBadReviewCount() : 0)) : 0);

        return R.data(result);
    }

    @Override
    public R<Map<Integer, Boolean>> getLawyerOnlineStatus(String lawyerIds) {
        log.info("LawyerUserServiceImpl.getLawyerOnlineStatus?lawyerIds={}", lawyerIds);

        String[] ids = lawyerIds.split(",");
        List<Integer> idList = Arrays.stream(ids)
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        if (idList.isEmpty()) {
            return R.data(new HashMap<>());
        }

        List<LawyerUser> lawyers = new ArrayList<>(this.listByIds(idList));
        Map<Integer, Boolean> result = new HashMap<>();
        for (LawyerUser lawyer : lawyers) {
            result.put(lawyer.getId(), lawyer.getIsOnline() != null && lawyer.getIsOnline() == 1);
        }

        return R.data(result);
    }

    @Override
    public R<IPage<LawyerUser>> getRecommendedLawyerList(int page, int pageSize, Integer categoryId, Integer lawyerId) {
        log.info("LawyerUserServiceImpl.getRecommendedLawyerList?page={},pageSize={},categoryId={},lawyerId={}",
                page, pageSize, categoryId, lawyerId);

        int pageNum = page > 0 ? page : 1;
        int pageSizeNum = pageSize > 0 ? pageSize : 10;

        // 构建查询条件
        QueryWrapper<LawyerUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag", 0)
                .eq("status", 1)
                .eq("order_receiving_status", 1);

        // 律师ID筛选
        if (lawyerId != null) {
            queryWrapper.eq("id", lawyerId);
        }

        // 分类筛选：通过律师服务领域关联表查询
        if (categoryId != null) {
            List<Integer> lawyerIds = getLawyerIdsByCategoryId(categoryId);
            if (lawyerIds.isEmpty()) {
                // 如果没有匹配的律师，返回空结果
                return R.data(new Page<>(pageNum, pageSizeNum));
            }
            queryWrapper.in("id", lawyerIds);
        }

        // 排序：优先推荐律师 -> 在线律师 -> 注册时间
        queryWrapper.orderByDesc("is_recommended")
                .orderByDesc("is_online")
                .orderByAsc("created_time");

        // 分页查询
        Page<LawyerUser> pageObj = new Page<>(pageNum, pageSizeNum);
        IPage<LawyerUser> pageResult = this.page(pageObj, queryWrapper);

        // 为每个律师设置关联的法律问题场景列表
        if (pageResult.getRecords() != null && !pageResult.getRecords().isEmpty()) {
            setLawyerScenarios(pageResult.getRecords());
            // 设置律师评价数
            setLawyerReviewCounts(pageResult.getRecords());
        }

        return R.data(pageResult);
    }

    /**
     * 根据分类ID获取律师ID列表
     */
    private List<Integer> getLawyerIdsByCategoryId(Integer categoryId) {
        QueryWrapper<LawyerServiceArea> areaQuery = new QueryWrapper<>();
        areaQuery.eq("problem_scenario_id", categoryId)
                .eq("delete_flag", 0)
                .eq("status", 1)
                .select("lawyer_user_id");
        List<LawyerServiceArea> serviceAreas = lawyerServiceAreaService.list(areaQuery);
        return serviceAreas.stream()
                .map(LawyerServiceArea::getLawyerUserId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * 为律师列表设置关联的法律问题场景
     */
    private void setLawyerScenarios(List<LawyerUser> lawyers) {
        List<Integer> lawyerIds = lawyers.stream()
                .map(LawyerUser::getId)
                .collect(Collectors.toList());

        // 批量查询律师服务领域关联
        QueryWrapper<LawyerServiceArea> areaQuery = new QueryWrapper<>();
        areaQuery.in("lawyer_user_id", lawyerIds)
                .eq("delete_flag", 0)
                .eq("status", 1)
                .orderByAsc("sort_order");
        List<LawyerServiceArea> serviceAreas = lawyerServiceAreaService.list(areaQuery);

        if (serviceAreas.isEmpty()) {
            // 如果没有服务领域关联，设置空列表
            lawyers.forEach(lawyer -> lawyer.setLawyerLegalProblemScenarioList(new ArrayList<>()));
            return;
        }

        // 获取所有关联的法律问题场景ID
        Set<Integer> scenarioIds = serviceAreas.stream()
                .map(LawyerServiceArea::getProblemScenarioId)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        // 批量查询法律问题场景
        Map<Integer, LawyerLegalProblemScenario> scenarioMap = getScenarioMap(scenarioIds);

        // 按律师ID分组服务领域（已按sort_order排序）
        Map<Integer, List<LawyerServiceArea>> lawyerAreaMap = serviceAreas.stream()
                .collect(Collectors.groupingBy(LawyerServiceArea::getLawyerUserId));

        // 为每个律师设置关联的法律问题场景列表
        lawyers.forEach(lawyer -> {
            List<LawyerLegalProblemScenario> scenarioList = lawyerAreaMap.getOrDefault(lawyer.getId(), Collections.emptyList())
                    .stream()
                    .map(area -> scenarioMap.get(area.getProblemScenarioId()))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            lawyer.setLawyerLegalProblemScenarioList(scenarioList);
        });
    }

    /**
     * 批量查询法律问题场景并转换为Map
     */
    private Map<Integer, LawyerLegalProblemScenario> getScenarioMap(Set<Integer> scenarioIds) {
        if (scenarioIds.isEmpty()) {
            return Collections.emptyMap();
        }
        List<LawyerLegalProblemScenario> scenarios = new ArrayList<>(lawyerLegalProblemScenarioService.listByIds(scenarioIds));
        return scenarios.stream()
                .filter(s -> s.getDeleteFlag() != null && s.getDeleteFlag() == 0)
                .collect(Collectors.toMap(LawyerLegalProblemScenario::getId, s -> s, (k1, k2) -> k1));
    }

    /**
     * 批量设置律师的评价数（只统计评价，不包含评论）
     *
     * @param lawyers 律师列表
     */
    private void setLawyerReviewCounts(List<LawyerUser> lawyers) {
        if (CollectionUtils.isEmpty(lawyers)) {
            return;
        }

        List<Integer> lawyerIds = lawyers.stream()
                .map(LawyerUser::getId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        if (lawyerIds.isEmpty()) {
            return;
        }

        try {
            // 批量查询每个律师的评价数
            LambdaQueryWrapper<OrderReview> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(OrderReview::getLawyerUserId, lawyerIds)
                    .eq(OrderReview::getDeleteFlag, 0)
                    .select(OrderReview::getLawyerUserId);
            List<OrderReview> reviews = orderReviewMapper.selectList(queryWrapper);

            // 按律师ID分组统计评价数
            Map<Integer, Long> reviewCountMap = reviews.stream()
                    .filter(r -> r.getLawyerUserId() != null)
                    .collect(Collectors.groupingBy(OrderReview::getLawyerUserId, Collectors.counting()));

            // 为每个律师设置评价数
            lawyers.forEach(lawyer -> {
                Long count = reviewCountMap.get(lawyer.getId());
                lawyer.setReviewCount(count != null ? count.intValue() : 0);
            });

            log.debug("批量设置律师评价数完成，律师数量={}", lawyers.size());
        } catch (Exception e) {
            log.error("批量设置律师评价数失败，错误信息={}", e.getMessage(), e);
            // 设置失败时，将所有律师的评价数设置为0
            lawyers.forEach(lawyer -> lawyer.setReviewCount(0));
        }
    }


    @Override
    public R<IPage<LawyerUser>> getRecommendedLawyersBySession(String sessionId, Integer messageId) {
        log.info("LawyerUserServiceImpl.getRecommendedLawyersBySession?sessionId={},messageId={}", sessionId, messageId);

        // TODO: 根据会话ID查询AI交互日志，获取关联的问题场景ID，然后推荐相关律师
        // 这里暂时返回推荐列表（可以复用上面的逻辑）
        return getRecommendedLawyerList(1, 10, null, null);
    }

    @Override
    public R<IPage<LawyerUser>> searchLawyerByName(String nickName, int page, int pageSize, Integer clientUserId) {
        log.info("LawyerUserServiceImpl.searchLawyerByName?nickName={},page={},pageSize={},clientUserId={}", nickName, page, pageSize, clientUserId);

        int pageNum = page > 0 ? page : 1;
        int pageSizeNum = pageSize > 0 ? pageSize : 10;

        // 构建查询条件
        QueryWrapper<LawyerUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag", 0)
                .eq("status", 1)
                .eq("order_receiving_status", 1);

        // 如果昵称不为空，添加昵称模糊查询条件
        if (nickName != null && !nickName.trim().isEmpty()) {
            queryWrapper.like("nick_name", nickName.trim());
        }

        // 排序：优先推荐律师 -> 在线律师 -> 注册时间
        queryWrapper.orderByDesc("is_recommended")
                .orderByDesc("is_online")
                .orderByAsc("created_time");

        // 分页查询
        Page<LawyerUser> pageObj = new Page<>(pageNum, pageSizeNum);
        IPage<LawyerUser> pageResult = this.page(pageObj, queryWrapper);

        // 如果提供了用户ID且昵称不为空，保存搜索历史（如果不存在则添加）
        if (clientUserId != null && nickName != null && !nickName.trim().isEmpty()) {
            try {
                String keyword = nickName.trim();
                // 检查是否已存在相同的搜索历史记录
                LambdaQueryWrapper<LawyerUserSearchHistory> checkWrapper = new LambdaQueryWrapper<>();
                checkWrapper.eq(LawyerUserSearchHistory::getClientUserId, clientUserId)
                        .eq(LawyerUserSearchHistory::getSearchKeyword, keyword)
                        .eq(LawyerUserSearchHistory::getSearchType, 0)  // 0:律师姓名
                        .eq(LawyerUserSearchHistory::getDeleteFlag, 0);
                long count = userSearchHistoryService.count(checkWrapper);

                // 如果不存在相同的记录，则添加
                if (count == 0) {
                    LawyerUserSearchHistory searchHistory = new LawyerUserSearchHistory();
                    searchHistory.setClientUserId(clientUserId);
                    searchHistory.setSearchKeyword(keyword);
                    searchHistory.setSearchType(0);  // 0:律师姓名
                    userSearchHistoryService.addUserSearchHistory(searchHistory);
                    log.info("保存搜索历史成功：用户ID={}, 关键词={}", clientUserId, keyword);
                } else {
                    log.debug("搜索历史已存在，跳过添加：用户ID={}, 关键词={}", clientUserId, keyword);
                }
            } catch (Exception e) {
                log.error("保存搜索历史失败：用户ID={}, 关键词={}, 错误={}", clientUserId, nickName, e.getMessage(), e);
                // 保存历史失败不影响查询结果返回
            }
        }

        // 为每个律师设置关联的法律问题场景列表
        if (pageResult.getRecords() != null && !pageResult.getRecords().isEmpty()) {
            setLawyerScenarios(pageResult.getRecords());
            // 设置律师评价数
            setLawyerReviewCounts(pageResult.getRecords());
        }

        return R.data(pageResult);
    }

    /**
     * 获取AI推荐律师列表
     *
     * @param page 页码
     *             pageSize 页大小
     *             categoryId 分类ID
     */
    @Override
    public R<IPage<LawyerUser>> getAiRecommendList(int page, int size, Integer categoryId) {
        log.info("LawyerUserController.aiRecommendList?page={},size={},categoryId={}",
                page, size, categoryId);

        // 构建查询条件
        QueryWrapper<LawyerUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_flag", 0)
                .eq("status", 1)
                .eq("order_receiving_status", 1);

        // 分类筛选：通过律师服务领域关联表查询
        if (categoryId != null) {
            List<Integer> lawyerIds = getLawyerIdsByCategoryId(categoryId);
            if (lawyerIds.isEmpty()) {
                // 如果没有匹配的律师，返回空结果
                return  getRecommendedLawyerList(1, 5, null, null);
            }
            queryWrapper.in("id", lawyerIds);
        }

        // 排序：优先推荐律师 -> 在线律师 -> 注册时间
        queryWrapper.orderByDesc("is_recommended")
                .orderByDesc("is_online")
                .orderByAsc("created_time");

        // 分页查询
        Page<LawyerUser> pageObj = new Page<>(page, size);
        IPage<LawyerUser> pageResult = this.page(pageObj, queryWrapper);

        // 为每个律师设置关联的法律问题场景列表
        if (pageResult.getRecords() != null && !pageResult.getRecords().isEmpty()) {
            setLawyerScenarios(pageResult.getRecords());
        }
        return R.data(pageResult);
    }

    /**
     * 注销律师用户
     * <p>
     * 注销前会进行以下校验：
     * 1. 参数校验：律师ID不能为空
     * 2. 律师存在性校验：律师必须存在
     * 3. 注销状态校验：已注销的律师不允许重复注销
     * 4. 设置注销相关字段：注销标记、注销时间、状态等
     * </p>
     *
     * @param id 律师ID
     * @return 注销结果，包含注销信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R<Map<String, Object>> logOutLawyerUser(Integer id) {
        log.info("开始注销律师用户，律师ID={}", id);

        Map<String, Object> resultMap = new HashMap<>();

        // 参数校验
        if (id == null) {
            log.warn("注销律师用户失败：律师ID为空");
            return R.fail("律师ID不能为空");
        }

        // 查询律师信息
        LawyerUser lawyerUser = this.getById(id);
        if (lawyerUser == null) {
            log.warn("注销律师用户失败：律师不存在，律师ID={}", id);
            return R.fail("律师不存在");
        }

        String key = "lawyer_" + lawyerUser.getPhone();
        String redisVerificationCode = baseRedisService.getString(key);
        //对redisVerificationCode进行校验，如果不是空的话清除redis中的记录
        if (redisVerificationCode != null) {
            baseRedisService.delete(key);
        }
        // 检查是否已经注销
        if (lawyerUser.getLogoutFlag() != null && lawyerUser.getLogoutFlag() == 1) {
            log.warn("注销律师用户失败：律师已注销，律师ID={}, 律师姓名={}", id, lawyerUser.getName());
            return R.fail("该律师账号已注销，无需重复注销");
        }

        // 检查是否已删除
        if (lawyerUser.getDeleteFlag() != null && lawyerUser.getDeleteFlag() == 1) {
            log.warn("注销律师用户失败：律师已删除，律师ID={}, 律师姓名={}", id, lawyerUser.getName());
            return R.fail("该律师账号已删除");
        }

        List<LawyerConsultationOrder> list=lawyerConsultationOrderMapper.selectOrder(null, id);


        if (!CollectionUtils.isEmpty( list)){
            // 提示前端有未完成订单 1：有未完成订单  0：无未完成订单
            resultMap.put("unfinishedOrder", 1);
        }

        if (lawyerUser.getOrderReceivingStatus() != null && lawyerUser.getOrderReceivingStatus() == 1){
            // 提示前端接单状态为接单中 1：接单中  0：未接单
            resultMap.put("orderReceivingStatus", 1);
        }

        if (CollectionUtils.isEmpty( list) && lawyerUser.getStatus() == 0){
            // 设置注销相关字段
            lawyerUser.setLogoutFlag(1); // 注销标记：1-已注销
            lawyerUser.setLogoutTime(new Date()); // 注销时间
            lawyerUser.setStatus(0); // 状态设置为禁用
            lawyerUser.setOrderReceivingStatus(0); // 接单状态设置为不接单
            lawyerUser.setIsOnline(0); // 在线状态设置为离线
            lawyerUser.setIsRecommended(0); // 推荐状态设置为不推荐
            lawyerUser.setIsOnline(0);
            lawyerUser.setDeleteFlag(1);
            lawyerUser.setLastOnlineTime(new Date());

            // 执行更新操作
            boolean result = this.updateById(lawyerUser);
            if (!result) {
                log.error("注销律师用户失败：更新数据库失败，律师ID={}", id);
                return R.fail("注销失败，请稍后重试");
            }

            log.info("注销律师用户成功，律师ID={}, 律师姓名={}, 注销时间={}",
                    id, lawyerUser.getName(), lawyerUser.getLogoutTime());

            // 构建返回结果
            resultMap.put("id", lawyerUser.getId());
            resultMap.put("name", lawyerUser.getName());
            resultMap.put("phone", lawyerUser.getPhone());
            resultMap.put("logoutFlag", lawyerUser.getLogoutFlag());
            resultMap.put("logoutTime", lawyerUser.getLogoutTime());
            resultMap.put("status", lawyerUser.getStatus());
            resultMap.put("message", "律师账号注销成功");
        }

        return R.data(resultMap);
    }

    @Override
    public R<LawyerUserVo> getLawyerInfo(Integer lawyerId) {
        log.info("LawyerUserServiceImpl.getLawyerInfo?lawyerId={}", lawyerId);

        // 参数校验
        if (lawyerId == null) {
            log.warn("查询律师信息失败：律师ID为空");
            return R.fail("律师ID不能为空");
        }

        // 查询律师信息
        LawyerUser lawyer = this.getById(lawyerId);
        if (lawyer == null) {
            log.warn("查询律师信息失败：律师不存在，律师ID={}", lawyerId);
            return R.fail("律师不存在");
        }

        // 检查是否已删除
        if (lawyer.getDeleteFlag() != null && lawyer.getDeleteFlag() == 1) {
            log.warn("查询律师信息失败：律师已删除，律师ID={}", lawyerId);
            return R.fail("律师信息已删除");
        }

        LawyerUserVo result=lawyerUserMapper.selectInfo(lawyerId);

        //把result中的数据problemScenarioId，scenarioNames 这两个数据放入到lawyerLegalProblemScenarioList中
        QueryWrapper<LawyerServiceArea> wrapper = new QueryWrapper<>();
        wrapper.in("lsa.lawyer_user_id", lawyerId)
                .eq("lsa.delete_flag", 0)
                .eq("lsa.status", 1);
        result.setLawyerLegalProblemScenarioList(lawyerServiceAreaMapper.getProblemScenario(wrapper));



        return R.data(result);
    }


    @Override
    public R<LawyerUserVo> updateLawyerUser(LawyerUserVo lawyerUserVo) {
        log.info("LawyerUserServiceImpl.updateLawyerUser?lawyerUserVo={}", lawyerUserVo);

        // 参数校验
        if (lawyerUserVo == null || lawyerUserVo.getId() == null) {
            log.warn("更新律师用户信息失败：参数为空或律师ID为空");
            return R.fail("律师ID不能为空");
        }
        LawyerUser lawyerUser = new LawyerUser();
        lawyerUser.setId(lawyerUserVo.getId());

        if (lawyerUserVo.getFirstLevelScenarioId() != null && !lawyerUserVo.getFirstLevelScenarioId().isEmpty()) {
            // 先将该律师的所有服务领域设置为逻辑删除
            UpdateWrapper<LawyerServiceArea> deleteWrapper = new UpdateWrapper<>();
            deleteWrapper.eq("lawyer_user_id", lawyerUserVo.getId())
                    .set("delete_flag", 1)
                    .set("updated_time", new Date());
            lawyerServiceAreaMapper.update(null, deleteWrapper);
            // 拆分场景ID并逐个处理
            String[] scenarioIds = lawyerUserVo.getFirstLevelScenarioId().split(",");
            for (String id : scenarioIds) {
                // 去除空格并验证ID有效性
                String trimmedId = id.trim();
                if (!trimmedId.isEmpty()) {
                    try {
                        LawyerServiceArea lawyerServiceArea = new LawyerServiceArea();
                        lawyerServiceArea.setLawyerUserId(lawyerUserVo.getId());
                        // 只设置当前循环的ID，而不是整个字符串
                        lawyerServiceArea.setProblemScenarioId(Integer.valueOf(trimmedId));
                        lawyerServiceArea.setCreatedTime(new Date());
                        lawyerServiceArea.setUpdatedTime(new Date());
                        lawyerServiceArea.setDeleteFlag(0);
                        lawyerServiceArea.setStatus(1);
                        int insertResult = lawyerServiceAreaMapper.insert(lawyerServiceArea);
                        if (insertResult <= 0) {
                            log.warn("更新律师用户信息失败：更新数据库失败，律师ID={}", lawyerUserVo.getId());
                            return R.fail("修改律师信息失败");
                        }
                    } catch (NumberFormatException e) {
                        log.warn("更新律师用户信息失败：场景ID格式错误，ID={}, 错误={}", trimmedId, e.getMessage());
                        return R.fail("修改律师信息失败：场景ID格式错误");
                    }
                }
            }

        }
        if (lawyerUserVo.getFirmId() != null) {
            lawyerUser.setFirmId(lawyerUserVo.getFirmId());
            lawyerUser.setLawFirm(lawyerUserVo.getFirmName());
            Integer result = lawyerUserMapper.updateLawyerUser(lawyerUser);
            if (result <= 0) {
                log.warn("更新律所信息失败：更新数据库失败，律师ID={}", lawyerUserVo.getId());
                return R.fail("修改律师信息失败");
            }
            //根据律师表中的firm_id进行修改账号和地址
            UpdateWrapper<LawFirmPayment> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("firm_id", lawyerUserVo.getFirmId())
                    .set("payment_account", lawyerUserVo.getPaymentNum()) // 假设有账号字段
                    .set("address", lawyerUserVo.getAddress()); // 假设有地址字段
            lawFirmPaymentmapper.update(null, updateWrapper);

        }

        boolean hasUpdate = false; // 标记是否有字段需要更新

        if (lawyerUserVo.getHeadImg() != null) {
            lawyerUser.setHeadImg(lawyerUserVo.getHeadImg());
            hasUpdate = true;
        }
        if (lawyerUserVo.getName() != null) {
            lawyerUser.setName(lawyerUserVo.getName());
            lawyerUser.setNickName(lawyerUserVo.getName().charAt(0)+"律师");
            hasUpdate = true;
        }
        if (lawyerUserVo.getPersonalIntroduction() != null) {
            lawyerUser.setPersonalIntroduction(lawyerUserVo.getPersonalIntroduction());
            hasUpdate = true;
        }
        if (lawyerUserVo.getPhone() != null) {
            lawyerUser.setPhone(lawyerUserVo.getPhone());
            hasUpdate = true;
        }
        if (lawyerUserVo.getOrderReceivingStatus() != null) {
            lawyerUser.setOrderReceivingStatus(lawyerUserVo.getOrderReceivingStatus());
            hasUpdate = true;
        }
        if (lawyerUserVo.getPracticeStartDate() != null) {
            lawyerUser.setPracticeStartDate(lawyerUserVo.getPracticeStartDate());
            hasUpdate = true;
        }
        if (lawyerUserVo.getCertificateImage() != null) {
            lawyerUser.setCertificateImage(lawyerUserVo.getCertificateImage());
            hasUpdate = true;
        }

// 只有当有字段需要更新时才执行更新操作
        if (hasUpdate) {

            Integer result = lawyerUserMapper.updateLawyerUser(lawyerUser);
            if (result <= 0) {
                log.warn("更新律师用户信息失败：更新数据库失败，律师ID={}", lawyerUserVo.getId());
                return R.fail("修改律师信息失败");
            }
        }


        // 查询更新后的律师信息
        LawyerUserVo res = lawyerUserMapper.selectInfo(lawyerUserVo.getId());
        return R.data(res);
    }

    @Override
    public R<LawyerUser> getLawyerInfoByPhone(String phone) {
        log.info("LawyerUserServiceImpl.getLawyerInfoByPhone?phone={}", phone);

        // 参数校验
        if (!StringUtils.hasText(phone)) {
            log.warn("查询律师信息失败：手机号为空");
            return R.fail("手机号不能为空");
        }

        // 构建查询条件
        LambdaQueryWrapper<LawyerUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LawyerUser::getPhone, phone)
                .eq(LawyerUser::getDeleteFlag, 0)
                .orderByDesc(LawyerUser::getCreatedTime)
                .last("LIMIT 1");

        // 查询律师信息
        LawyerUser lawyerUser = lawyerUserMapper.selectOne(queryWrapper);

        if (lawyerUser == null) {
            log.warn("查询律师信息失败：律师不存在，手机号={}", phone);
            return R.fail("律师不存在");
        }

        return R.data(lawyerUser);
    }

    @Override
    public R<IPage<LawyerUserVo>> getLawyerList(String name,
                                                String phone,
                                                Integer firmId,
                                                String startTime,
                                                String endTime,
                                                int page,
                                                int size) {
        log.info("LawyerUserServiceImpl.getLawyerList?name={},phone={},firmId={},startTime={},endTime={},page={},pageSize={}",
                name, phone, firmId, startTime, endTime, page, size);

        // 查询分页数据（在SQL层面使用LIMIT进行分页）
        List<LawyerUserVo> list = lawyerUserMapper.selectLawyerUserList(name, phone, firmId, startTime, endTime);
        if (list == null) {
            list = new ArrayList<>();
        }

        return R.data(ListToPage.setPage(list, page, size));
    }

    @Override
    public R<Boolean> isRecommended(Integer lawyerId, Integer isRecommended) {
        log.info("LawyerUserServiceImpl.isRecommended?lawyerId={},isRecommended={}", lawyerId, isRecommended);

        // 参数校验
        if (lawyerId == null) {
            log.warn("设置律师推荐状态失败：律师ID为空");
            return R.fail("律师ID不能为空");
        }

        if (isRecommended == null || (isRecommended != 0 && isRecommended != 1)) {
            log.warn("设置律师推荐状态失败：推荐状态参数无效，isRecommended={}", isRecommended);
            return R.fail("推荐状态参数无效，必须为0（取消推荐）或1（推荐）");
        }

        // 查询律师信息
        LawyerUser lawyerUser = this.getById(lawyerId);
        if (lawyerUser == null) {
            log.warn("设置律师推荐状态失败：律师不存在，律师ID={}", lawyerId);
            return R.fail("律师不存在");
        }

        // 更新推荐状态
        lawyerUser.setIsRecommended(isRecommended);
        boolean result = this.updateById(lawyerUser);
        if (result) {
            log.info("设置律师推荐状态成功：律师ID={},推荐状态={}", lawyerId, isRecommended);
            return R.success("设置成功");
        } else {
            log.warn("设置律师推荐状态失败：更新数据库失败，律师ID={},推荐状态={}", lawyerId, isRecommended);
            return R.fail("设置失败");
        }
    }

    @Override
    public void exportLawyerList(HttpServletResponse response,
                                 String name,
                                 String phone,
                                 Integer firmId,
                                 String startTime,
                                 String endTime,
                                 Integer pageNum,
                                 Integer pageSize) throws Exception {
        log.info("LawyerUserServiceImpl.exportLawyerList?name={},phone={},firmId={},startTime={},endTime={},pageNum={},pageSize={}",
                name, phone, firmId, startTime, endTime, pageNum, pageSize);

        // 如果pageNum为null或0，则导出全部数据（设置一个很大的pageSize）
        int page = (pageNum == null || pageNum == 0) ? 1 : pageNum;
        int size = (pageNum == null || pageNum == 0) ? Integer.MAX_VALUE : (pageSize == null ? 10 : pageSize);

        // 调用查询接口获取数据
        R<IPage<LawyerUserVo>> result = getLawyerList(name, phone, firmId, startTime, endTime, page, size);

        if (result == null || !result.isSuccess()) {
            log.warn("获取律师列表失败：{}", result != null ? result.getMsg() : "返回结果为空");
            throw new RuntimeException(result != null ? result.getMsg() : "获取数据失败，请稍后重试");
        }

        IPage<LawyerUserVo> pageResult = result.getData();
        if (pageResult == null || pageResult.getRecords() == null || pageResult.getRecords().isEmpty()) {
            log.warn("律师列表导出：无数据可导出");
            throw new IllegalArgumentException("暂无数据可导出");
        }

        List<LawyerUserVo> voList = pageResult.getRecords();
        log.info("律师列表导出：查询到{}条数据，导出{}条数据", pageResult.getTotal(), voList.size());

        // 转换为Excel VO
        List<LawyerUserExcelVo> excelVoList = convertToExcelVo(voList);

        // 使用EasyExcelUtil导出
        EasyExcelUtil.exportExcel(response, excelVoList, LawyerUserExcelVo.class, "中台律师列表", "中台律师列表");
    }

    @Override
    public R<LawyerUserVo> updateLawyerUserCharge(LawyerUserDto lawyerUserDto) {
        LawyerUser lawyerUser = new LawyerUser();
        lawyerUser.setId(lawyerUserDto.getId());
        lawyerUser.setChargeMinute(lawyerUserDto.getChargeMinute());
        lawyerUser.setMinuteNum(lawyerUserDto.getMinuteNum());
        lawyerUser.setChargeTime(lawyerUserDto.getChargeTime());
        lawyerUser.setTimeNum(lawyerUserDto.getTimeNum());
        this.updateById(lawyerUser);
        return R.success("修改成功");
    }

    /**
     * 将LawyerUserVo转换为LawyerUserExcelVo
     *
     * @param voList LawyerUserVo列表
     * @return LawyerUserExcelVo列表
     */
    private List<LawyerUserExcelVo> convertToExcelVo(List<LawyerUserVo> voList) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return voList.stream().map(vo -> {
            LawyerUserExcelVo excelVo = new LawyerUserExcelVo();
            excelVo.setId(vo.getId());
            excelVo.setName(vo.getName());
            excelVo.setPhone(vo.getPhone());
            excelVo.setFirmName(vo.getFirmName());
//            excelVo.setLawyerCertificateNo(vo.getLawyerCertificateNo());
//            excelVo.setPracticeYears(vo.getPracticeYears());
//            excelVo.setServiceScore(vo.getServiceScore());
//            excelVo.setServiceCount(vo.getServiceCount());
            excelVo.setFirmId(vo.getFirmId());

            // 转换执业开始日期
//            if (vo.getPracticeStartDate() != null) {
//                excelVo.setPracticeStartDate(dateFormat.format(vo.getPracticeStartDate()));
//            }
//
//            // 转换用户状态
//            if (vo.getStatus() != null) {
//                excelVo.setStatusValue(vo.getStatus());
//                excelVo.setStatus(vo.getStatus() == 1 ? "启用" : "禁用");
//            }

            // 转换资质认证状态
//            if (vo.getCertificationStatus() != null) {
//                excelVo.setCertificationStatusValue(vo.getCertificationStatus());
//                switch (vo.getCertificationStatus()) {
//                    case 0:
//                        excelVo.setCertificationStatus("未认证");
//                        break;
//                    case 1:
//                        excelVo.setCertificationStatus("认证中");
//                        break;
//                    case 2:
//                        excelVo.setCertificationStatus("已认证");
//                        break;
//                    case 3:
//                        excelVo.setCertificationStatus("认证失败");
//                        break;
//                    default:
//                        excelVo.setCertificationStatus("未知");
//                }
//            }

            // 转换是否推荐
            if (vo.getIsRecommended() != null) {
                excelVo.setIsRecommendedValue(vo.getIsRecommended());
                excelVo.setIsRecommended(vo.getIsRecommended() == 1 ? "推荐" : "不推荐");
            }

            // 转换法律场景
            if (vo.getScenarioNames() != null && !vo.getScenarioNames().isEmpty()) {
                excelVo.setScenarioNames(vo.getScenarioNames());
            } else {
                excelVo.setScenarioNames("");
            }

            // 转换接单状态
            if (vo.getOrderReceivingStatus() != null) {
                excelVo.setOrderReceivingStatusValue(vo.getOrderReceivingStatus());
                excelVo.setOrderReceivingStatus(vo.getOrderReceivingStatus() == 1 ? "接单中" : "不接单");
            } else {
                excelVo.setOrderReceivingStatus("未知");
            }

            // 设置收款账号
            if (vo.getPaymentNum() != null && !vo.getPaymentNum().isEmpty()) {
                excelVo.setPaymentNum(vo.getPaymentNum());
            } else {
                excelVo.setPaymentNum("");
            }

            // 转换创建时间
//            if (vo.getCreatedTime() != null) {
//                excelVo.setCreatedTimeValue(vo.getCreatedTime());
//                excelVo.setCreatedTime(dateTimeFormat.format(vo.getCreatedTime()));
//            }

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

