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

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.ContentInformUserDao;
import com.skr.mdm.dto.InformInfoDTO;
import com.skr.mdm.entity.ContentInformUserDO;
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;

/**
 * @author nfq
 * @date 2022/03/23 15:46
 */
@CmdHandler(cmdType = CmdTypeConstants.PUSH_INFORM)
@Slf4j
public class InformServiceImpl implements CmdHandlerService {

    @Autowired
    private ContentInformUserDao contentInformUserDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            JSONArray jsonArray = JSONUtil.parseArray(data);
            List<InformInfoDTO> informInfoDTOList = JSONUtil.toList(jsonArray, InformInfoDTO.class);
            List<Integer> cidList = new ArrayList<>(informInfoDTOList.size());
            informInfoDTOList.forEach(informInfoDTO -> {
                if (informInfoDTO.getState() != null || informInfoDTO.getReadTime() != null) {
                    new LambdaUpdateChainWrapper<>(contentInformUserDao)
                            .set(informInfoDTO.getState() != null, ContentInformUserDO::getState, informInfoDTO.getState())
                            .set(informInfoDTO.getReadTime() != null, ContentInformUserDO::getReadTime, informInfoDTO.getReadTime())
                            .eq(ContentInformUserDO::getInformId, informInfoDTO.getInformId())
                            .eq(ContentInformUserDO::getEquipmentId, equipmentId)
                            .update();
                }
                cidList.add(informInfoDTO.getCid());
            });
            return ResponseResult.success(JSONUtil.toJsonStr(cidList));
        } catch (Exception e) {
            log.error("通知回调异常: " + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
