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

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.skr.mdm.annotation.CmdHandler;
import com.skr.mdm.constant.CmdTypeConstants;
import com.skr.mdm.dao.DeviceInstructRestoreFactoryDao;
import com.skr.mdm.dto.RestoreFactoryDTO;
import com.skr.mdm.entity.DeviceInstructRestoreFactoryDO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.service.CmdHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @className: EquipmentRestoreFactoryServiceImpl
 * @outher:    Tty
 * @Date:      2020/11/26 18:13
 * @Description: 恢复出厂设置
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.RESTORE_FACTORY)
public class EquipmentRestoreFactoryServiceImpl implements CmdHandlerService {

    @Autowired
    private DeviceInstructRestoreFactoryDao deviceInstructRestoreFactoryDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            // 上传恢复出厂
            JSONArray jsonArray = JSONUtil.parseArray(data);
            List<RestoreFactoryDTO> restoreFactoryDTOList = JSONUtil.toList(jsonArray, RestoreFactoryDTO.class);
            List<DeviceInstructRestoreFactoryDO> restoreFactoryDOList = new ArrayList<>(restoreFactoryDTOList.size());
            List<Integer> cidList = new ArrayList<>(restoreFactoryDTOList.size());
			restoreFactoryDTOList.forEach(restoreFactoryDTO -> {
				DeviceInstructRestoreFactoryDO restoreFactoryDO = new DeviceInstructRestoreFactoryDO();
				restoreFactoryDO.setMessageId(restoreFactoryDTO.getFactoryId().toString());
				restoreFactoryDO.setState(restoreFactoryDTO.getState());
				restoreFactoryDO.setEquipmentId(equipmentId);
				restoreFactoryDOList.add(restoreFactoryDO);
				cidList.add(restoreFactoryDTO.getCid());
			});
			deviceInstructRestoreFactoryDao.updateBatchIdsList(restoreFactoryDOList);
            return ResponseResult.success(JSONUtil.toJsonStr(cidList));
        } catch (Exception e) {
            log.error("上传恢复出厂异常: " + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
