package cn.pluss.platform.merchantQrcode.impl;

import cn.pluss.platform.entity.MerchantBaseInfo;
import cn.pluss.platform.entity.MerchantQrcode;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantQrcodeMapper;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantQrcode.MerchantQrcodeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Djh
 * @since 2020-10-23
 */
@Service
public class MerchantQrcodeServiceImpl extends ServiceImpl<MerchantQrcodeMapper, MerchantQrcode> implements MerchantQrcodeService {

    @Setter(onMethod_ = {@Autowired})
    private MerchantBaseInfoService merchantBaseInfoService;

    @Override
    public List<MerchantQrcode> listPage(Map<String, Object> map) {
        return baseMapper.listPage(map);
    }

    @Override
    public Integer countMerchantQrcode(Map<String, Object> map) {
        return baseMapper.countMerchantQrcode(map);
    }

    @Override
    public void saveMerQrcode(MerchantQrcode merchantQrcode) {
        String userId = merchantQrcode.getUserId();

        if (merchantQrcode == null || merchantQrcode.getQrCodeUrl() == null || "".equals(merchantQrcode.getQrCodeUrl())) {
            throw new MsgException("请先上传微信二维码!");
        }

        MerchantBaseInfo merchantBaseInfo1 = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);

        MerchantQrcode existData = new MerchantQrcode();
        existData.setMerchantCode(merchantBaseInfo1.getMerchantCode());
        existData = getOne(new QueryWrapper<>(existData));

        if (existData != null) {
            existData.setQrCodeUrl(merchantQrcode.getQrCodeUrl());
            existData.setWechat(merchantQrcode.getWechat());
            updateById(existData);
        } else {
            MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getMerchantBaseInfoByUserId(merchantQrcode.getUserId());
            merchantQrcode.setMerchantCode(merchantBaseInfo.getMerchantCode());
            merchantQrcode.setMerchantName(merchantBaseInfo.getAlias());

            save(merchantQrcode);
        }
    }

    @Override
    public void removeByUserId(String userId) {
        MerchantBaseInfo merchantBaseInfo1 = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);

        QueryWrapper<MerchantQrcode> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("merchantCode", merchantBaseInfo1.getMerchantCode());
        remove(queryWrapper);
    }
}
