package com.sv.socket.event;

import Net.PC15.Command.CommandDetial;
import Net.PC15.Connector.ConnectorAllocator;
import Net.PC15.Connector.E_ControllerType;
import Net.PC15.Connector.TCPClient.TCPClientDetial;
import Net.PC15.FC8800.Command.Door.CloseDoor;
import Net.PC15.FC8800.Command.Door.OpenDoor;
import Net.PC15.FC8800.Command.Door.Parameter.OpenDoor_Parameter;
import Net.PC15.FC8800.Command.Door.Parameter.RemoteDoor_Parameter;
import Net.PC15.FC8800.FC8800Identity;
import com.enums.FaceRecognizeEnum;
import com.sv.dto.api.MemberMessageDto;
import com.sv.entity.Device;
import com.sv.entity.Member;
import com.sv.entity.MemberEnterVenueLog;
import com.sv.entity.face.FaceRecognizeResponse;
import com.sv.service.api.MemberEnterVenueLogService;
import com.sv.service.api.MemberService;
import com.sv.service.api.VenueService;
import com.sv.service.common.FaceService;
import com.sv.socket.DeviceSocket;
import com.ydd.framework.core.common.dto.ResponseDTO;
import com.ydd.framework.core.common.utils.JsonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;

@Component
public class SocketMessageListener implements ApplicationListener<SocketMessageEvent> {

    @Resource
    private MemberEnterVenueLogService memberEnterVenueLogService;

    @Resource
    private MemberService memberService;
    @Resource
    private VenueService venueService;
    private final Logger logger = LoggerFactory.getLogger(SocketMessageListener.class);

    @Value("${door.ip}")
    private String ip;

    @Value("${door.port}")
    private Integer port;

    @Value("${door.sn}")
    private String sn;

    @Value("${door.pwd}")
    private String pwd;

    @Value("${nettym.url}")
    private String url;

    @Resource
    private RestTemplate restTemplate;

    @Async
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized void onApplicationEvent(SocketMessageEvent event) {
        Device device = event.getDevice();
        FaceRecognizeResponse response = JsonMapper.nonNullMapper().fromJson(event.getMessage(), FaceRecognizeResponse.class);
        if (FaceRecognizeEnum.RECOGNIZED.name.equals(response.getType())) {
            //识别成功
            if (response.getPerson() != null) {
                if (device.getId() == 1) {
                    //进门

                    enter(device, response);
                } else if (device.getId() == 2) {
                    //出门
                    out(device, response);
                }
            }
        }
    }

    public void enter(Device device, FaceRecognizeResponse response) {
        try {
            int code = 1;
            Member member = memberService.findByFaceId(response.getPerson().getId());
            if (member != null) {
                //最后进场记录
                MemberEnterVenueLog enterVenueLog = memberEnterVenueLogService.findMemberLastLog(member.getId(), device.getVenueId());
                if (enterVenueLog != null) {
                    //有记录 查看 最后一次是否是出场
                    if (enterVenueLog.getType() == 1) {
                        //是出场 不用限制
                    } else {
                        //是进场 判断上次进场距离现在多久
                        Date date = new Date();
                        if (memberEnterVenueLogService.countEnterByDate(member.getId(), device.getVenueId(), date) < 2) {
                            //当天没有过 第二次的连续入场
                        } else {
                            //入场失败
                            code = -1;
                        }
                    }
                }
                MemberMessageDto memberMessageDto = new MemberMessageDto();
                memberMessageDto.setAmount(member.getMoney());
                memberMessageDto.setName(member.getName());
                memberMessageDto.setAvatar(member.getAvatar());
                memberMessageDto.setMobile(member.getMobile());
                memberMessageDto.setPlaceName("");

                if (code > 0) {
                    int status = venueService.enterVenue(response.getPerson().getId(), device.getId()).getStatus();
                    if (status >= 0) {
                        memberMessageDto.setCode(1);
                        if (status == 1) {
                            memberMessageDto.setCardName("会员卡");
                        }
                        logger.info(member.getId() + "入场成功:" + member.getMoney().toString());

                    } else {
                        logger.info(member.getId() + "入场失败:" + member.getMoney().toString());
                        memberMessageDto.setCode(0);
                    }
                } else {
                    logger.info(member.getId() + "入场失败:连续入场");
                    memberMessageDto.setCode(0);
                }
//                HttpHeaders headers = new HttpHeaders();
//                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//                headers.setContentType(type);
//                HttpEntity<String> jsonEntity = new HttpEntity<>(JsonMapper.nonNullMapper().toJson(memberMessageDto), headers);
//                restTemplate.postForObject(url, jsonEntity, ResponseDTO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void out(Device device, FaceRecognizeResponse response) {
        Member member = memberService.findByFaceId(response.getPerson().getId());
        if (member != null) {
            //出场 不用判断直接出
            MemberEnterVenueLog memberEnterVenueLog = new MemberEnterVenueLog();
            memberEnterVenueLog.setOrderSn("");
            memberEnterVenueLog.setType(1);
            memberEnterVenueLog.setMemberId(member.getId());
            memberEnterVenueLog.setVeneuType(device.getVenueType());
            memberEnterVenueLog.setVenueId(device.getVenueId());
            memberEnterVenueLog.setPlatformId(member.getPlatformId());
            memberEnterVenueLogService.save(memberEnterVenueLog);
            logger.info("用户" + member.getNickname() + "出场");
        }
    }

}
