package com.fs.his.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.his.vo.AnswerVO;
import com.fs.his.vo.FsQuestionAndAnswerVO;
import com.fs.his.vo.OptionsVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.his.mapper.FsQuestionAndAnswerMapper;
import com.fs.his.domain.FsQuestionAndAnswer;
import com.fs.his.service.IFsQuestionAndAnswerService;
import org.springframework.util.CollectionUtils;

/**
 * 问答Service业务层处理
 * 
 * @author fs
 * @date 2025-09-29
 */
@Slf4j
@Service
public class FsQuestionAndAnswerServiceImpl extends ServiceImpl<FsQuestionAndAnswerMapper, FsQuestionAndAnswer> implements IFsQuestionAndAnswerService {


    @Autowired
    private FsQuestionAndAnswerMapper fsQuestionAndAnswerMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 问答模板缓存key前缀
     * 格式：fs:question:template:{id}
     */
    public static final String QUESTION_TEMPLATE_KEY = "fs:question:template:";

    /**
     * 缓存过期时间：60天（单位：秒）
     * 60天 = 60 * 24 * 60 * 60 = 5,184,000秒
     * 因为模板很少修改，设置较长的过期时间
     */
    private static final long CACHE_EXPIRE_TIME = 5184000L;

    /**
     * 查询问答
     * 
     * @param id 问答主键
     * @return 问答
     */
    @Override
    public FsQuestionAndAnswerVO selectFsQuestionAndAnswerById(Long id)
    {
        String cacheKey = getTemplateKey(id);
        FsQuestionAndAnswerVO cachedVo = redisCache.getCacheObject(cacheKey);
        if (cachedVo != null) {
            return cachedVo;
        }
        log.info("缓存未命中，从数据库查询问答模板，id: {}", id);
        FsQuestionAndAnswer fsQuestionAndAnswer = baseMapper.selectFsQuestionAndAnswerById(id);
        if (fsQuestionAndAnswer == null) {
            return null;
        }
        FsQuestionAndAnswerVO vo = new FsQuestionAndAnswerVO();
        vo.setQuestionName(fsQuestionAndAnswer.getQuestionName());
        List<AnswerVO> answerVOS = JSON.parseArray(fsQuestionAndAnswer.getJsonInfo(), AnswerVO.class);
        vo.setAnswers(answerVOS);
        vo.setId(fsQuestionAndAnswer.getId());
        vo.setType(fsQuestionAndAnswer.getType());
        redisCache.setCacheObject(cacheKey, vo, (int) CACHE_EXPIRE_TIME, TimeUnit.SECONDS);
        return vo;
    }

    /**
     * 查询问答列表
     * 
     * @param fsQuestionAndAnswer 问答
     * @return 问答
     */
    @Override
    public List<FsQuestionAndAnswer> selectFsQuestionAndAnswerList(FsQuestionAndAnswer fsQuestionAndAnswer)
    {
        return baseMapper.selectFsQuestionAndAnswerList(fsQuestionAndAnswer);
    }

    /**
     * 新增问答
     * 
     * @param fsQuestionAndAnswer 问答
     * @return 结果
     */
    @Override
    public int insertFsQuestionAndAnswer(FsQuestionAndAnswer fsQuestionAndAnswer)
    {
        fsQuestionAndAnswer.setCreateTime(DateUtils.getNowDate());
        int result  = baseMapper.insertFsQuestionAndAnswer(fsQuestionAndAnswer);
        if (result > 0 && fsQuestionAndAnswer.getId() != null) {
            String cacheKey = getTemplateKey(fsQuestionAndAnswer.getId());
            redisCache.deleteObject(cacheKey);
            log.info("新增问答模板，清除缓存，id: {}, key: {}", fsQuestionAndAnswer.getId(), cacheKey);
        }
        return result;
    }

    /**
     * 修改问答
     * 
     * @param fsQuestionAndAnswer 问答
     * @return 结果
     */
    @Override
    public int updateFsQuestionAndAnswer(FsQuestionAndAnswer fsQuestionAndAnswer)
    {
        fsQuestionAndAnswer.setUpdateTime(DateUtils.getNowDate());
        int result=baseMapper.updateFsQuestionAndAnswer(fsQuestionAndAnswer);
        if (result > 0 && fsQuestionAndAnswer.getId() != null) {
            String cacheKey = getTemplateKey(fsQuestionAndAnswer.getId());
            redisCache.deleteObject(cacheKey);
            log.info("修改问答模板，清除缓存，id: {}, key: {}", fsQuestionAndAnswer.getId(), cacheKey);
        }
        return result;
    }

    /**
     * 批量删除问答
     * 
     * @param ids 需要删除的问答主键
     * @return 结果
     */
    @Override
    public int deleteFsQuestionAndAnswerByIds(Long[] ids)
    {
        int result=baseMapper.deleteFsQuestionAndAnswerByIds(ids);
        if (result > 0 && ids != null && ids.length > 0) {
            for (Long id : ids) {
                String cacheKey = getTemplateKey(id);
                redisCache.deleteObject(cacheKey);
                log.info("批量删除问答模板，清除缓存，id: {}, key: {}", id, cacheKey);
            }
        }
        return result;
    }

    /**
     * 删除问答信息
     * 
     * @param id 问答主键
     * @return 结果
     */
    @Override
    public int deleteFsQuestionAndAnswerById(Long id)
    {
        int result=baseMapper.deleteFsQuestionAndAnswerById(id);
        if (result > 0) {
            String cacheKey = getTemplateKey(id);
            redisCache.deleteObject(cacheKey);
            log.info("删除问答模板，清除缓存，id: {}, key: {}", id, cacheKey);
        }
        return result;
    }

    @Override
    public List<OptionsVO> selectAllQuestionOptions(Integer type) {
        return fsQuestionAndAnswerMapper.selectAllQuestionOptions(type);
    }

    @Override
    public List<FsQuestionAndAnswerVO> selectFsQuestionAndAnswerVOList() {
        List<FsQuestionAndAnswer> answers = fsQuestionAndAnswerMapper.selectFsQuestionAndAnswerList(new FsQuestionAndAnswer());
        List<FsQuestionAndAnswerVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(answers)) {
            answers.forEach(answer -> {
                FsQuestionAndAnswerVO vo = new FsQuestionAndAnswerVO();
                vo.setQuestionName(answer.getQuestionName());
                List<AnswerVO> answerVOS = JSON.parseArray(answer.getJsonInfo(), AnswerVO.class);
                vo.setAnswers(answerVOS);
                vo.setId(answer.getId());
                vos.add(vo);
            });
        }
        return vos;
    }

    /**
     * 获取完整的模板缓存key
     * @param id 模板ID
     * @return 完整的key
     */
    private String getTemplateKey(Long id) {
        return QUESTION_TEMPLATE_KEY + id;
    }
}
