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

import com.google.common.collect.Lists;
import com.skr.mdm.annotation.CmdHandler;
import com.skr.mdm.bean.vo.app.ClientAppStoreVO;
import com.skr.mdm.bean.vo.app.ClientAppStoreVersionVO;
import com.skr.mdm.constant.CmdTypeConstants;
import com.skr.mdm.dao.MdmAppStoreDao;
import com.skr.mdm.dao.MdmAppStoreVersionDao;
import com.skr.mdm.dto.LoginUserDTO;
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.List;

/**
 * 应用商店列表
 *
 * @author nfq
 * @date 2022/12/05 10:48
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.SHOW_ALL_APP)
public class MdmAppStoreServiceImpl implements CmdHandlerService {

    @Autowired
    private MdmAppStoreDao appStoreDao;
    @Autowired
    private MdmAppStoreVersionDao appStoreVersionDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            LoginUserDTO loginUserDTO = (LoginUserDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            List<ClientAppStoreVO> clientAppStoreVOList = Lists.newCopyOnWriteArrayList(appStoreDao.listClientAppStoreVO(
                    equipmentId, loginUserDTO.getUserId(), loginUserDTO.getDepartmentId(), loginUserDTO.getCompanyId()));
            if (CollectionUtils.isNotEmpty(clientAppStoreVOList)) {
                clientAppStoreVOList.forEach(clientAppStoreVO -> {
                    List<ClientAppStoreVersionVO> appStoreVersionVOList = appStoreVersionDao.listClientAppStoreVersionVO(clientAppStoreVO.getId());
                    clientAppStoreVO.setClientAppStoreVersionVOList(appStoreVersionVOList);
                    if (CollectionUtils.isEmpty(appStoreVersionVOList)) {
                        clientAppStoreVOList.remove(clientAppStoreVO);
                    }
                });
            }
            return ResponseResult.success(clientAppStoreVOList);
        } catch (Exception e) {
            log.error("客户端应用商店发布异常:" + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}