package org.dromara.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.domain.complaintSuggestion.ComplaintSuggestion;
import org.dromara.domain.complaintSuggestion.bo.ComplaintSuggestionBo;
import org.dromara.domain.complaintSuggestion.vo.ComplaintSuggestionVo;
import org.dromara.domain.suggestionFj.SuggestionFj;
import org.dromara.domain.suggestionFj.bo.SuggestionFjBo;
import org.dromara.domain.suggestionFj.vo.SuggestionFjVo;
import org.dromara.mapper.ComplaintSuggestionMapper;
import org.dromara.mapper.SuggestionFjMapper;
import org.dromara.service.IComplaintSuggestionService;
import org.dromara.service.ISuggestionFjService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import static org.dromara.common.core.constant.Constants.*;

/**
 * 投诉建议Service业务层处理
 *
 * @author boman
 * @date 2025-04-11
 */
@RequiredArgsConstructor
@Service
public class ComplaintSuggestionServiceImpl implements IComplaintSuggestionService {

    private final ComplaintSuggestionMapper baseMapper;

    @Autowired
    private ISuggestionFjService suggestionFjService;

    @Autowired
    private SuggestionFjMapper suggestionFjMapper;

    /**
     * 查询投诉建议
     *
     * @param suggestionId 主键
     * @return 投诉建议
     */
    @Override
    public ComplaintSuggestionVo queryById(Long suggestionId){
        ComplaintSuggestionVo vo = baseMapper.selectVoById(suggestionId);
        SuggestionFjBo fjBo = new SuggestionFjBo();
        fjBo.setSuggestionId(suggestionId);
        List<SuggestionFjVo> suggestionFjVos = suggestionFjService.queryList(fjBo);
        if (suggestionFjVos != null && !suggestionFjVos.isEmpty()){
            vo.setSuggestionFjList(suggestionFjVos);
        }
        //判断是否已读如果是未读设置成已读
        String isRead = vo.getIsRead();
        Long userId = vo.getUserId();
        if (N.equals(isRead) && userId.equals(LoginHelper.getUserId())){
            vo.setIsRead(Y);
            ComplaintSuggestion update = MapstructUtils.convert(vo, ComplaintSuggestion.class);
            baseMapper.updateById(update);
            //app首页统计减少一个数
            String userSuggestionKey = COMPLAINT_SUGGESTION_NO + userId;
            //往redis中新增 个人 投诉建议未回复的数量 app统计使用 回复了这个用户的投诉，这个用户能看到
            Object userNum = RedisUtils.getCacheObject(userSuggestionKey);
            if (ObjectUtils.isNotEmpty(userNum)) {
                RedisUtils.setCacheObject(userSuggestionKey, Math.max((int) userNum - 1, 0));
            }else {
                RedisUtils.setCacheObject(userSuggestionKey,0);
            }
        }
        return vo;
    }

    /**
     * 分页查询投诉建议列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 投诉建议分页列表
     */
    @Override
    public TableDataInfo<ComplaintSuggestionVo> queryPageList(ComplaintSuggestionBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ComplaintSuggestion> lqw = buildQueryWrapper(bo);
        Page<ComplaintSuggestionVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的投诉建议列表
     *
     * @param bo 查询条件
     * @return 投诉建议列表
     */
    @Override
    public List<ComplaintSuggestionVo> queryList(ComplaintSuggestionBo bo) {
        LambdaQueryWrapper<ComplaintSuggestion> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ComplaintSuggestion> buildQueryWrapper(ComplaintSuggestionBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ComplaintSuggestion> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ComplaintSuggestion::getSuggestionId);
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), ComplaintSuggestion::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), ComplaintSuggestion::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getImages()), ComplaintSuggestion::getImages, bo.getImages());
        lqw.eq(bo.getCreatedTime() != null, ComplaintSuggestion::getCreatedTime, bo.getCreatedTime());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ComplaintSuggestion::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getReplyContent()), ComplaintSuggestion::getReplyContent, bo.getReplyContent());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), ComplaintSuggestion::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getIsPublic()), ComplaintSuggestion::getIsPublic, bo.getIsPublic());
        lqw.eq(bo.getUserId() != null, ComplaintSuggestion::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getIsRead()), ComplaintSuggestion::getIsRead, bo.getIsRead());
        lqw.eq(StringUtils.isNotBlank(bo.getIsDel()), ComplaintSuggestion::getIsDel, bo.getIsDel());
        return lqw;
    }

    /**
     * 新增投诉建议
     *
     * @param bo 投诉建议
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ComplaintSuggestionBo bo) {
        Long userId = LoginHelper.getUserId();
        bo.setCreateTime(DateUtils.getNowDate());
        bo.setUserId(userId);
        ComplaintSuggestion add = MapstructUtils.convert(bo, ComplaintSuggestion.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setSuggestionId(add.getSuggestionId());
            //往redis中新增 总数 投诉建议未回复的数量 app统计使用
            Object allNum = RedisUtils.getCacheObject(COMPLAINT_SUGGESTION_NO_ALL);
            if (ObjectUtils.isNotEmpty(allNum)) {
                RedisUtils.setCacheObject(COMPLAINT_SUGGESTION_NO_ALL, Math.max((int) allNum + 1, 0));
            }else {
                RedisUtils.setCacheObject(COMPLAINT_SUGGESTION_NO_ALL,1);
            }
        }
        return flag;
    }

    /**
     * 修改投诉建议
     *
     * @param bo 投诉建议
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ComplaintSuggestionBo bo) {
        Long userId = bo.getUserId();
        String status = bo.getStatus();
        if (TWO.equals(status)){
            //判断是否有附件
            List<SuggestionFj> suggestionFjList = bo.getSuggestionFjList();
            if (suggestionFjList != null && !suggestionFjList.isEmpty()){

                suggestionFjMapper.insertBatch(suggestionFjList);
            }
            String userSuggestionKey = COMPLAINT_SUGGESTION_NO + userId;
            //往redis中新增 个人 投诉建议未回复的数量 app统计使用 回复了这个用户的投诉，这个用户能看到
            Object userNum = RedisUtils.getCacheObject(userSuggestionKey);
            if (ObjectUtils.isNotEmpty(userNum)) {
                RedisUtils.setCacheObject(userSuggestionKey, Math.max((int) userNum + 1, 0));
            }else {
                RedisUtils.setCacheObject(userSuggestionKey,1);
            }
            //往redis中新增 总数 投诉建议未回复的数量 app统计使用
            Object allNum = RedisUtils.getCacheObject(COMPLAINT_SUGGESTION_NO_ALL);
            if (ObjectUtils.isNotEmpty(allNum)) {
                RedisUtils.setCacheObject(COMPLAINT_SUGGESTION_NO_ALL, Math.max((int) allNum - 1, 0));
            }else {
                RedisUtils.setCacheObject(COMPLAINT_SUGGESTION_NO_ALL,0);
            }
        }
        ComplaintSuggestion update = MapstructUtils.convert(bo, ComplaintSuggestion.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ComplaintSuggestion entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除投诉建议信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
