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.foundation.utils.ValidationUtil;
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("changeReason", log.getChangeReason())
                .put("changeAttachment", JSONObject.parseArray(log.getChangeAttachment()))
                .put("unitName", log.getUnitName())
                .put("recUserName", log.getRecUserName())
                .put("changeLogId", log.getSequenceNbr())
                .build();
    }

    /**
     * 根据ids查询设备
     */
    public Page<JSONObject> queryEquipInIds(JSONObject map) {
        Page<JSONObject> result = new Page<>(map.getInteger("number"), map.getInteger("size"));
        SearchRequest request = new SearchRequest();
        request.indices("biz_data_operate_log");
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.trackTotalHits(true);
        BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
        if (!ObjectUtils.isEmpty(map.get("changeLogId"))) {
            BoolQueryBuilder seqBuilder = QueryBuilders.boolQuery();
            seqBuilder.must(QueryBuilders.termQuery("batchId", map.get("changeLogId")));
            boolMust.must(seqBuilder);
        }
        builder.query(boolMust);
        builder.sort("createDate", SortOrder.DESC);
        builder.from((map.getInteger("number") - 1) * map.getInteger("size"));
        builder.size(map.getInteger("size"));
        request.source(builder);
        long totle = 0;
        List<JSONObject> list = new LinkedList<>();
        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");
                if (!ValidationUtil.isEmpty(source.get("columnType")) && !"String".equals(source.get("columnType"))) {
                    Object before = source.get("beforeData");
                    Object after = source.get("afterData");
                    Object displayOldValue = source.get("displayOldValue");
                    Object displayNewValue = source.get("displayNewValue");
                    if (Objects.toString(before, "").trim().startsWith("[") && Objects.toString(after, "").trim().startsWith("[")) {
                        source.put("beforeData", JSONObject.parseArray(Objects.toString(before, "")));
                        source.put("afterData", JSONObject.parseArray(Objects.toString(after, "")));
                        source.put("displayOldValue", JSONObject.parseArray(Objects.toString(displayOldValue, "")));
                        source.put("displayNewValue", JSONObject.parseArray(Objects.toString(displayNewValue, "")));
                    }
                }
                list.add(source);
                totle = Objects.requireNonNull(response.getInternalResponse().hits().getTotalHits()).value;
                result.setRecords(list);
                result.setTotal(totle);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}