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

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.skr.mdm.annotation.CmdHandler;
import com.skr.mdm.constant.CmdTypeConstants;
import com.skr.mdm.dao.LogUserDao;
import com.skr.mdm.dto.UserLogConfirmDTO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.entity.LogUserDO;
import com.skr.mdm.service.CmdHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @author nfq
 * @date 2021/11/04 17:25
 */
@CmdHandler(cmdType = CmdTypeConstants.LOG_CONFIRM)
@Slf4j
public class UserLogConfirmServiceImpl implements CmdHandlerService {

    @Autowired
    private LogUserDao logUserDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {

        List<UserLogConfirmDTO> userLogConfirmDTOList = JSONUtil.toList(JSONUtil.parseArray(data), UserLogConfirmDTO.class);
        if (CollectionUtils.isEmpty(userLogConfirmDTOList)) {
            return ResponseResult.failure();
        }
        List<UserLogConfirmDTO> userLogConfirmDTOS = new ArrayList<>(userLogConfirmDTOList.size());
        userLogConfirmDTOList.forEach(userLogConfirmDTO -> {
            String date = "";
            if (userLogConfirmDTO.getOperateTime() != null) {
                date = DateUtil.format(DateUtil.date(userLogConfirmDTO.getOperateTime()), "yyyy-MM-dd HH:mm:ss");
            }
            Long count = new LambdaQueryChainWrapper<>(logUserDao)
                    .eq(LogUserDO::getEquipmentId, equipmentId)
                    .eq(LogUserDO::getLogType, userLogConfirmDTO.getLogType())
                    .eq(LogUserDO::getCid, userLogConfirmDTO.getCid())
                    .eq(StringUtils.isNotBlank(date), LogUserDO::getOperateTime, date)
                    .count();
            if (count > 0) {
                userLogConfirmDTOS.add(userLogConfirmDTO);
            }
        });
        return ResponseResult.success(userLogConfirmDTOS);
    }
}