package com.zcloud.personnel.positioning.command;

import com.zcloud.personnel.positioning.dto.TerminalUpdateCmd;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalDO;
import com.zcloud.personnel.positioning.persistence.repository.TerminalRepository;
import com.alibaba.cola.exception.BizException;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * web-app
 *
 * @Author fangjiakai
 * @Date 2026-07-07
 */
@Component
@AllArgsConstructor
public class TerminalUpdateExe {
    private final TerminalRepository terminalRepository;
    private final FindsPendingSyncService findsPendingSyncService;

    @Transactional(rollbackFor = Exception.class)
    public void execute(TerminalUpdateCmd cmd) {
        if (cmd == null || cmd.getId() == null) {
            throw new BizException("终端ID不能为空");
        }
        TerminalDO terminal = terminalRepository.getById(cmd.getId());
        if (terminal == null) {
            throw new BizException("终端不存在");
        }
        Long findsTerminalId = terminal.getFindsTerminalId();
        BeanUtils.copyProperties(cmd, terminal, "findsTerminalId", "syncStatus", "syncToken", "lastSyncTime", "rawJson");
        terminal.setFindsTerminalId(findsTerminalId);
        terminal.setSyncStatus(FindsPendingSyncService.STATUS_WAIT);
        terminal.setSyncToken(FindsSyncToken.next());
        boolean res = terminalRepository.updateById(terminal);
        if (!res) {
            throw new BizException("修改失败");
        }
        findsPendingSyncService.scheduleTerminal(terminal.getId());
    }
}
