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

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.AppDownloadDao;
import com.skr.mdm.dto.AppDownloadDTO;
import com.skr.mdm.dto.LoginUserDTO;
import com.skr.mdm.entity.AppDownloadDO;
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 org.springframework.security.core.context.SecurityContextHolder;

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

@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.APP_DOWNLOAD_UPLOAD)
public class AppDownloadServiceImpl implements CmdHandlerService {

    @Autowired
    private AppDownloadDao appDownloadDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            LoginUserDTO loginUserDTO = (LoginUserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<AppDownloadDTO> appDownloadDTOList = JSONUtil.toList(JSONUtil.parseArray(data), AppDownloadDTO.class);
            List<Integer> cidList = new ArrayList<>(appDownloadDTOList.size());
            if (CollectionUtils.isNotEmpty(appDownloadDTOList)) {
                List<AppDownloadDO> appDownloadDOList = new ArrayList<>(appDownloadDTOList.size());
                appDownloadDTOList.forEach(appDownloadDTO -> {
                    Long count = new LambdaQueryChainWrapper<>(appDownloadDao)
                            .eq(AppDownloadDO::getEquipmentId, equipmentId)
                            .eq(AppDownloadDO::getAppPackage, appDownloadDTO.getAppPackage())
                            .count();
                    if (count == 0) {
                        AppDownloadDO appDownloadDO = AppDownloadDO.builder()
                                .equipmentId(equipmentId)
                                .companyId(loginUserDTO.getCompanyId())
                                .appName(appDownloadDTO.getAppName())
                                .appPackage(appDownloadDTO.getAppPackage())
                                .build();
                        appDownloadDOList.add(appDownloadDO);
                    }
                    cidList.add(appDownloadDTO.getCid());
                });
                if (CollectionUtils.isNotEmpty(appDownloadDOList)) {
                    appDownloadDao.insertBatch(appDownloadDOList);
                }
            }
            return ResponseResult.success(JSONUtil.toJsonStr(cidList));
        } catch (Exception e) {
            log.error("应用下载上传异常:" + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
