package com.yuchen.saas.park.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
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.yuchen.saas.message.api.dto.WebSocketMessagDTO;
import com.yuchen.saas.message.api.feign.ws.WebSocketFeignServer;
import com.yuchen.saas.park.api.dto.park.ImportantFaceMatchDTO;
import com.yuchen.saas.park.api.entity.device.PmgBatSmartEquipment;
import com.yuchen.saas.park.api.entity.park.PmgBatFaceCaptureEventData;
import com.yuchen.saas.park.api.entity.park.PmgBatParkInfo;
import com.yuchen.saas.park.api.enums.PersonGroupNameEnum;
import com.yuchen.saas.park.api.request.PeopleCaptureQueryRequest;
import com.yuchen.saas.park.api.response.PeopleCaptureResponse;
import com.yuchen.saas.park.api.vo.park.FaceMatchVo;
import com.yuchen.saas.park.service.mapper.FaceCaptureEventDataMapper;
import com.yuchen.saas.park.service.service.FaceMatchService;
import com.yuchen.saas.park.service.service.PmgBatParkInfoService;
import com.yuchen.saas.park.service.service.PmgBatSmartEquipmentService;
import com.yuchen.saas.park.service.wrapper.FaceMatchWrapper;
import com.yuchen.saas.parking.api.util.DateUtils;
import com.yuchen.saas.parking.api.util.StringUtil;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author llc
 * @date 2022/6/16 16:19
 * @Description
 */
