package com.pcloud.book.es.biz.impl;

import com.pcloud.book.book.dao.BookDao;
import com.pcloud.book.es.biz.ESBookAndAdviserBiz;
import com.pcloud.book.es.entity.ESBookAndAdviser;
import com.pcloud.book.es.repository.BookAndAdviserRepository;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.book.util.common.YesOrNoEnums;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.string.StringUtil;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author ruansiyuan
 * @Date 2020/4/13 12:21
 **/
@Component("esBookAndAdviserBiz")
public class ESBookAndAdviserBizImpl implements ESBookAndAdviserBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(ESBookAndAdviserBizImpl.class);

    @Autowired
    private BookDao bookDao;
    @Autowired
    private BookAndAdviserRepository bookAndAdviserRepository;

    @ParamLog("导入全部book和bookAdviser")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addAllBookAndAdviserToES() {
        ThreadPoolUtils.OTHER_THREAD_POOL.execute(() -> {
            Integer count = bookDao.count();
            LOGGER.info("总数:" + count);
            if (null == count || count <= 0) {
                return;
            }
            Long maxId = 0L;
            Integer index = 0;
            Integer offset = 10000;
            List<ESBookAndAdviser> list;
            while (index * offset < count) {
                list = bookDao.findAllBookAndAdviser(maxId, offset);
                if (ListUtils.isEmpty(list)) {
                    break;
                }
                bookAndAdviserRepository.save(list);
                maxId = Long.valueOf(list.get(list.size() - 1).getBookId());
                index += 1;
                list.clear();
            }
        });
    }

    @ParamLog("更新书和编辑书")
    @Override
    public void updateBookAndAdviserToES(List<Long> bookIds) {
        if(bookIds==null){
            return;
        }
        try {
            List<ESBookAndAdviser> list = bookDao.findBookAndAdviserByBookIds(bookIds);
            if (ListUtils.isEmpty(list)){
                return;
            }
            bookAndAdviserRepository.save(list);
        }catch (Exception e){
            LOGGER.error("更新书和编辑书出错："+bookIds.toString());
        }

    }

    @Override
    public Page<ESBookAndAdviser> getAdviserBooks4ES(String grayStatus, String keyword, Long templetId, Long secondTempletId, Integer currentPage, Integer numPerPage) {
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .filter(QueryBuilders.termQuery("isBookDelete", 0))
                .filter(Objects.isNull(templetId) ? QueryBuilders.boolQuery() : QueryBuilders.termQuery("templetId", templetId))
                .filter(Objects.isNull(secondTempletId) ? QueryBuilders.boolQuery() : QueryBuilders.termQuery("secondTempletId", secondTempletId));
        BoolQueryBuilder should = QueryBuilders.boolQuery()
                .should(StringUtil.isEmpty(keyword) ? QueryBuilders.boolQuery() : QueryBuilders.wildcardQuery("bookName", "*" + keyword + "*"))
                .should(StringUtil.isEmpty(keyword) ? QueryBuilders.boolQuery() : QueryBuilders.wildcardQuery("isbn", "*" + keyword + "*"));
        BoolQueryBuilder should1 = QueryBuilders.boolQuery()
                .should(QueryBuilders.termQuery("isBookAdviserDelete", 0))
                .should(QueryBuilders.termQuery("isAdviserBook", 0));
        // 审核通过之后屏蔽掉测试编辑的书刊
        BoolQueryBuilder adviserIdBuilder = QueryBuilders.boolQuery();
        if (YesOrNoEnums.YES.getCode().equals(grayStatus)) {
            if ("test".equalsIgnoreCase(BookProps.getSystemEnv())) {
                adviserIdBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("adviserId", 1404));
            }
            if ("uat".equalsIgnoreCase(BookProps.getSystemEnv())) {
                adviserIdBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("adviserId", 12829));
            }
            if ("pro".equalsIgnoreCase(BookProps.getSystemEnv())) {
                adviserIdBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("adviserId", 1362));
            }
        }
        boolQueryBuilder.must(should);
        boolQueryBuilder.must(should1);
        boolQueryBuilder.must(adviserIdBuilder);
        Sort sort=new Sort(Sort.Direction.DESC, "isAdviserBook","lastModifiedDate", "bookId");
        PageRequest pageRequest = new PageRequest(currentPage, numPerPage,sort);
        Page<ESBookAndAdviser> search = bookAndAdviserRepository.search(boolQueryBuilder, pageRequest);
        return search;
    }

}
