package jnpf.attendance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jnpf.attendance.mapper.AttendanceGroupUserMapper;
import jnpf.attendance.mapper.AttendanceUserFaceMapper;
import jnpf.attendance.service.AttenceMachineService;
import jnpf.attendance.service.AttendanceUserFaceService;
import jnpf.entity.attendance.AttendanceMachineManage;
import jnpf.entity.attendance.AttendanceRuleScope;
import jnpf.entity.attendance.AttendanceUserFace;
import jnpf.enums.attendance.ScopeBizType;
import jnpf.model.attendance.dto.UserFaceDto;
import jnpf.model.attendance.dto.MachineDealDto;
import jnpf.model.attendance.vo.UserFaceVo;
import jnpf.util.*;
import jnpf.util.attendance.RuleScopeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 人脸服务实现
 *
 * @author yanwenfu
 * @create 2024-04-09
 */
@Slf4j
@Service
public class AttendanceUserFaceServiceImpl implements AttendanceUserFaceService {

    @Resource
    private AttendanceUserFaceMapper attendanceUserFaceMapper;
    @Resource
    private AttenceMachineService attenceMachineService;
    @Resource
    private AttendanceGroupUserMapper attendanceGroupUserMapper;
    @Resource
    private RuleScopeUtil ruleScopeUtil;

    @Override
    public UserFaceVo getUserFace(String userId) {

        LambdaQueryWrapper<AttendanceUserFace> queryWrapper = new LambdaQueryWrapper<AttendanceUserFace>()
                .eq(AttendanceUserFace::getUserId, userId)
                .eq(AttendanceUserFace::getDeleteMark, ConstantUtil.NUM_FALSE);
        AttendanceUserFace userFace = attendanceUserFaceMapper.selectOne(queryWrapper);
        return JsonUtil.getJsonToBean(userFace, UserFaceVo.class);
    }

    @Override
    public void addUserFace(UserFaceDto userFaceDto) {

        AttendanceUserFace userFace = JsonUtil.getJsonToBean(userFaceDto, AttendanceUserFace.class);
        userFace.setId(FtbUtil.getId());
        attendanceUserFaceMapper.insert(userFace);
        MachineDealDto machineDealDto = new MachineDealDto(userFaceDto.getUserId(), ConstantUtil.CAL_ADD);
        machineDeal(machineDealDto);
    }

    @Override
    public List<String> machineDeal(MachineDealDto machineDealDto) {
        String userId = machineDealDto.getUserId();
        String dealType = machineDealDto.getDealType();
        List<String> machineList = new ArrayList<>();
        // 判断用户当前在哪些考勤组
        List<String> groupIds = getUserGroupList(userId);
        log.error("用户的考勤组：{}", groupIds);
        if (groupIds.isEmpty()) {
            return machineList;
        }
        // 判断是否绑定考勤机
        List<AttendanceRuleScope> scopeList = StringUtil.isNotEmpty(machineDealDto.getOrgId()) ? ruleScopeUtil.selectUserEffectList(userId, machineDealDto.getOrgId(), ScopeBizType.ATTENDANCE_MACHINE)
                : ruleScopeUtil.selectUserEffectList(userId, ScopeBizType.ATTENDANCE_MACHINE, UserProvider.getUser().getTenantId());
        log.error("适配范围：{}", scopeList);
        if (null == scopeList || scopeList.isEmpty()) {
            return machineList;
        }
        List<String> ruleIds = scopeList.stream().map(AttendanceRuleScope::getRuleId).collect(Collectors.toList());
        List<AttendanceMachineManage> list = attenceMachineService.list(new LambdaQueryWrapper<AttendanceMachineManage>()
                .in(AttendanceMachineManage::getId, ruleIds)
                .eq(AttendanceMachineManage::getDeleteMark, ConstantUtil.NUM_FALSE));
        log.error("关联ruleId：{}", ruleIds);
        if (list.isEmpty()) {
            return machineList;
        }
        list.forEach(machine -> {
            if (dealType.equals(ConstantUtil.CAL_REDUCE)) {
                attenceMachineService.deleteUserList(machine.getType(), machine.getMac(), List.of(userId));
                attenceMachineService.sendUserToMachine(machine.getType(), userId, machine.getMac());
            } else if (dealType.equals(ConstantUtil.CAL_DELETE)) {
                attenceMachineService.deleteUserList(machine.getType(), machine.getMac(), List.of(userId));
            } else {
                attenceMachineService.sendUserToMachine(machine.getType(), userId, machine.getMac());
            }
            machineList.add(machine.getMac());
        });
        return machineList;
    }

    private List<String> getUserGroupList(String userId) {

        String groupId = attendanceGroupUserMapper.getSelfGroup(userId);
        return Stream.of(groupId).collect(Collectors.toList());
    }

    @Override
    public void updateUserFace(UserFaceDto userFaceDto) {

        LambdaQueryWrapper<AttendanceUserFace> query = new LambdaQueryWrapper<AttendanceUserFace>()
                .eq(AttendanceUserFace::getUserId, userFaceDto.getUserId());
        AttendanceUserFace userFace = attendanceUserFaceMapper.selectOne(query);
        if (null == userFace) {
            addUserFace(userFaceDto);
        } else {
            LambdaUpdateWrapper<AttendanceUserFace> updateWrapper = new LambdaUpdateWrapper<AttendanceUserFace>()
                    .eq(AttendanceUserFace::getUserId, userFaceDto.getUserId())
                    .set(AttendanceUserFace::getFaceData, userFaceDto.getFaceData());
            attendanceUserFaceMapper.update(null, updateWrapper);
            MachineDealDto machineDealDto = new MachineDealDto(userFaceDto.getUserId(), ConstantUtil.CAL_REDUCE);
            machineDeal(machineDealDto);
        }
    }

    @Override
    public void deleteUserFace(String userId) {

        LambdaUpdateWrapper<AttendanceUserFace> queryWrapper = new LambdaUpdateWrapper<AttendanceUserFace>()
                .eq(AttendanceUserFace::getUserId, userId)
                .eq(AttendanceUserFace::getDeleteMark, ConstantUtil.NUM_FALSE)
                .set(AttendanceUserFace::getDeleteMark, ConstantUtil.NUM_TRUE);
        attendanceUserFaceMapper.update(null, queryWrapper);
    }
}
