package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.entity.CaseImage;
import com.zhentao.entity.CaseTimeline;
import com.zhentao.entity.SuccessCase;
import com.zhentao.mapper.CaseImageMapper;
import com.zhentao.mapper.CaseTimelineMapper;
import com.zhentao.mapper.SuccessCaseMapper;
import com.zhentao.service.SuccessCaseService;
import com.zhentao.vo.CaseImageVO;
import com.zhentao.vo.CaseTimelineVO;
import com.zhentao.vo.SuccessCaseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 成功案例服务实现类
 */
@Service
public class SuccessCaseServiceImpl implements SuccessCaseService {
    
    @Autowired
    private SuccessCaseMapper successCaseMapper;
    
    @Autowired
    private CaseTimelineMapper caseTimelineMapper;
    
    @Autowired
    private CaseImageMapper caseImageMapper;
    
    /**
     * 获取成功案例列表
     */
    @Override
    public List<SuccessCaseVO> getCaseList() {
        QueryWrapper<SuccessCase> queryWrapper = new QueryWrapper<>();
        
        // 只查询展示中的案例
        queryWrapper.eq("case_status", 1);
        
        // 按创建时间降序
        queryWrapper.orderByDesc("created_at");
        
        List<SuccessCase> caseList = successCaseMapper.selectList(queryWrapper);
        
        // 转换为VO
        return caseList.stream().map(this::convertToVO).collect(Collectors.toList());
    }
    
    /**
     * 获取成功案例详情
     */
    @Override
    public SuccessCaseVO getCaseDetail(String caseNo) {
        QueryWrapper<SuccessCase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_no", caseNo);
        queryWrapper.eq("case_status", 1);
        
        SuccessCase successCase = successCaseMapper.selectOne(queryWrapper);
        if (successCase == null) {
            return null;
        }
        
        SuccessCaseVO vo = convertToVO(successCase);
        
        // 查询图片列表
        List<CaseImage> images = caseImageMapper.selectByCaseId(successCase.getCaseId());
        if (images != null && !images.isEmpty()) {
            List<CaseImageVO> imageVOList = images.stream().map(img -> {
                CaseImageVO imageVO = new CaseImageVO();
                BeanUtils.copyProperties(img, imageVO);
                return imageVO;
            }).collect(Collectors.toList());
            vo.setImages(imageVOList);
        }
        
        // 查询时间线
        List<CaseTimeline> timelines = caseTimelineMapper.selectByCaseId(successCase.getCaseId());
        if (timelines != null && !timelines.isEmpty()) {
            List<CaseTimelineVO> timelineVOList = timelines.stream().map(timeline -> {
                CaseTimelineVO timelineVO = new CaseTimelineVO();
                timelineVO.setTimelineId(timeline.getTimelineId());
                timelineVO.setEventDate(timeline.getTimelineDate());
                timelineVO.setEventDescription(timeline.getTimelineTitle());
                timelineVO.setEventDetail(timeline.getTimelineDesc());
                timelineVO.setSortOrder(timeline.getSortOrder());
                
                // 查询时间线的图片
                List<CaseImage> timelineImages = caseImageMapper.selectByTimelineId(timeline.getTimelineId());
                if (timelineImages != null && !timelineImages.isEmpty()) {
                    List<CaseImageVO> timelineImageVOList = timelineImages.stream().map(img -> {
                        CaseImageVO imageVO = new CaseImageVO();
                        BeanUtils.copyProperties(img, imageVO);
                        return imageVO;
                    }).collect(Collectors.toList());
                    timelineVO.setImages(timelineImageVOList);
                }
                
                return timelineVO;
            }).collect(Collectors.toList());
            vo.setTimeline(timelineVOList);
        }
        
        return vo;
    }
    
