package com.skr.mdm.service.impl;

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.SysSendMsgUserDao;
import com.skr.mdm.dto.CmdCallBackDTO;
import com.skr.mdm.entity.SysSendMsgUserDO;
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.List;

/**
 * @author nfq
 * @date 2020/8/7 17:07
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.ISSUE)
public class CommonCallbackServiceImpl implements CmdHandlerService {

    @Autowired
    private SysSendMsgUserDao sysSendMsgUserDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            // 统一回调接口
            JSONArray jsonArray = JSONUtil.parseArray(data);
            List<CmdCallBackDTO> cmdCallBackDTOList = JSONUtil.toList(jsonArray, CmdCallBackDTO.class);
            cmdCallBackDTOList.forEach(cmdCallBackDTO -> {
                LambdaUpdateChainWrapper<SysSendMsgUserDO> updateChainWrapper = new LambdaUpdateChainWrapper<>(sysSendMsgUserDao);
                updateChainWrapper
                        .set(SysSendMsgUserDO::getState, cmdCallBackDTO.getState())
                        .eq(SysSendMsgUserDO::getSendMsgId, cmdCallBackDTO.getId())
                        .eq(SysSendMsgUserDO::getEquipmentId, equipmentId)
                        .update();
            });
            return ResponseResult.success();
        } catch (Exception e) {
            log.error("指令统一回调接口异常：" + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
