package cn.com.ty.lift.ud.searchIndex.service.impl;

import cn.com.ty.lift.ud.quan_news.controller.query.QuanNewsQuery;
import cn.com.ty.lift.ud.quan_news.mapper.entity.QuanNews;
import cn.com.ty.lift.ud.quan_news.service.IQuanNewsService;
import cn.com.ty.lift.ud.question.controller.query.QuestionBankAppQuery;
import cn.com.ty.lift.ud.question.controller.query.QuestionBankQuery;
import cn.com.ty.lift.ud.question.service.IQuestionBankService;
import cn.com.ty.lift.ud.recruitmentInfos.controller.query.RecruitmentInfoQuery;
import cn.com.ty.lift.ud.recruitmentInfos.service.IRecruitmentInfoService;
import cn.com.ty.lift.ud.schoolVideo.controller.query.SchoolVideoQuery;
import cn.com.ty.lift.ud.schoolVideo.service.ISchoolVideoService;
import cn.com.ty.lift.ud.searchHistory.mapper.SearchHistoryMapper;
import cn.com.ty.lift.ud.searchHistory.mapper.entity.SearchHistoryEntity;
import cn.com.ty.lift.ud.searchHistory.service.ISearchHistoryService;
import cn.com.ty.lift.ud.searchIndex.mapper.SearchIndexMapper;
import cn.com.ty.lift.ud.searchIndex.mapper.entity.SearchIndexEntity;
import cn.com.ty.lift.ud.searchIndex.mapper.entity.SearchIndexVo;
import cn.com.ty.lift.ud.searchIndex.service.ISearchIndexService;
import cn.com.ty.lift.ud.shopping.controller.query.ShoppingQuery;
import cn.com.ty.lift.ud.shopping.mapper.entity.ShoppingEntity;
import cn.com.ty.lift.ud.shopping.service.IShoppingService;
import cn.com.ty.lift.ud.utils.IKAnalyzerUtil;
import cn.com.xwy.boot.web.dto.RestResponse;
import cn.com.xwy.util.collection.ListUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 搜索索引表-ServiceImpl
 *
 * @author Xson
 * @date 2020-05-09
 */
