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

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.MdmAppPushUserDao;
import com.skr.mdm.dto.AppPushCallBackInfoDTO;
import com.skr.mdm.entity.MdmAppPushUserDO;
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 14:49
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.APP_PUSH_CB)
public class AppPushServiceImpl implements CmdHandlerService {

    @Autowired
    private MdmAppPushUserDao appPushUserDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            List<AppPushCallBackInfoDTO> appPushCallBackInfoDTOList = JSONUtil.toList(JSONUtil.parseArray(data), AppPushCallBackInfoDTO.class);
            List<Integer> cidList = new ArrayList<>(appPushCallBackInfoDTOList.size());
            appPushCallBackInfoDTOList.forEach(appPushCallBackInfoDTO -> {
                new LambdaUpdateChainWrapper<>(appPushUserDao)
                        .set(appPushCallBackInfoDTO.getState() != null, MdmAppPushUserDO::getState, appPushCallBackInfoDTO.getState())
                        .set(StringUtils.isNotBlank(appPushCallBackInfoDTO.getFailInfo()), MdmAppPushUserDO::getFailInfo, appPushCallBackInfoDTO.getFailInfo())
                        .eq(MdmAppPushUserDO::getAppPushId, appPushCallBackInfoDTO.getAppPushId())
                        .eq(MdmAppPushUserDO::getEquipmentId, equipmentId)
                        .update();
                cidList.add(appPushCallBackInfoDTO.getCid());
            });
            return ResponseResult.success(JSONUtil.toJsonStr(cidList));
        } catch (Exception e) {
            log.error("应用推送回调异常:" + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }

}
