package com.usky.fire.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.fire.domain.PatrolInspectionEvent;
import com.usky.fire.domain.PatrolInspectionPersonnel;
import com.usky.fire.domain.PatrolInspectionPlanSchedule;
import com.usky.fire.mapper.PatrolInspectionEventMapper;
import com.usky.fire.service.PatrolInspectionEventService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.fire.service.PatrolInspectionPersonnelService;
import com.usky.fire.service.PatrolInspectionPlanScheduleService;
import com.usky.fire.service.config.SyncPatrolInspectionEvent;
import com.usky.fire.service.config.mqtt.MqttOutConfig;
import com.usky.fire.service.config.rabbitmq.RabbitMQConfig;
import com.usky.fire.service.vo.PatrolInspectionPlanRequestVO;
import com.usky.system.RemoteDictService;
import com.usky.system.RemoteMceService;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 事件管理表 服务实现类
 * </p>
 *
 * @author han
 * @since 2024-05-09
 */
@Service
public class PatrolInspectionEventServiceImpl extends AbstractCrudService<PatrolInspectionEventMapper, PatrolInspectionEvent> implements PatrolInspectionEventService {
    @Autowired
    private PatrolInspectionPlanScheduleService patrolInspectionPlanScheduleService;
    @Autowired
    private PatrolInspectionPersonnelService patrolInspectionPersonnelService;
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
//    @Autowired
//    private RabbitMQConfig rabbitMQConfig;
    @Resource
    private MqttOutConfig.MqttGateway mqttGateway;
    @Autowired
    private SyncPatrolInspectionEvent syncPatrolInspectionEvent;

    @Override
    public CommonPage<PatrolInspectionEvent> patrolInspectionEventList(PatrolInspectionPlanRequestVO requestVO){
        Integer current = requestVO.getPageNum();
        Integer size = requestVO.getPageSize();
        IPage<PatrolInspectionEvent> page = new Page<>(current,size);
        LambdaQueryWrapper<PatrolInspectionEvent> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(requestVO.getId() != null,PatrolInspectionEvent::getId,requestVO.getId())
                .like(StringUtils.isNotBlank(requestVO.getPersonnelName()),PatrolInspectionEvent::getPersonnelName,requestVO.getPersonnelName())
                .like(StringUtils.isNotBlank(requestVO.getEventName()),PatrolInspectionEvent::getEventName,requestVO.getEventName())
                .eq(requestVO.getHandleStatus() != null,PatrolInspectionEvent::getHandleStatus,requestVO.getHandleStatus())
                .eq(StringUtils.isNotBlank(requestVO.getDeviceId()),PatrolInspectionEvent::getDeviceId,requestVO.getDeviceId())
                .eq(requestVO.getEventLevel() != null,PatrolInspectionEvent::getEventLevel,requestVO.getEventLevel())
                .eq(PatrolInspectionEvent::getTenantId, SecurityUtils.getTenantId())
                .orderByDesc(PatrolInspectionEvent::getId);
        page = this.page(page,queryWrapper);

        return new CommonPage<>(page.getRecords(),page.getTotal(),size,current);
    }

    @Override
    public void add(PatrolInspectionEvent patrolInspectionEvent){

        Map<Object,Object> map = new HashMap<>();

        if(null != patrolInspectionEvent.getPlanId()){
            Integer planId = patrolInspectionEvent.getPlanId();
            LambdaQueryWrapper<PatrolInspectionPlanSchedule> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(PatrolInspectionPlanSchedule::getPlanId,planId);
            List<PatrolInspectionPlanSchedule> list = patrolInspectionPlanScheduleService.list(queryWrapper);
            if(list.size() > 0){
                Integer personnelId = list.get(0).getPersonnelId();
                LambdaQueryWrapper<PatrolInspectionPersonnel> queryWrapper1 = Wrappers.lambdaQuery();
                queryWrapper1.eq(PatrolInspectionPersonnel::getId,personnelId);
                PatrolInspectionPersonnel one = patrolInspectionPersonnelService.getOne(queryWrapper1);

                patrolInspectionEvent.setPersonnelId(personnelId);
                patrolInspectionEvent.setPersonnelName(one.getFullName());
                map.put("idCard",one.getIdCard());
            }
        }else{
            Long userId = SecurityUtils.getUserId();
            patrolInspectionEvent.setPersonnelId(userId.intValue());
            patrolInspectionEvent.setPersonnelName(SecurityUtils.getUsername());
        }

        patrolInspectionEvent.setHandleStatus(0);
        patrolInspectionEvent.setTenantId(SecurityUtils.getTenantId());
        patrolInspectionEvent.setCreateBy(SecurityUtils.getUsername());
        patrolInspectionEvent.setCreateTime(LocalDateTime.now());

        map.put("deviceId",patrolInspectionEvent.getDeviceId());
        map.put("personnelId",patrolInspectionEvent.getPersonnelId());
        map.put("personnelName",patrolInspectionEvent.getPersonnelName());
        map.put("eventName",patrolInspectionEvent.getEventName());
        map.put("eventType",patrolInspectionEvent.getEventType());
        map.put("eventCategory",patrolInspectionEvent.getEventCategory());
        map.put("eventImage",patrolInspectionEvent.getEventImage());
        map.put("handleStatus",patrolInspectionEvent.getHandleStatus());
        map.put("handleName",patrolInspectionEvent.getHandleName());
        map.put("handleTime",patrolInspectionEvent.getHandleTime());
        map.put("remark",patrolInspectionEvent.getRemark());
        map.put("createBy",patrolInspectionEvent.getCreateBy());
        map.put("createTime",patrolInspectionEvent.getCreateTime());

//        rabbitTemplate.convertAndSend(rabbitMQConfig.patrolEventExchange,SecurityUtils.getTenantId().toString(),map);
        mqttGateway.sendToMqtt("/patrolEEvent/"+SecurityUtils.getTenantId()+"/event",JSONObject.toJSONString(map));
//      rabbitTemplate.convertAndSend(rabbitMQConfig.patrolFEventExchange,"", JSONObject.toJSONString(map));

        this.save(patrolInspectionEvent);

//        syncPatrolInspectionEvent.sendAsyncMessage(SecurityUtils.getTenantId(),patrolInspectionEvent.getId(),patrolInspectionEvent.getEventName(),patrolInspectionEvent.getEventType());

    }

    @Override
    public void edit(PatrolInspectionEvent patrolInspectionEvent){
        PatrolInspectionEvent one = this.getById(patrolInspectionEvent.getId());
        if(one == null){
            throw new BusinessException("没有对应记录数据");
        }

        patrolInspectionEvent.setHandleStatus(1);
        patrolInspectionEvent.setHandleName(SecurityUtils.getUsername());
        patrolInspectionEvent.setHandleTime(LocalDateTime.now());
        this.updateById(patrolInspectionEvent);

    }

}
