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

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.ClientUpgradeUserDao;
import com.skr.mdm.dto.ClientUpgradeInfoDTO;
import com.skr.mdm.entity.ClientUpgradeUserDO;
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 15:29
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.APP_UPGRADE)
public class ClientUpgradeServiceImpl implements CmdHandlerService {

    @Autowired
    private ClientUpgradeUserDao clientUpgradeUserDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            // 客户端升级回调
            List<ClientUpgradeInfoDTO> clientUpgradeInfoDTOList = JSONUtil.toList(JSONUtil.parseArray(data), ClientUpgradeInfoDTO.class);
            List<Integer> cidList = new ArrayList<>(clientUpgradeInfoDTOList.size());
            clientUpgradeInfoDTOList.forEach(clientUpgradeInfoDTO -> {
                new LambdaUpdateChainWrapper<>(clientUpgradeUserDao)
                        .set(clientUpgradeInfoDTO.getState() != null, ClientUpgradeUserDO::getState, clientUpgradeInfoDTO.getState())
						.set(clientUpgradeInfoDTO.getPauseStatus() != null, ClientUpgradeUserDO::getPauseStatus, clientUpgradeInfoDTO.getPauseStatus())
						.set(StringUtils.isNotBlank(clientUpgradeInfoDTO.getFailInfo()), ClientUpgradeUserDO::getFailInfo, clientUpgradeInfoDTO.getFailInfo())
                        .eq(ClientUpgradeUserDO::getClientUpgradeId, clientUpgradeInfoDTO.getClientUpgradeId())
                        .eq(ClientUpgradeUserDO::getEquipmentId, equipmentId)
                        .update();
                cidList.add(clientUpgradeInfoDTO.getCid());
            });
            return ResponseResult.success(JSONUtil.toJsonStr(cidList));
        } catch (Exception e) {
            log.error("客户端升级回调异常：" + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
