package com.yeejoin.amos.boot.module.jg.biz.service.impl;

import cn.hutool.core.map.MapBuilder;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jg.api.dto.ESDataChangeLogDto;
import com.yeejoin.amos.boot.module.jg.api.dto.JgBizChangeLogDto;
import com.yeejoin.amos.boot.module.jg.api.dto.JgResumeInfoDto;
import com.yeejoin.amos.boot.module.jg.api.entity.JgBizChangeLog;
import com.yeejoin.amos.boot.module.jg.api.mapper.JgBizChangeLogMapper;
import com.yeejoin.amos.boot.module.jg.api.service.IJgBizChangeLogService;
import com.yeejoin.amos.boot.module.jg.biz.dao.ESDataChangeLogDao;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import java.io.IOException;
import java.util.*;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2025-04-14
 */
@Service
@RequiredArgsConstructor
public class JgBizChangeLogServiceImpl extends BaseService<JgBizChangeLogDto, JgBizChangeLog, JgBizChangeLogMapper> implements IJgBizChangeLogService {

    private final ESDataChangeLogDao esDataChangeLogDao;
    private final RestHighLevelClient restHighLevelClient;
    private final JgResumeInfoServiceImpl jgResumeInfoService;

    public void save2DbAndEs(JgBizChangeLog changeLog, List<ESDataChangeLogDto> esDataChangeLogDtos) {
        this.save(changeLog);
        esDataChangeLogDtos.forEach(esDataChangeLogDto -> esDataChangeLogDto.setBatchId(changeLog.getSequenceNbr() + ""));
        if (!esDataChangeLogDtos.isEmpty()) {
            esDataChangeLogDao.saveAll(esDataChangeLogDtos);
        }
    }

    @Override
    public IPage<JgResumeInfoDto> queryPageListByChangeIds(Set<String> changeIds, int current, int size) {
        if (CollectionUtils.isEmpty(changeIds)) {
            return new Page<>(current, size);
        }
        Page<JgResumeInfoDto> page = new Page<>(current, size);
        return jgResumeInfoService.queryPageListByChangeIds(page, changeIds);
    }

    public Map<String, Object> getDetails(String changeLogId) {
        JgBizChangeLog log = baseMapper.selectById(changeLogId);
        if (log == null) return Collections.emptyMap();
        return MapBuilder.<String, Object>create()
                .put("operateLogList", this.queryEquipInIds(changeLogId))
                .put("changeReason", log.getChangeReason())
                .put("changeAttachment", JSONObject.parseArray(log.getChangeAttachment()))
                .put("unitName", log.getUnitName())
                .put("recUserName", log.getRecUserName())
                .build();
    }

    /**
     * 根据ids查询设备
     */
    public List<JSONObject> queryEquipInIds(String changeLogId) {
        List<JSONObject> result = new ArrayList<>();
        SearchRequest request = new SearchRequest();
        request.indices("biz_data_operate_log");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        if (!ObjectUtils.isEmpty(changeLogId)) {
            BoolQueryBuilder seqBuilder = QueryBuilders.boolQuery();
            seqBuilder.must(QueryBuilders.termQuery("batchId", changeLogId));
            boolMust.must(seqBuilder);
        }
        builder.query(boolMust);
        builder.sort("createDate", SortOrder.DESC);
        request.source(builder);
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            for (SearchHit hit : response.getHits().getHits()) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(hit);
                JSONObject source = jsonObject.getJSONObject("sourceAsMap");
                result.add(source);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}