package com.tykj.model.service.impl;


import com.github.wenhao.jpa.PredicateBuilder;
import com.github.wenhao.jpa.Specifications;

import com.tykj.base.result.ApiException;
import com.tykj.model.dao.QuoteDao;

import com.tykj.model.entity.Quote;
import com.tykj.model.entity.vo.SearchQuoteVO;
import com.tykj.model.entity.vo.UpdateQuoteVO;
import com.tykj.model.service.QuoteService;
import com.tykj.model.utils.SessionUtil;
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.List;
import java.util.stream.Collectors;

import static java.util.Objects.isNull;

/**
 * @Description TODO
 * @Author WWW
 * @Date 2021/5/17 15:59
 */
@Service
public class QuoteServiceImpl implements QuoteService {
    @Autowired
    private QuoteDao quoteDao;


    @Override
    public int updateQuote(UpdateQuoteVO updateQuoteVO) {
        List<Quote> quoteList = updateQuoteVO.getQuoteList();

        try {
            for (Quote quote : quoteList) {
                quote.setColumnId(updateQuoteVO.getId());
                if (existValue(quote.getColumnId(), quote.getValue())) {
                    quoteDao.save(quote);
                }
            }
            return 0;
        }
        catch (Exception e){
            return 1;
        }
    }

    @Override
    public List<Quote> getAllQuote(SearchQuoteVO sqv) {
        PredicateBuilder<Quote> and = Specifications.and();
        if (sqv!=null){
            and.like(!isNull(sqv.getValue() ) && StringUtils.isNotEmpty(sqv.getValue()),
                    "value", "%" + sqv.getValue() + "%");
            and.in(sqv.getColumnIds()!=null && sqv.getColumnIds().length>0,
                    "columnId",sqv.getColumnIds());
            and.in(sqv.getValues()!=null && sqv.getValues().length>0,
                    "value", sqv.getValues());
        }
        return quoteDao.findAll(and.build());
    }


    @Override
    public Quote saveQuote(Quote quote) {

        if (existValue(quote.getColumnId(), quote.getValue())) {
            return quoteDao.save(quote);
        }
        throw new ApiException("插入错误！");
    }

    @Override
    public Integer delQuote(Integer id) {
         quoteDao.deleteById(id);
         return 1;
    }

    public boolean existValue(Integer cId, String value) {
        List<String> collect = quoteDao.findAllByColumnId(cId)
                .stream()
                .map(Quote::getValue)
                .collect(Collectors.toList());
        if (collect.contains(value)) {
            return false;
        }
        return true;
    }


}
