package cn.pluss.platform.merchantChannelImg.impl;

import cn.pluss.platform.entity.MerchantChannelImg;
import cn.pluss.platform.entity.MerchantImage;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.mapper.MerchantChannelImgMapper;
import cn.pluss.platform.mapper.MerchantImageMapper;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.merchantChannelImg.MerchantChannelImgService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MerchantChannelImgServiceImpl extends ServiceImpl<MerchantChannelImgMapper, MerchantChannelImg> implements MerchantChannelImgService {

    private final MerchantChannelImgMapper merchantChannelImgMapper;

    private final UserAppMapper userAppMapper;

    private final MerchantImageMapper merchantImageMapper;

    @Override
    public MerchantChannelImg get(String srcUrl, Integer channelType) {
        MerchantChannelImg condition = new MerchantChannelImg();
        condition.setSrcUrl(srcUrl).setChannelType(channelType);

        return baseMapper.selectOne(new QueryWrapper<>(condition));
    }

    @Override
    public List<MerchantImage> getAuditImg(String userId, String channelId) {
        List<MerchantImage> uploadedImgList = merchantChannelImgMapper.selectListByUserId(userId, channelId);
        UserApp userApp = new UserApp().setUserId(Long.parseLong(userId));
        userApp = userAppMapper.selectOne(new QueryWrapper<>(userApp));
        QueryWrapper<MerchantImage> queryWrapper = new QueryWrapper<MerchantImage>().eq("merchantCode", userApp.getMerchantCode());
        List<MerchantImage> merchantImageList = merchantImageMapper.selectList(queryWrapper);

        // 将没有上传的图片挑出来
        Iterator<MerchantImage> iterator = merchantImageList.iterator();
        while (iterator.hasNext()) {
            MerchantImage next = iterator.next();
            boolean exist = false;
            for (MerchantImage uploadImg : uploadedImgList) {
                if (uploadImg.getId().equals(next.getId())) {
                    exist = true;
                    break;
                }
            }

            if (!exist) {
                next.setPhotoUrl(null);
                uploadedImgList.add(next);
                iterator.remove();
            }
        }

        return uploadedImgList;
    }
}
