package com.skr.mdm.service.impl.cmd;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.skr.mdm.annotation.CmdHandler;
import com.skr.mdm.constant.CmdTypeConstants;
import com.skr.mdm.dao.DeviceInstructLockscreenDao;
import com.skr.mdm.dto.CmdCallBackDTO;
import com.skr.mdm.entity.DeviceInstructLockscreenDO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.service.CmdHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author nfq
 * @date 2020/8/3 18:38
 */
@Slf4j
@CmdHandler(cmdType = {CmdTypeConstants.LOCK_SCREEN, CmdTypeConstants.UNLOCK})
public class LockUnlockServiceImpl implements CmdHandlerService {

    @Autowired
    private DeviceInstructLockscreenDao lockscreenDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            // 锁屏解锁回调
            JSONArray jsonArray = JSONUtil.parseArray(data);
            List<CmdCallBackDTO> cmdCallBackDTOList = JSONUtil.toList(jsonArray, CmdCallBackDTO.class);
            List<Integer> cidList = new ArrayList<>(cmdCallBackDTOList.size());
            cmdCallBackDTOList.forEach(cmdCallBackDTO -> {
                LambdaUpdateChainWrapper<DeviceInstructLockscreenDO> updateChainWrapper = new LambdaUpdateChainWrapper<>(lockscreenDao);
                updateChainWrapper
                        .set(DeviceInstructLockscreenDO::getState, cmdCallBackDTO.getState())
                        .set(StringUtils.isNotBlank(cmdCallBackDTO.getRandomCode()),DeviceInstructLockscreenDO::getOfflineUnlockCode, cmdCallBackDTO.getRandomCode())
                        .eq(DeviceInstructLockscreenDO::getMessageId, cmdCallBackDTO.getId())
                        .eq(DeviceInstructLockscreenDO::getEquipmentId, equipmentId)
                        .update();
                cidList.add(cmdCallBackDTO.getCid());
            });
            return ResponseResult.success(JSONUtil.toJsonStr(cidList));
        } catch (Exception e) {
            log.error("锁屏解锁回调异常: " + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}