package cn.iocoder.yudao.module.system.controller.admin.equipment;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.infra.api.websocket.WebSocketSenderApi;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.attendancemachine.*;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.userExt.UsersExtRespVO;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.websocket.UpdatePasswordVO;
import cn.iocoder.yudao.module.system.controller.admin.equipment.vo.websocket.WebsocketBaseVO;
import cn.iocoder.yudao.module.system.dal.dataobject.equipment.DistributeRecordDO;
import cn.iocoder.yudao.module.system.service.equipment.AttendanceMachineService;
import cn.iocoder.yudao.module.system.service.equipment.DistributeRecordService;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Collections;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.REQUEST_FAILURE;


@Tag(name = "管理后台 - 考勤设备")
@RestController
@RequestMapping("/system/attendance-machine")
@Validated
public class AttendanceMachineController {

    @Resource
    private AttendanceMachineService attendanceMachineService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private WebSocketSenderApi webSocketSenderApi;

    @Resource
    private DistributeRecordService recordService;

    @PostMapping("/create")
    @Operation(summary = "创建考勤设备")
    @PreAuthorize("@ss.hasPermission('system:attendance-machine:create')")
    public CommonResult<Long> createAttendanceMachine(@Valid @RequestBody AttendanceMachineSaveReqVO createReqVO) {
        return success(attendanceMachineService.createAttendanceMachine(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新考勤设备")
    @PreAuthorize("@ss.hasPermission('system:attendance-machine:update')")
    public CommonResult<Boolean> updateAttendanceMachine(@Valid @RequestBody AttendanceMachineSaveReqVO updateReqVO) {

        attendanceMachineService.updateAttendanceMachine(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-password")
    @Operation(summary = "考勤设备密码修改")
    @PreAuthorize("@ss.hasPermission('system:attendance-machine:update')")
    public CommonResult<Boolean> updateAttendanceMachine(@Valid @RequestBody AttendanceMachinePasswordVO updateReqVO) {

        // 将密码信息 储存在redis中
        stringRedisTemplate.opsForValue().set(updateReqVO.getDeviceNo(), updateReqVO.getOldPassword() + "-" + updateReqVO.getNewPassword());

        String requestId = IdWorker.get32UUID();
        // 设备修改密码命令信息
        UpdatePasswordVO passwordVO = new UpdatePasswordVO().setOld_password(updateReqVO.getOldPassword())
                .setNew_password(updateReqVO.getNewPassword());
        WebsocketBaseVO data = new WebsocketBaseVO()
                .setFrom("")
                .setTo(updateReqVO.getDeviceNo())
                .setExtra(requestId + "_" + getLoginUserId())
                .setData(passwordVO);

        // 设置 设备下发记录
        DistributeRecordDO recordDO = new DistributeRecordDO();
        recordDO.setRequestId(requestId);
        recordDO.setDeviceNo(updateReqVO.getDeviceNo());
        recordDO.setUserId(getLoginUserId());
        recordDO.setType(3);
        recordDO.setResult("通讯失败");

        // 更新下发记录信息
        recordService.createDistributeRecord(Collections.singletonList(recordDO));

        // 设备租户ID
        TenantContextHolder.setTenantId(1L);
        // 发送修改密码命令给设备
        webSocketSenderApi.sendSN(updateReqVO.getDeviceNo(), "attendance-message-send", JsonUtils.toJsonString(data));

        Long startTime = System.currentTimeMillis();
        while (true) {

            if (stringRedisTemplate.opsForValue().get(updateReqVO.getDeviceNo()) == null) {

                return success(true);
            }else if ("false".equals(stringRedisTemplate.opsForValue().get(updateReqVO.getDeviceNo()))) {

                Integer code = Integer.valueOf(stringRedisTemplate.opsForValue().get(updateReqVO.getDeviceNo() + "msg").split("_")[0]);
                String msg = stringRedisTemplate.opsForValue().get(updateReqVO.getDeviceNo() + "msg").split("_")[1];

                // 清楚 redis缓存
                stringRedisTemplate.delete(updateReqVO.getDeviceNo());
                stringRedisTemplate.delete(updateReqVO.getDeviceNo() + "msg");
                return error(code, msg);
            }

            Long currentTime = System.currentTimeMillis();
            if (currentTime - startTime > 5000) {

                throw exception(REQUEST_FAILURE);
            }
        }
    }

    @PutMapping("/update-user")
    @Operation(summary = "考勤设备用户下发")
    @PreAuthorize("@ss.hasPermission('system:attendance-machine:update')")
    public CommonResult<Boolean> addUserToAttendanceMachine(@Valid @RequestBody AddUserToAttendanceMachineVO addReqVO) {

        attendanceMachineService.addUserToAttendanceMachine(addReqVO);
        return success(true);
    }

    @GetMapping("/getUserByDeviceNo")
    @Operation(summary = "获得设备已下发的用户列表")
    @PreAuthorize("@ss.hasPermission('system:attendance-machine:query')")
    public CommonResult<PageResult<UsersExtRespVO>> getUserByDeviceNo(UserExtPageReqVO pageReqVO) {

        PageResult<UsersExtRespVO> userPage = attendanceMachineService.getUserByDeviceNo(pageReqVO);

        return success(userPage);
    }

    @GetMapping("/get")
    @Operation(summary = "获得考勤设备")
    @Parameter(name = "assetsNo", description = "资产编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:attendance-machine:query')")
    public CommonResult<AttendanceMachineRespVO> getAttendanceMachine(@RequestParam("assetsNo") String assetsNo) {

        AttendanceMachineRespVO attendanceMachine = attendanceMachineService.getAttendanceMachine(assetsNo);

        return success(attendanceMachine);
    }

    @GetMapping("/page")
    @Operation(summary = "获得考勤设备分页")
    @PreAuthorize("@ss.hasPermission('system:attendance-machine:query')")
    public CommonResult<PageResult<AttendanceMachineRespVO>> getAttendanceMachinePage(@Valid AttendanceMachinePageReqVO pageReqVO) {

        PageResult<AttendanceMachineRespVO> pageResult = attendanceMachineService.getAttendanceMachinePage(pageReqVO);

        return success(pageResult);
    }
}