package com.yeejoin.equipmanage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.equipmanage.common.dto.EquiplistSpecificBySystemESVO;
import com.yeejoin.equipmanage.common.entity.EquipmentIndex;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecificIndex;
import com.yeejoin.equipmanage.common.entity.dto.EquipmentAlarmLogDto;
import com.yeejoin.equipmanage.common.exception.BaseException;
import com.yeejoin.equipmanage.dao.ESequiplistSpecificBySystemRepository;
import com.yeejoin.equipmanage.mapper.EquipmentIndexMapper;
import com.yeejoin.equipmanage.service.IESeqService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/3/13
 */
@Service
public class ESeqServiceImpl implements IESeqService {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Autowired
    private ESequiplistSpecificBySystemRepository esequiplistSpecificBySystemRepository;

    @Autowired
    private EquipmentIndexMapper equipmentIndexMapper;

    @Value("${es.ESEquiplistSpecific.flag}")
    private Boolean flag;
    @Value("${es.ESEquiplistSpecific.year}")
    private Integer year;

    @Override
    @Async("equipAsyncExecutor")
    public EquiplistSpecificBySystemESVO saveESEquiplistSpecificBySystemESVO(EquipmentSpecificIndex equipmentSpecificIndex,String systemId,String systemName) {
        EquiplistSpecificBySystemESVO  equiplistSpecificBySystemESVO  =new EquiplistSpecificBySystemESVO();

        try {
            BeanUtils.copyProperties(equipmentSpecificIndex,equiplistSpecificBySystemESVO);
            equiplistSpecificBySystemESVO.setId(UUID.randomUUID().toString());
            equiplistSpecificBySystemESVO.setTime(new Date().getTime());
            equiplistSpecificBySystemESVO.setSystemId(systemId);
            equiplistSpecificBySystemESVO.setSystemName(systemName);
            esequiplistSpecificBySystemRepository.save(equiplistSpecificBySystemESVO);

        }catch (Exception e) {
           throw new BaseException("es新增报错");
        }
        return equiplistSpecificBySystemESVO;
    }

    @Override
    public Page<EquipmentAlarmLogDto> findAllBySystemId(String systemId,  Long startTime, Long endTime,int pageSize, int current   ) {
        Page<EquipmentAlarmLogDto> pageBean = new Page<EquipmentAlarmLogDto>(current,pageSize);
        //组装查询
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
                .withQuery(
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.wildcardQuery("systemId", "*"+systemId+"*"))
                                .must(QueryBuilders.termQuery("isAlarm", 0))
                                .must(QueryBuilders.rangeQuery("time").gte(startTime).lte(endTime))
                )
                .withPageable(PageRequest.of(current-1, pageSize))
                .withSort(SortBuilders.fieldSort("time").order(SortOrder.DESC));
        List<EquipmentAlarmLogDto> list = new LinkedList<EquipmentAlarmLogDto>();
        try
        {
            SearchHits<EquiplistSpecificBySystemESVO> searchHits =elasticsearchTemplate.search(queryBuilder.build(), EquiplistSpecificBySystemESVO.class);

            for (SearchHit<EquiplistSpecificBySystemESVO> searchHit : searchHits.getSearchHits())
            {
                JSONObject jsonObject = (JSONObject) JSON.toJSON(searchHit.getContent());
                EquiplistSpecificBySystemESVO equiplistSpecificBySystemESVO = JSON.toJavaObject(jsonObject, EquiplistSpecificBySystemESVO.class);
                EquipmentAlarmLogDto da=new EquipmentAlarmLogDto();
                    da.setId(UUID.randomUUID().toString());
                    da.setName(equiplistSpecificBySystemESVO.getEquipmentSpecificName());
                    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date daf =new Date(equiplistSpecificBySystemESVO.getTime());
                    String time=ft.format(daf);
                    da.setTime(time);
//                    String value=equiplistSpecificBySystemESVO.getValue();
//                    value= getReadableStatus(value );
//                    da.setContent(equiplistSpecificBySystemESVO.getEquipmentIndexName()+":"+value);
                    QueryWrapper<EquipmentIndex> wrapper = new QueryWrapper<>();
                    wrapper.eq("name_key", equiplistSpecificBySystemESVO.getEquipmentIndexKey());
                    wrapper.last("limit 1");
                    EquipmentIndex index = equipmentIndexMapper.selectOne(wrapper);
                    da.setContent(index.getTypeName());
                    list.add(da);
            }
            pageBean.setRecords(list);
            pageBean.setTotal(searchHits.getTotalHits());

        }catch (Exception e) {
            e.printStackTrace();
            throw  new BadRequest("系统异常");
        }
        return pageBean;
    }

    @Override
    @Scheduled(cron = "${es.ESEquiplistSpecific.time}")
    public void deleteESEquiplistSpecificBySystemES() {
        if(flag){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.YEAR, -year);
            Long endTime = calendar.getTime().getTime();
            BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
            queryBuilder.must(QueryBuilders.rangeQuery("time").lte(endTime));
            Query query = new NativeSearchQuery(queryBuilder);
            elasticsearchTemplate.delete(query, EquiplistSpecificBySystemESVO.class, IndexCoordinates.of("equipmen_date"));

        }
    }

    public String getReadableStatus(String value ) {
        if("true".equals(value)){
            return "是";
        }
        return  "false".equals(value)?"否":value;
    }
}
