package org.jeecg.modules.database.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jodd.util.StringUtil;
import org.jeecg.common.constant.enums.PhysicalErrCodeEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.database.constant.ComponentSearchType;
import org.jeecg.modules.database.entity.Experiment;
import org.jeecg.modules.database.entity.SearchResult;
import org.jeecg.modules.database.mapper.ComponentSearchMapper;
import org.jeecg.modules.database.service.IComponentSearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ComponentSearchServiceImpl extends ServiceImpl<ComponentSearchMapper, SearchResult> implements IComponentSearchService {
    private static final Logger logger = LoggerFactory.getLogger(ComponentSearchServiceImpl.class);

    @Override
    public IPage<SearchResult> queryPageList(Integer type, String content, Integer pageNo, Integer pageSize) {
        LambdaQueryWrapper<SearchResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchResult::getDataType, type);
        queryWrapper.likeRight(SearchResult::getContent, content);
        Page<SearchResult> page = new Page<>(pageNo, pageSize);
        return  this.page(page, queryWrapper);
    }

    @Override
    public List<SearchResult> search(Integer type, String content) {

        LambdaQueryWrapper<SearchResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchResult::getDataType, type);
        queryWrapper.likeRight(SearchResult::getContent, content);

        return this.list(queryWrapper);
    }

    @Override
    public void saveDataAfterSaveExperiment(Experiment experiment) {
        logger.info(experiment.getSampleInfoList().toString());
        // 批量更新样品型号,样品名称，样品批次
        if (CollUtil.isNotEmpty(experiment.getSampleInfoList())) {
            experiment.getSampleInfoList().forEach(sampleInfo -> {
                if (StringUtil.isNotEmpty(sampleInfo.getSampleModel())) {
                    LambdaQueryWrapper<SearchResult> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SearchResult::getDataType,  ComponentSearchType.MODEL_NUMBER.getCode());
                    queryWrapper.likeRight(SearchResult::getContent, sampleInfo.getSampleModel().trim());
                    if (0L == this.count(queryWrapper)){
                        SearchResult modelNumberRecord = new SearchResult();
                        modelNumberRecord.setDataType(ComponentSearchType.MODEL_NUMBER.getCode());
                        modelNumberRecord.setContent(sampleInfo.getSampleModel().trim());
                        try {
                            saveOrUpdate(modelNumberRecord);
                        }catch (Exception e) {
                            logger.warn("样品型号搜索数据更新失败,错误信息: " + e.getMessage());
                        }
                    }
                }

                if (StringUtil.isNotEmpty(sampleInfo.getSampleName())) {
                    LambdaQueryWrapper<SearchResult> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(SearchResult::getDataType,  ComponentSearchType.MODEL_NAME.getCode());
                    queryWrapper.likeRight(SearchResult::getContent, sampleInfo.getSampleName().trim());
                    if (0L == this.count(queryWrapper)){
                        SearchResult modelNameRecord = new SearchResult();
                        modelNameRecord.setDataType(ComponentSearchType.MODEL_NAME.getCode());
                        modelNameRecord.setContent(sampleInfo.getSampleName());
                        try {
                            saveOrUpdate(modelNameRecord);
                        }catch (Exception e) {
                            logger.warn("样品名称搜索数据更新失败,错误信息: " + e.getMessage());
                        }
                    }
                }

               if (StringUtil.isNotEmpty(sampleInfo.getSampleBatch())){
                   LambdaQueryWrapper<SearchResult> queryWrapper = new LambdaQueryWrapper<>();
                   queryWrapper.eq(SearchResult::getDataType,  ComponentSearchType.MODEL_BATCH_NO.getCode());
                   queryWrapper.likeRight(SearchResult::getContent, sampleInfo.getSampleBatch().trim());
                   if (0L == this.count(queryWrapper)){
                       SearchResult modelBatchNoRecord = new SearchResult();
                       modelBatchNoRecord.setDataType(ComponentSearchType.MODEL_BATCH_NO.getCode());
                       modelBatchNoRecord.setContent(sampleInfo.getSampleBatch());
                       try {
                           saveOrUpdate(modelBatchNoRecord);
                       }catch (Exception e) {
                           logger.warn("样品批次搜索数据更新失败,错误信息: " + e.getMessage());
                       }
                   }
               }

            });
        }
    }

    @Override
    public boolean saveComponentSearch(SearchResult searchResult) {
        logger.info(searchResult.toString());

        LambdaQueryWrapper<SearchResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchResult::getDataType,  searchResult.getDataType());
        queryWrapper.eq(SearchResult::getContent, searchResult.getContent());
        if (this.count(queryWrapper) > 0)
            throw  new JeecgBootException("数据已存在！",PhysicalErrCodeEnum.SEARCH_DATA_ADD_DUPLICATE.getCode());

        return  this.saveOrUpdate(searchResult);
    }

    @Override
    public boolean saveComponentSearchByType(int type, String content) {
        boolean result = false;
        LambdaQueryWrapper<SearchResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SearchResult::getDataType,  type);
        queryWrapper.likeRight(SearchResult::getContent, content);
        if (0L == this.count(queryWrapper)){
            SearchResult modelBatchNoRecord = new SearchResult();
            modelBatchNoRecord.setDataType(type);
            modelBatchNoRecord.setContent(content);
            try {
                result = saveOrUpdate(modelBatchNoRecord);
            }catch (Exception e) {
                logger.warn("搜索数据更新失败，type: " + type + ", 内容：" + content);
                result = false;
            }
        }
        return result;
    }
}