    /**
     * 获取案例时间线
     */
    @Override
    public List<CaseTimelineVO> getTimeline(String caseNo) {
        QueryWrapper<SuccessCase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("case_no", caseNo);
        
        SuccessCase successCase = successCaseMapper.selectOne(queryWrapper);
        if (successCase == null) {
            return new ArrayList<>();
        }
        
        List<CaseTimeline> timelines = caseTimelineMapper.selectByCaseId(successCase.getCaseId());
        
        return timelines.stream().map(timeline -> {
            CaseTimelineVO timelineVO = new CaseTimelineVO();
            timelineVO.setTimelineId(timeline.getTimelineId());
            timelineVO.setEventDate(timeline.getTimelineDate());
            timelineVO.setEventDescription(timeline.getTimelineTitle());
            timelineVO.setEventDetail(timeline.getTimelineDesc());
            timelineVO.setSortOrder(timeline.getSortOrder());
            
            // 查询时间线的图片
            List<CaseImage> timelineImages = caseImageMapper.selectByTimelineId(timeline.getTimelineId());
            if (timelineImages != null && !timelineImages.isEmpty()) {
                List<CaseImageVO> timelineImageVOList = timelineImages.stream().map(img -> {
                    CaseImageVO imageVO = new CaseImageVO();
                    BeanUtils.copyProperties(img, imageVO);
                    return imageVO;
                }).collect(Collectors.toList());
                timelineVO.setImages(timelineImageVOList);
            }
            
            return timelineVO;
        }).collect(Collectors.toList());
    }
    
    /**
     * 转换为VO对象
     */
    private SuccessCaseVO convertToVO(SuccessCase successCase) {
        SuccessCaseVO vo = new SuccessCaseVO();
        BeanUtils.copyProperties(successCase, vo);
        
        // 查询第一张图片作为封面
        List<CaseImage> images = caseImageMapper.selectByCaseId(successCase.getCaseId());
        if (images != null && !images.isEmpty()) {
            vo.setImageUrl(images.get(0).getImageUrl());
        }
        
        // 设置详情内容（根据案例编号）
        setDetailContent(vo, successCase.getCaseNo());
        
        return vo;
    }
    
    /**
     * 设置案例详情内容
     */
    private void setDetailContent(SuccessCaseVO vo, String caseNo) {
        switch (caseNo) {
            case "SC202501001":
                vo.setQuote("从第一次咖啡约会到领证，只用了90天");
                vo.setStory("张先生是一名IT工程师，李女士是幼儿园老师。两人都比较内向，通过平台红娘的精心安排，在一家安静的咖啡厅初次见面。虽然开始有些紧张，但聊起共同的兴趣爱好时，话匣子就打开了。他们都喜欢看书、听音乐，性格互补。经过几次约会，感情迅速升温，3个月后就领取了结婚证。");
                vo.setMarriageDate("2024-12-20");
                vo.setMatchmakerName("李红娘");
                break;
            case "SC202502001":
                vo.setQuote("感谢红娘的专业服务，让我们相遇相知");
                vo.setStory("王先生经营着一家小公司，赵女士是一名护士。两人都曾有过感情经历，对婚姻比较慎重。红娘老师耐心地为他们分析性格匹配度，安排了多次不同场景的约会。从正式的西餐厅到轻松的公园散步，两人在交往中逐渐发现对方的优点，最终走向婚姻的殿堂。");
                vo.setMarriageDate("2025-02-14");
                vo.setMatchmakerName("王月");
                break;
            case "SC202503001":
                vo.setQuote("在最美的年纪遇见最对的人");
                vo.setStory("刘先生和陈女士都是85后，事业有成但感情空白。通过平台的专业测评，发现两人在价值观、生活目标等方面高度契合。从第一次见面的心动到确定关系，再到见家长、订婚，每个步骤都走得很顺利。他们说，这就是命中注定的缘分。");
                vo.setMarriageDate("2024-12-25");
                vo.setMatchmakerName("李红娘");
                break;
            case "SC202504001":
                vo.setQuote("爱情来了，挡都挡不住");
                vo.setStory("周先生是个阳光大男孩，杨女士温柔贤淑。两人在平台组织的户外活动中相识，一起爬山、看日出，在大自然中培养感情。周先生的幽默风趣深深吸引了杨女士，而杨女士的温柔体贴也让周先生倍感温暖。新年第一天领证，寓意着新的开始。");
                vo.setMarriageDate("2025-01-01");
                vo.setMatchmakerName("张美丽");
                break;
            case "SC202505001":
                vo.setQuote("谢谢平台让我们找到彼此");
                vo.setStory("陈先生和周女士都喜欢孩子，有着共同的家庭观念。从六一儿童节认识到情人节领证，他们的爱情故事充满了仪式感。陈先生说，遇见她是我最大的幸运；周女士说，感谢平台让我们找到彼此，我们会珍惜这份来之不易的缘分。");
                vo.setMarriageDate("2025-02-14");
                vo.setMatchmakerName("王月");
                break;
            default:
                vo.setQuote("爱情的故事，从这里开始");
                vo.setStory("每一份真挚的爱情都有属于自己的美好故事，感谢您选择我们的平台，让我们一起见证更多幸福时刻的到来。");
                vo.setMatchmakerName("专业红娘");
                break;
        }
    }
    
