package com.fdkankan.ucenter.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fdkankan.ucenter.entity.Case;
import com.fdkankan.ucenter.entity.FeedbackOption;
import com.fdkankan.ucenter.mapper.ICaseMapper;
import com.fdkankan.ucenter.service.ICaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.ucenter.service.IFeedbackOptionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-11
 */
@Service
public class CaseServiceImpl extends ServiceImpl<ICaseMapper, Case> implements ICaseService {

    @Autowired
    IFeedbackOptionService feedbackOptionService;
    @Override
    public List<Case> allList(Case caseEntity) {
        LambdaQueryWrapper<Case> wrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(caseEntity.getTypeId())){
            wrapper.eq(Case::getTypeId,caseEntity.getTypeId());
        }
        if(caseEntity.getIconId() !=null){
            wrapper.apply("JSON_CONTAINS(icon_ids, '"+caseEntity.getIconId()+"')");
        }
        if(caseEntity.getFeedbackOptionId()!=null){
            wrapper.apply("JSON_CONTAINS(feedback_option_ids, '"+caseEntity.getFeedbackOptionId()+"')");
        }
        wrapper.eq(Case::getLanguage,caseEntity.getLanguage());
        wrapper.eq(Case::getIsPublic,1);
        wrapper.orderByAsc(Case::getSort);
        wrapper.orderByAsc(Case::getId);
        List<Case> list = this.list(wrapper);
        HashSet<Integer> feedIds = new HashSet<>();
        for (Case aCase : list) {
            if(StringUtils.isNotBlank(aCase.getFeedbackOptionIds())){
                JSONArray jsonArray = JSONArray.parseArray(aCase.getFeedbackOptionIds());
                for (Object object : jsonArray) {
                    feedIds.add((Integer) object);
                }
            }
        }
        HashMap<Integer, FeedbackOption> mapByIds = feedbackOptionService.getMapByIds(feedIds);
        for (Case aCase : list) {
            if(StringUtils.isNotBlank(aCase.getFeedbackOptionIds())){
                JSONArray jsonArray = JSONArray.parseArray(aCase.getFeedbackOptionIds());
                List<FeedbackOption> options = new ArrayList<>();
                for (Object object : jsonArray) {
                    FeedbackOption feedbackOption = mapByIds.get((Integer) object);
                    if(feedbackOption!=null){
                        options.add(feedbackOption);
                    }
                }
                aCase.setFeedbackOptionList(options);
            }
        }

        return list;
    }
}
