package com.jpsoft.shinestar.mq.listener;

import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.entity.MeetingPersonRecode;
import com.jpsoft.shinestar.modules.business.service.CanteenRecordAttendanceService;
import com.jpsoft.shinestar.modules.business.service.MeetingPersonRecodeService;
import com.jpsoft.shinestar.modules.business.service.WorkAttendanceService;
import com.jpsoft.shinestar.modules.business.service.WorkScheduleAttendanceService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.uniview.dto.PersonNotification;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Component
@RabbitListener(queues = "personNotificationQueue",concurrency = "10")
public class PersonNotificationListener {
    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private DeviceInfoService deviceInfoService;

//  @Autowired
//  private WorkAttendanceService workAttendanceService;
    @Autowired
    private WorkScheduleAttendanceService workScheduleAttendanceService;

    @Autowired
    private CanteenDiningRecordService canteenDiningRecordService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private WarningPusherService warningPusherService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private MeetingPersonRecodeService meetingPersonRecodeService;

    @Autowired
    private WxConfig wxConfig;

    @Value("${wx.notice.temperatureWarningTmplCode}")
    private String temperatureWarningTmplCode;

    @Value("${mobile.temperatureUrl}")
    private String temperatureUrl;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @RabbitHandler
    public void process(PersonNotification notification) {
        log.warn("收到身份识别通知：" + notification.getPersonId());

        try {
            PersonInfo personInfo = personInfoService.get(notification.getPersonId());

            if (personInfo==null) {
                log.warn("{}无人员信息!", notification.getPersonId());
                return;
            }

            DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(notification.getDeviceNo());

            if (deviceInfo==null){
                log.error("{}无对应设备信息!", notification.getDeviceNo());
                return;
            }

            List<String> sceneNameList = deviceInfoService.findSceneListByDeviceNo(notification.getDeviceNo());

            if(sceneNameList.stream().filter((scene)->scene.contains("考勤")).count()>0){
                workScheduleAttendanceService.punchIn(notification.getDeviceNo(), personInfo.getId(),
                        notification.getTemperature(),
                        notification.getRecordTime());
            }

            if(sceneNameList.stream().filter((scene)->scene.contains("食堂")).count()>0){
                canteenDiningRecordService.punchIn(notification.getDeviceNo(), personInfo.getId(), notification.getRecordTime());
            }

            if(sceneNameList.stream().filter((scene)->scene.contains("会议")).count()>0){
                meetingPersonRecodeService.punchIn(notification.getDeviceNo(), personInfo.getId(), notification.getRecordTime());
            }

            sendTemperatureAlarmsyncTask(personInfo,notification.getPersonDeviceLogId());
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);
        }
    }

    public void sendTemperatureAlarmsyncTask(PersonInfo personInfo, String personDeviceLogId) {
        try {
            if(personInfo==null || personInfo.getId()==0L){
                log.warn("人员不存在!");
                return;
            }

            PersonDeviceLog personDeviceLog = personDeviceLogService.get(personDeviceLogId);

            if (personInfo == null) {
                log.warn(personDeviceLog.getPersonId() + "对应的人员不存在!");
                return;
            }

            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            if (companyInfo == null) {
                throw new Exception(personInfo.getName() + "对应的公司不存在");
            }

            DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(personDeviceLog.getDeviceNo());

            if (deviceInfo == null) {
                throw new Exception(personDeviceLog.getDeviceNo() + "设备不存在");
            }

            List<String> idList = Arrays.asList(companyInfo.getCode().split(","));

            List<WarningPusher> warningPusherList = warningPusherService.findByCompanyIdList(idList);

            if (warningPusherList.size() > 0) {
                for (WarningPusher warningPusher : warningPusherList) {
                    if (personDeviceLog.getTemperature()!=null
                    && personDeviceLog.getTemperature().compareTo(warningPusher.getTemperature())>0) {
                        Map<String, Object> searchParams = new HashMap<>();
                        searchParams.put("deviceNo", personDeviceLog.getDeviceNo());
                        searchParams.put("personId", personDeviceLog.getPersonId());
                        //后台查询时>=，故这里加0.1
                        searchParams.put("minTemperature", warningPusher.getTemperature().add(new BigDecimal(0.1F)));
                        searchParams.put("beginTime", new Date(personDeviceLog.getRecordTime().getTime() - 300000));
                        List<Sort> sortList = new ArrayList<>();
                        sortList.add(new Sort("record_time", "desc"));

                        List<PersonDeviceLog> personDeviceLogList = personDeviceLogService.pageList(searchParams, sortList);

                        if (personDeviceLogList.size() >= warningPusher.getTimes()) {
                            WechatMessageUtil.sendTemperatureAlarmInfo(
                                    temperatureWarningTmplCode,
                                    warningPusher.getOpenId(),
                                    String.format("测温人:%s,温度:%s,地点:%s",
                                            personInfo.getName(),
                                            personDeviceLog.getTemperature(),
                                            companyInfo.getName() + "_" + deviceInfo.getAliasName()
                                    ),
                                    wxConfig.getAppId(),
                                    wxConfig.getAppSecret(),
                                    temperatureUrl + "?id=" + personDeviceLog.getId());
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