    // ==================== 管理端方法实现 ====================
    
    /**
     * 【管理端】分页查询案例列表
     */
    @Override
    public Map<String, Object> getAdminCaseList(Integer page, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        
        // 使用MyBatis-Plus分页
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SuccessCase> pageParam = 
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, pageSize);
        
        QueryWrapper<SuccessCase> queryWrapper = new QueryWrapper<>();
        // 管理端查询所有案例（包括隐藏的）
        queryWrapper.orderByDesc("created_at");
        
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<SuccessCase> pageResult = 
            successCaseMapper.selectPage(pageParam, queryWrapper);
        
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("page", pageResult.getCurrent());
        result.put("pageSize", pageResult.getSize());
        
        return result;
    }
    
    /**
     * 【管理端】根据ID获取案例详情
     */
    @Override
    public SuccessCase getAdminCaseById(Integer caseId) {
        return successCaseMapper.selectById(caseId);
    }
    
    /**
     * 【管理端】创建案例
     */
    @Override
    public SuccessCase createCase(SuccessCase successCase) {
        // 生成案例编号
        if (successCase.getCaseNo() == null || successCase.getCaseNo().isEmpty()) {
            successCase.setCaseNo(generateCaseNo());
        }
        
        // 设置默认状态
        if (successCase.getCaseStatus() == null) {
            successCase.setCaseStatus(1);
        }
        
        // 保存到数据库
        successCaseMapper.insert(successCase);
        
        return successCase;
    }
    
    /**
     * 【管理端】更新案例
     */
    @Override
    public boolean updateCase(Integer caseId, SuccessCase successCase) {
        // 确保ID正确
        successCase.setCaseId(caseId);
        
        // 更新到数据库
        int rows = successCaseMapper.updateById(successCase);
        
        return rows > 0;
    }
    
    /**
     * 【管理端】删除案例
     */
    @Override
    public boolean deleteCase(Integer caseId) {
        // 删除案例（这将级联删除关联的图片和时间线）
        int rows = successCaseMapper.deleteById(caseId);
        
        return rows > 0;
    }
    
    /**
     * 生成案例编号
     */
    private String generateCaseNo() {
        // 格式：SC + 年月日 + 3位序号
        String dateStr = new java.text.SimpleDateFormat("yyyyMMdd").format(new java.util.Date());
        
        // 查询今天已有的案例数量
        QueryWrapper<SuccessCase> queryWrapper = new QueryWrapper<>();
        queryWrapper.likeRight("case_no", "SC" + dateStr);
        Long count = successCaseMapper.selectCount(queryWrapper);
        
        // 生成序号
        String sequence = String.format("%03d", count + 1);
        
        return "SC" + dateStr + sequence;
    }
}