@Service
@Transactional
public class SearchIndexServiceImpl extends ServiceImpl<SearchIndexMapper, SearchIndexEntity>
        implements ISearchIndexService {

    @Autowired
    private SearchIndexMapper searchIndexMapper;

    @Autowired
    private IQuestionBankService iQuestionBankService;

    @Autowired
    private ISchoolVideoService iSchoolVideoService;

    @Autowired
    private IShoppingService iShoppingService;

    @Autowired
    private IRecruitmentInfoService iRecruitmentInfoService;

    @Autowired
    private IQuanNewsService quanNewsService;

    @Autowired
    private ISearchHistoryService searchHistoryService;

    @Autowired
    private SearchHistoryMapper searchHistoryMapper;

    @Autowired
    private  RedisTemplate<String, Object> redisTemplate;

//    /**
//     * 全文搜索,目前只有题库的增删改接口，同步修改了索引表的数据
//     *
//     * @param request
//     * @return
//     */
//    @Override
//    public RestResponse searchIndex(String request) {
//        List<SearchIndexVo> searchIndexList = new ArrayList();
//        List<QuestionBankEntity> qbEntityList = new ArrayList();
//        List<SchoolVideoEntity> svEntityList = new ArrayList();
//        List<ShoppingEntity> spEntityList = new ArrayList();
//        List<RecruitmentInfoEntity> riEntityList = new ArrayList();
//
//        try {
//            //分词
//            List<String> stringList = IKAnalyzerUtil.cut(request);
//            //查询 搜索索引表 中的数据
//            List<SearchIndexEntity> indexList = new ArrayList();
//            if (ListUtil.isNotEmpty(stringList)) {
//                for (String word : stringList) {
//                    List<SearchIndexEntity> indexEntityList = searchIndexMapper.selectByKeyWord(word);
//                    indexList.addAll(indexEntityList);
//                }
//                if (ListUtil.isNotEmpty(indexList)) {
//                    //查询不同的表中的数据
//                    for (SearchIndexEntity indexEntity : indexList) {
//                        //不同的表分别查出来，再整合到一起
//                        String tableName = indexEntity.getTableName();
//                        //对应的表的某条数据的主键
//                        Long tableId = indexEntity.getTableId();
//                        //不同的表有不同的接口
//                        //题库
//                        if ("question_bank".equals(tableName)) {
//                            QuestionBankEntity questionBankEntity = iQuestionBankService.selectById(tableId);
//                            qbEntityList.add(questionBankEntity);
//                        }
//                        //视频
//                        else if ("school_video".equals(tableName)) {
//                            SchoolVideoEntity schoolVideoEntity = iSchoolVideoService.getById(tableId);
//                            svEntityList.add(schoolVideoEntity);
//                        }
//                        //商城
//                        else if ("shopping".equals(tableName)) {
//                            ShoppingEntity shoppingEntity = iShoppingService.getById(tableId);
//                            spEntityList.add(shoppingEntity);
//                        }
//                        //招聘
//                        else if ("recruitment_info".equals(tableName)) {
//                            RecruitmentInfoEntity recruitmentInfoEntity = iRecruitmentInfoService.getById(tableId);
//                            riEntityList.add(recruitmentInfoEntity);
//                        }
//
//                    }
//                    //搜索结果不分页
//                    //题库
//                    SearchIndexVo searchIndexVo1 = new SearchIndexVo();
//                    searchIndexVo1.setCode("1");
//                    searchIndexVo1.setInfoList(qbEntityList);
//                    searchIndexList.add(searchIndexVo1);
//                    //视频
//                    SearchIndexVo searchIndexVo2 = new SearchIndexVo();
//                    searchIndexVo2.setCode("2");
//                    searchIndexVo2.setInfoList(svEntityList);
//                    searchIndexList.add(searchIndexVo2);
//                    //商城
//                    SearchIndexVo searchIndexVo3 = new SearchIndexVo();
//                    searchIndexVo3.setCode("3");
//                    searchIndexVo3.setInfoList(spEntityList);
//                    searchIndexList.add(searchIndexVo3);
//                    //招聘
//                    SearchIndexVo searchIndexVo4 = new SearchIndexVo();
//                    searchIndexVo4.setCode("4");
//                    searchIndexVo4.setInfoList(riEntityList);
//                    searchIndexList.add(searchIndexVo4);
//
//                    return RestResponse.success(searchIndexList, "搜索成功");
//                }
//            }
//            return RestResponse.fail("暂无数据");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return RestResponse.success(null, "暂无数据");
//    }

    /**
     * 新增时相应修改搜索索引表数据
     *
     * @param word     被修改的字段的内容  题库 title  ； 视频学堂 title ； 商城 name ； 招聘 job
     * @param moduleId 模板ID  1：题库  2：视频学堂  3：商城  4：招聘
     * @param id       数据主键ID
     */
    @Override
    public void insertSearchIndex(String word, Integer moduleId, Long id) {
        List<String> cutList = null;
        try {
            cutList = IKAnalyzerUtil.cut(word);
            if (ListUtil.isNotEmpty(cutList)) {
                for (String title : cutList) {
                    SearchIndexEntity siEntity = new SearchIndexEntity();
                    siEntity.setKeyWord(title);
                    siEntity.setTableId(id);
                    siEntity.setModuleId(moduleId);
                    //题库
                    if (moduleId == 1) {
                        siEntity.setColoumName("title");
                        siEntity.setTableName("question_bank");
                    }
                    //视频
                    if (moduleId == 2) {
                        siEntity.setColoumName("title");
                        siEntity.setTableName("school_video");
                    }
                    //商城
                    if (moduleId == 3) {
                        siEntity.setColoumName("name");
                        siEntity.setTableName("shopping");
                    }
                    //招聘
                    if (moduleId == 4) {
                        siEntity.setColoumName("job");
                        siEntity.setTableName("recruitment_info");
                    }
                    searchIndexMapper.insert(siEntity);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 修改时相应修改搜索索引表数据
     *
     * @param word     被修改的字段的内容  题库 title  ； 视频学堂 title ； 商城 name ； 招聘 job
     * @param moduleId 模板ID  1：题库  2：视频学堂  3：商城  4：招聘
     * @param id       数据主键ID
     */
    @Override
    public void updateSearchIndex(String word, Integer moduleId, Long id) {
        //1、删除之前这个 id 对应的数据
        searchIndexMapper.deleteByIdAndModuleId(moduleId, id);
        //2、新增数据
        insertSearchIndex(word, moduleId, id);
    }

    /**
     * 删除时相应修改搜索索引表数据
     *
     * @param moduleId 模板ID  1：题库  2：视频学堂  3：商城  4：招聘
     * @param ids      数据主键ID集合
     */
    @Override
    public void deleteSearchIndex(Integer moduleId, List<Long> ids) {
        //删除之前这个 id 对应的数据
        for (Long id : ids) {
            searchIndexMapper.deleteByIdAndModuleId(moduleId, id);
        }
    }

    /**
     * 全文搜索，不分词，直接模糊匹配版本
     *
     * @param request
     * @return
     */
    @Override
    public RestResponse searchIndex(String request) {
        List<SearchIndexVo> searchIndexList = new ArrayList();
        if (null != request) {
            //查询不同的表中的数据
            //题库
            QuestionBankQuery query1 = new QuestionBankQuery();
            query1.setTitle(request);
            query1.setPlatform("app");
            RestResponse restResponse1 = iQuestionBankService.selectByExample(query1);
            IPage data = (IPage) restResponse1.getData();
            if (ListUtil.isNotEmpty(data.getRecords())) {
                SearchIndexVo searchIndexVo1 = new SearchIndexVo();
                searchIndexVo1.setCode("1");
                searchIndexVo1.setInfoList(data.getRecords());
                searchIndexList.add(searchIndexVo1);
            }
            //视频
            SchoolVideoQuery query2 = new SchoolVideoQuery();
            query2.setTitle(request);
            query2.setPlatform("app");
            RestResponse restResponse2 = iSchoolVideoService.selectByExample(query2);
            IPage data2 = (IPage) restResponse2.getData();
            if (ListUtil.isNotEmpty(data2.getRecords())) {
                SearchIndexVo searchIndexVo2 = new SearchIndexVo();
                searchIndexVo2.setCode("2");
                searchIndexVo2.setInfoList(data2.getRecords());
                searchIndexList.add(searchIndexVo2);
            }
            //商城
            ShoppingQuery query3 = new ShoppingQuery();
            query3.setName(request);
            query3.setPlatform("app");
            IPage<ShoppingEntity> data3 = iShoppingService.page(query3.page(), query3.condition());
            if (ListUtil.isNotEmpty(data3.getRecords())) {
                SearchIndexVo searchIndexVo3 = new SearchIndexVo();
                searchIndexVo3.setCode("3");
                searchIndexVo3.setInfoList(data3.getRecords());
                searchIndexList.add(searchIndexVo3);
            }
            //招聘
            RecruitmentInfoQuery query4 = new RecruitmentInfoQuery();
            query4.setJob(request);
            query4.setPlatform("app");
            RestResponse restResponse4 = iRecruitmentInfoService.selectByExample(query4);
            IPage data4 = (IPage) restResponse4.getData();
            if (ListUtil.isNotEmpty(data4.getRecords())) {
                SearchIndexVo searchIndexVo4 = new SearchIndexVo();
                searchIndexVo4.setCode("4");
                searchIndexVo4.setInfoList(data4.getRecords());
                searchIndexList.add(searchIndexVo4);
            }

            //新闻
            QuanNewsQuery query5 = new QuanNewsQuery();
            query5.setTitle(request);
            IPage data5 = quanNewsService.page(query5.page(), query5.condition());
            if (ListUtil.isNotEmpty(data5.getRecords())) {
                SearchIndexVo searchIndexVo5 = new SearchIndexVo();
                searchIndexVo5.setCode("5");
                //获取lookNum
                QuanNews news = (QuanNews)data5.getRecords().get(0);
                String id = news.getId().toString();
                Long lookNum = redisTemplate.boundHashOps("system-quanNews-look-time").increment(id, 1);
                news.setLookNum(lookNum);
                data5.getRecords().remove(0);
                data5.getRecords().add(news);
                searchIndexVo5.setInfoList(data5.getRecords());
                searchIndexList.add(searchIndexVo5);
            }
            //新增/修改搜索记录
            //如果关键词搜索过，数量加1,；否则新增一条数据
            SearchHistoryEntity byKeyWord = searchHistoryMapper.getByKeyWord(request);
            if(null != byKeyWord){
                searchHistoryMapper.updateTimes(request);
            }else{
                SearchHistoryEntity sh = new SearchHistoryEntity();
                sh.setSearchTimes(1);
                sh.setKeyWord(request);
                searchHistoryService.save(sh);
            }
            return RestResponse.success(searchIndexList, "搜索成功");
        } else {
            return RestResponse.fail("暂无数据");
        }
    }

}