@Service
public class FaceMatchServiceImpl extends BaseServiceImpl<FaceCaptureEventDataMapper, PmgBatFaceCaptureEventData>
        implements FaceMatchService {

    @Resource
    //SimpMessagingTemplate simpMessagingTemplate;
    private WebSocketFeignServer webSocketClient;

    @Autowired
    private PmgBatSmartEquipmentService equipmentService;

    @Resource
    private PmgBatParkInfoService pmgBatParkInfoService;


    @Override
    public boolean add(ImportantFaceMatchDTO importantFaceMatchDTO) {
        PmgBatFaceCaptureEventData pmgBatFaceCaptureEventData = new PmgBatFaceCaptureEventData();
        BeanUtils.copyProperties(importantFaceMatchDTO, pmgBatFaceCaptureEventData);
        // 园区id通过设备查询数据库获取
        PmgBatSmartEquipment equipment = equipmentService.getOne(Wrappers.<PmgBatSmartEquipment>lambdaQuery()
                .select(PmgBatSmartEquipment::getParkId, PmgBatSmartEquipment::getTenantId)
                .eq(PmgBatSmartEquipment::getProductKey, importantFaceMatchDTO.getProductKey())
                .eq(PmgBatSmartEquipment::getDeviceName, importantFaceMatchDTO.getDeviceName()));
        if (equipment != null) {
            pmgBatFaceCaptureEventData.setParkId(equipment.getParkId());
            pmgBatFaceCaptureEventData.setTenantId(equipment.getTenantId());
            FaceMatchVo vo =new FaceMatchWrapper().entityVO(pmgBatFaceCaptureEventData);;
            // 设备识别失败丢掉数据
            this.save(pmgBatFaceCaptureEventData);
            // webSocket推送前端
            switch (importantFaceMatchDTO.getType()){
                case "0":  //登记人员推送
                    vo.setMessageType("0");
                    /*simpMessagingTemplate.convertAndSendToUser(String.valueOf(pmgBatFaceCaptureEventData.getParkId()),
                            "/person", vo);*/
                    WebSocketMessagDTO dto0 = new WebSocketMessagDTO(String.valueOf(pmgBatFaceCaptureEventData.getParkId()),
                            "/person", BeanUtil.beanToMap(vo));
                    webSocketClient.convertAndSendToUser(dto0);
                case "1":   //陌生人员推送
                    vo.setMessageType("1");
                    /*simpMessagingTemplate.convertAndSendToUser(String.valueOf(pmgBatFaceCaptureEventData.getParkId()),
                            "/person", vo);*/
                    WebSocketMessagDTO dto1 = new WebSocketMessagDTO(String.valueOf(pmgBatFaceCaptureEventData.getParkId()),
                            "/person", BeanUtil.beanToMap(vo));
                    webSocketClient.convertAndSendToUser(dto1);
                default:

            }
            vo.setMessageType("2");
            //中间人脸识别推送
            /*simpMessagingTemplate.convertAndSendToUser(String.valueOf(pmgBatFaceCaptureEventData.getParkId()),
                    "/person",vo);*/
            WebSocketMessagDTO dto2 = new WebSocketMessagDTO(String.valueOf(pmgBatFaceCaptureEventData.getParkId()),
                    "/person", BeanUtil.beanToMap(vo));
            webSocketClient.convertAndSendToUser(dto2);

        }else{
            log.error("数据丢失:"+importantFaceMatchDTO.getProductKey()+""+importantFaceMatchDTO.getDeviceName());
        }

        return true;
    }



    @Override
    public List<FaceMatchVo> latestDataQuery(Long parkId) {
        LambdaQueryWrapper<PmgBatFaceCaptureEventData> peopleHikWrapper = Wrappers.lambdaQuery();
        List<PmgBatFaceCaptureEventData> preventionList = this.list(peopleHikWrapper
                .eq(PmgBatFaceCaptureEventData::getParkId, parkId)
                .orderByDesc(PmgBatFaceCaptureEventData::getFaceTime).last("limit 30"));
        return new FaceMatchWrapper().listVO(preventionList);
    }

    @Override
    public List<FaceMatchVo> latestDataQuery2(Long parkId,String type,String limit) {
        LambdaQueryWrapper<PmgBatFaceCaptureEventData> peopleHikWrapper = Wrappers.lambdaQuery();
        List<PmgBatFaceCaptureEventData> preventionList = this.list(peopleHikWrapper
                .eq(PmgBatFaceCaptureEventData::getParkId, parkId)
                .eq(PmgBatFaceCaptureEventData::getType, type)
                .orderByDesc(PmgBatFaceCaptureEventData::getFaceTime).last("limit "+limit));
        return new FaceMatchWrapper().listVO(preventionList);
    }

    @Override
    public IPage<FaceMatchVo> pageQuery(ImportantFaceMatchDTO importantFaceMatchDTO, Query query) {
        return null;
    }


    @Override
    public IPage<PeopleCaptureResponse> listPage(PeopleCaptureQueryRequest queryRequest, Query query) {
        //分页查询
        LambdaQueryWrapper<PmgBatFaceCaptureEventData> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(Objects.nonNull(queryRequest.getParkId())){
            lambdaQueryWrapper.eq(PmgBatFaceCaptureEventData::getParkId,queryRequest.getParkId());
        }
        if(StringUtils.isNotBlank(queryRequest.getName())){
            lambdaQueryWrapper.like(PmgBatFaceCaptureEventData::getFaceInfoName,queryRequest.getName());
        }

        if(Objects.nonNull(queryRequest.getType())){
            if(StringUtils.isNotBlank(queryRequest.getType())){
                lambdaQueryWrapper.eq(PmgBatFaceCaptureEventData::getFaceGroupCode,queryRequest.getType());
            }
        }else {
            lambdaQueryWrapper.isNull(PmgBatFaceCaptureEventData::getFaceGroupCode);
        }
      if(Objects.nonNull(queryRequest.getStartTime())){
            lambdaQueryWrapper.ge(PmgBatFaceCaptureEventData::getFaceTime, queryRequest.getStartTime());
            lambdaQueryWrapper.le(PmgBatFaceCaptureEventData::getFaceTime, queryRequest.getEndTime());
        }

        lambdaQueryWrapper.orderByDesc(PmgBatFaceCaptureEventData::getId);
        IPage<PmgBatFaceCaptureEventData> iPage = this.page(Condition.getPage(query),lambdaQueryWrapper);

        //组装返回response
        IPage<PeopleCaptureResponse> pageVo = new Page(iPage.getCurrent(), iPage.getSize(), iPage.getTotal());
        List<PeopleCaptureResponse> records = this.listVO(iPage.getRecords());
        pageVo.setRecords(records);
        return pageVo;
    }

    private  List<PeopleCaptureResponse> listVO(List<PmgBatFaceCaptureEventData> list) {

        return (List)list.stream().map(entity->{
            PmgBatParkInfo pmgBatParkInfo =   pmgBatParkInfoService.lambdaQuery().
                    select(PmgBatParkInfo::getId,PmgBatParkInfo::getParkName).eq(PmgBatParkInfo::getId,entity.getParkId()).one();
            PeopleCaptureResponse peopleCaptureResponse = new PeopleCaptureResponse();
            peopleCaptureResponse.setParkName(pmgBatParkInfo.getParkName());
            peopleCaptureResponse.setPeoplePic(entity.getFaceUrl());
            peopleCaptureResponse.setPersonTypeName(PersonGroupNameEnum.getDescByCode(entity.getFaceGroupCode()));
            peopleCaptureResponse.setPersonName(entity.getFaceInfoName());
            if(StringUtils.isNotBlank(entity.getFaceTime())){
                if(entity.getFaceTime().contains("T")){
                    peopleCaptureResponse.setCaptureTime(DateUtils.timeOfStrToDate(entity.getFaceTime()));
                }else {
                    peopleCaptureResponse.setCaptureTime(DateUtils.parseDate(DateUtils.DATE_TIME_PATTERN,entity.getFaceTime()));
                }
            }
            peopleCaptureResponse.setCaptureLocation(entity.getCn());
            return peopleCaptureResponse;
        }).collect(Collectors.toList());
    }


}
