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

import cn.hutool.json.JSONArray;
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.DeviceEquipmentDao;
import com.skr.mdm.dao.LogUserDao;
import com.skr.mdm.entity.DeviceEquipmentDO;
import com.skr.mdm.entity.LogUserDO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.service.CmdHandlerService;
import com.vdurmont.emoji.EmojiParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @author nfq
 * @date 2020/8/4 16:36
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.UPLOAD_LOG)
public class UserLogServiceImpl implements CmdHandlerService {

    @Autowired
    private LogUserDao logUserDao;
    @Autowired
    private DeviceEquipmentDao equipmentDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            // 用户日志上传
            JSONArray jsonArray = JSONUtil.parseArray(data);
            List<LogUserDO> logUserDOList = JSONUtil.toList(jsonArray, LogUserDO.class);
            DeviceEquipmentDO equipmentDO = new LambdaQueryChainWrapper<>(equipmentDao).eq(DeviceEquipmentDO::getId, equipmentId).one();
            if (equipmentDO == null) {
                return ResponseResult.failure();
            }
            List<Integer> ids = new ArrayList<>(jsonArray.size());
            logUserDOList.forEach(logUserDO -> {
                logUserDO.setEquipmentId(equipmentId);
                logUserDO.setUserName(equipmentDO.getUserName());
                logUserDO.setEquipmentName(equipmentDO.getEquipmentName());
                logUserDO.setContent(EmojiParser.parseToUnicode(logUserDO.getContent()));
                logUserDO.setDepartmentName(equipmentDO.getDepartmentName());
                logUserDO.setDepartmentId(equipmentDO.getDepartmentId());
                logUserDO.setCompanyId(equipmentDO.getCompanyId());
                ids.add(logUserDO.getId());
            });
            logUserDao.insertBatch(logUserDOList);
            return ResponseResult.success(JSONUtil.toJsonStr(ids));
        } catch (Exception e) {
            log.error("用户上传日志异常:"  + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
