/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.mp.comment.platform.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.config.WxConfig;
import com.yami.shop.mp.comment.dao.WeixinMaterialMapper;
import com.yami.shop.mp.comment.model.WeixinMaterial;
import com.yami.shop.mp.comment.platform.service.WeixinMaterialService;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *
 * @author lgh on 2019/05/14.
 */
@Service
@AllArgsConstructor
public class WeixinMaterialServiceImpl extends ServiceImpl<WeixinMaterialMapper,WeixinMaterial> implements WeixinMaterialService {

    private final WeixinMaterialMapper weixinMaterialMapper;

    private final WxConfig wxConfig;

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void insertBatch(List<WeixinMaterial> allMaterial, String type) {
        WeixinMaterial record = new WeixinMaterial();
        record.setMediaType(type);
        weixinMaterialMapper.deleteById(record.getMediaId());
        if (CollectionUtil.isNotEmpty(allMaterial)) {
            weixinMaterialMapper.insertBatch(allMaterial);
        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void delete(String mediaId) {
        weixinMaterialMapper.deleteById(mediaId);
        try {
            wxConfig.getWxMpService().getMaterialService().materialDelete(mediaId);
        } catch (WxErrorException e) {
            throw new GlobalException(e.getError().getErrorMsg());
        }
    }

}
