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

import cn.hutool.json.JSONUtil;
import com.skr.mdm.annotation.CmdHandler;
import com.skr.mdm.constant.CmdTypeConstants;
import com.skr.mdm.dao.MdmAppStoreInstallDao;
import com.skr.mdm.dto.AppStoreInstallDTO;
import com.skr.mdm.entity.MdmAppStoreInstallDO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.service.CmdHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用商店安装记录上传
 *
 * @author nfq
 * @date 2022/12/05 14:21
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.APP_STORE_INSTALL)
public class MdmAppStoreInstallServiceImpl implements CmdHandlerService {

    @Autowired
    private MdmAppStoreInstallDao appStoreInstallDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            List<AppStoreInstallDTO> appStoreInstallDTOList = JSONUtil.toList(JSONUtil.parseArray(data), AppStoreInstallDTO.class);
            if (CollectionUtils.isNotEmpty(appStoreInstallDTOList)) {
                List<MdmAppStoreInstallDO> appStoreInstallDOList = appStoreInstallDTOList.stream()
                        .map(appStoreInstallDTO -> MdmAppStoreInstallDO
                                .builder()
                                .appVersionId(appStoreInstallDTO.getAppVersionId())
                                .installTime(appStoreInstallDTO.getInstallTime())
                                .equipmentId(equipmentId)
                                .build())
                        .collect(Collectors.toList());
                appStoreInstallDao.insertBatch(appStoreInstallDOList);
                List<Integer> cidList = appStoreInstallDTOList.stream()
                        .map(AppStoreInstallDTO::getCid)
                        .collect(Collectors.toList());
                return ResponseResult.success(JSONUtil.toJsonStr(cidList));
            }
            return ResponseResult.success();
        } catch (Exception e) {
            log.error("客户端应用商店发布异常:" + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
