package com.usky.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.meet.utils.TimeUtils;
import com.usky.meeting.domain.MeetingDevice;
import com.usky.meeting.domain.MeetingFace;
import com.usky.meeting.mapper.MeetingDeviceMapper;
import com.usky.meeting.mapper.MeetingFaceMapper;
import com.usky.meeting.repository.MeetingRoomRepository;
import com.usky.meeting.server.FaceContrastServer;
import com.usky.meeting.service.MeetingFaceService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.meeting.service.vo.FaceResultVO;
import com.usky.meeting.service.vo.MeetingFaceRequestVO;
import com.usky.meeting.service.vo.MeetingFaceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyj
 * @since 2024-03-08
 */
@Service
public class MeetingFaceServiceImpl extends AbstractCrudService<MeetingFaceMapper, MeetingFace> implements MeetingFaceService {

    @Autowired
    FaceContrastServer faceContrastServer;
    @Autowired
    private MeetingRoomRepository dmMeetingRoomRepository;
    @Autowired
    private MeetingDeviceMapper deviceMapper;

    @Override
    public MeetingFaceVO vef(MeetingFaceRequestVO requestVO) {

        String deviceCode = requestVO.getDeviceCode();
        Integer tenantId;
        if(StringUtils.isNotBlank(deviceCode)){
            LambdaQueryWrapper<MeetingDevice> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MeetingDevice::getDeviceCode,requestVO.getDeviceCode());
            tenantId = deviceMapper.selectOne(queryWrapper).getTenantId();
        }else{
            tenantId = SecurityUtils.getTenantId();
        }

        List<MeetingFace> faceList = lambdaQuery().eq(MeetingFace::getTenantId,tenantId).orderByDesc(MeetingFace::getVefNum).list();
        MeetingFaceVO faceState = new MeetingFaceVO();
        MeetingFaceVO faceState1 = new MeetingFaceVO();
        faceState.setTenantId(tenantId);
        faceState1.setTenantId(tenantId);
        // 如果人脸库为空,则第一次登录为录入人脸
        if (!faceList.isEmpty()){
            //人脸校验
            if(StringUtils.isNotBlank(requestVO.getImageBase())){
                int faceLength = faceList.size();
                for (MeetingFace face : faceList) {
                    FaceResultVO faceResult = faceContrastServer.faceContrast(face.getFaceBase(), requestVO.getImageBase());
                    // 是否比对成功
                    if (faceResult.getCode() == MeetingFaceVO.SUCCESS_CODE ){
                        // 相似度是否大于80
                        if (faceResult.getScore() > MeetingFaceVO.SATISFY_SCORE){
                            if (face.getFaceStatus() == 0){
                                // 成功
                                lambdaUpdate().set(MeetingFace::getVefNum,face.getVefNum()+1).eq(MeetingFace::getFid,face.getFid()).update();
                                faceState.setMsg(TimeUtils.timeQuantum()+"好,"+face.getFaceName());
                                faceState.setFaceName(face.getFaceName());
                                faceState.setUserId(face.getUserId());
                                faceState.setCode(MeetingFaceVO.SUCCESS_CODE);
                                faceState.setFaceBase(requestVO.getImageBase());
                                faceState.setVefType(1);
                                return faceState;
                            }else {
                                // 失败 人脸被禁用
                                lambdaUpdate().set(MeetingFace::getVefNum,face.getVefNum()+1).eq(MeetingFace::getFid,face.getFid()).update();
                                faceState1.setMsg("当前人脸被禁用");
                                faceState1.setFaceName(face.getFaceName());
                                faceState1.setUserId(face.getUserId());
                                faceState1.setCode(MeetingFaceVO.FORBIDDEN_FACE);
                                faceState1.setFaceBase(requestVO.getImageBase());
                                faceState1.setVefType(1);
                                // 就算上一张人脸被禁用还得往下执行
                                // 可能当前用户存在多张人脸，
                                if (faceLength == 1){
                                    return faceState1;
                                }
                                faceLength --;
                            }
                        }else {
                            // 人脸库没有检测到人脸
                            if (faceLength == 1){
                                // 判断当前人脸是否被禁用，如被禁用，提示被禁用
                                // 禁用优先级大于 没有检测到人脸
                                faceState.setMsg("人脸不匹配，请联系管理员");
                                faceState.setCode(MeetingFaceVO.NOT_FOUND_FACE);
                                faceState.setFaceBase(requestVO.getImageBase());
                                faceState.setVefType(1);
                                return faceState;
                            }
                            faceLength --;
                        }
                    }else {
                        // 接口返回异常
                        faceState.setMsg("人脸验证接口返回异常");
                        faceState.setCode(MeetingFaceVO.FACE_ERROR);
                        return faceState;
                    }
                }
            }else if(StringUtils.isNotBlank(requestVO.getCardNum())){  //卡号校验
                int faceLength = faceList.size();
                String cardNum = requestVO.getCardNum();
                for (MeetingFace face : faceList) {
                    if(cardNum.equals(face.getCardNum())){
                        // 成功
                        lambdaUpdate().set(MeetingFace::getVefNum,face.getVefNum()+1).eq(MeetingFace::getFid,face.getFid()).update();
                        faceState.setMsg(TimeUtils.timeQuantum()+"好,"+face.getFaceName());
                        faceState.setFaceName(face.getFaceName());
                        faceState.setUserId(face.getUserId());
                        faceState.setCode(MeetingFaceVO.SUCCESS_CODE);
                        faceState.setCardNum(requestVO.getCardNum());
                        faceState.setVefType(2);
                        return faceState;
                    }else {
                        // 失败 卡号不存在
                        lambdaUpdate().set(MeetingFace::getVefNum,face.getVefNum()+1).eq(MeetingFace::getFid,face.getFid()).update();
                        faceState1.setMsg("当前卡号不存在");
                        faceState1.setCode(MeetingFaceVO.NOT_FOUND_FACE);
                        faceState1.setCardNum(requestVO.getCardNum());
                        faceState1.setVefType(2);
                        // 就算上一张卡号没有找到还得往下执行
                        if (faceLength == 1){
                            return faceState1;
                        }
                        faceLength --;
                    }
                }
            }


        }
        // 空异常
        if(StringUtils.isNotBlank(requestVO.getImageBase())){
            faceState.setMsg("人脸不存在，请联系管理员");
            faceState.setCode(MeetingFaceVO.NULL_ERROR);
            faceState.setFaceBase(requestVO.getImageBase());
            faceState.setVefType(1);
        }else if(StringUtils.isNotBlank(requestVO.getCardNum())){
            faceState.setMsg("卡号不存在，请联系管理员");
            faceState.setCode(MeetingFaceVO.NULL_ERROR);
            faceState.setFaceBase(requestVO.getCardNum());
            faceState.setVefType(2);
        }

        return faceState;
    }


//    public MeetingFaceVO initFace(String imageBase){
//        MeetingFaceVO faceResult = new MeetingFaceVO();
//        MeetingFace face = new MeetingFace();
//        face.setFaceBase(imageBase);
//        face.setCreateTime(LocalDateTime.now());
//        face.setVefNum(0);
//        face.setFaceName("admin");
//        face.setFaceStatus(0);
//        boolean save = save(face);
//        faceResult.setMsg("人脸初始化"+(save?"成功":"失败")+","+(save?"请验证登录":"请稍后再试"));
//        faceResult.setFaceName(face.getFaceName());
//        return faceResult;
//    }
}
