package cn.iocoder.yudao.module.system.api.equipment;

import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.userExt.UsersExtSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.websocket.AddUserVO;
import cn.iocoder.yudao.module.system.dal.dataobject.equipment.AttendanceMachineDO;
import cn.iocoder.yudao.module.system.service.equipment.AttendanceMachineService;
import cn.iocoder.yudao.module.system.service.equipment.UsersExtService;
import cn.iocoder.yudao.module.system.service.websocket.WebsocketService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class UsersExtApiImpl implements UsersExtApi{

    @Resource
    private UsersExtService usersExtService;

    @Resource
    private AttendanceMachineService attendanceMachineService;

    @Resource
    private WebsocketService websocketService;

    @Override
    public void createUsersExt(Long userId, String userName, Long deptId, String faceImg) {

        // 查询当前部门下 是否存在考勤设备
        List<AttendanceMachineDO> deviceList = attendanceMachineService.getListByDeptId(deptId);
        List<String> deviceNos = new ArrayList<>();
        try {

            for (AttendanceMachineDO machineDO : deviceList) {

                // 设置下发命令
                AddUserVO addUserVO = new AddUserVO()
                        .setCmd("addUser")
                        .setUser_id(String.valueOf(userId))
                        .setName(userName)
                        .setFace_template(faceImg)
                        .setId_valid("");

                // 发送指令至 考勤设备 下发员工
                websocketService.sendSn(machineDO.getDeviceNo(), addUserVO, 1);

                deviceNos.add(machineDO.getDeviceNo());
            }
        } finally {

            UsersExtSaveReqVO saveReqVO = new UsersExtSaveReqVO()
                    .setUserId(userId)
                    .setDeptId(deptId)
                    .setFaceImg(faceImg)
                    .setAttendanceMachineNos(deviceNos);
            // 插入用户拓展信息
            usersExtService.createUsers(saveReqVO);
        }
    }
}
