package com.sqx.modules.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.modules.goods.dao.GoodsAttrDao;
import com.sqx.modules.goods.entity.GoodsAttr;
import com.sqx.modules.goods.entity.GoodsAttrValue;
import com.sqx.modules.goods.service.GoodsAttrService;
import com.sqx.modules.goods.service.GoodsAttrValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GoodsAttrServiceImpl extends ServiceImpl<GoodsAttrDao, GoodsAttr> implements GoodsAttrService {

    @Autowired
    private GoodsAttrValueService goodsAttrValueService;

    @Override
    public int updateGoodsAttr(GoodsAttr goodsAttr) {
        //删除之前的值
        goodsAttrValueService.deleteGoodsAttrValueByGoodsId(goodsAttr.getGoodsId());
        //放入新值
        for (GoodsAttrValue v : goodsAttr.getAttrValue()) {
            v.setId(null);
            v.setGoodsId(goodsAttr.getGoodsId());
            v.setAttrId(goodsAttr.getId());
            goodsAttrValueService.save(v);
        }
        baseMapper.delete(new QueryWrapper<GoodsAttr>().eq("goods_id",goodsAttr.getGoodsId()));
        baseMapper.insert(goodsAttr);
        return 1;
    }

    @Override
    public void deleteAttrAndValue(Long goodsId){
        goodsAttrValueService.deleteGoodsAttrValueByGoodsId(goodsId);
        deleteGoodsAttr(goodsId);
    }

    @Override
    public int deleteGoodsAttr(Long goodsId){
        return baseMapper.delete(new QueryWrapper<GoodsAttr>().eq("goods_id",goodsId));
    }

    @Override
    public List<GoodsAttr> findAllByGoodsId(Long goodsId){
        return baseMapper.selectList(new QueryWrapper<GoodsAttr>().eq("goods_id",goodsId));
    }

    @Override
    public int saveGoodsAttr(GoodsAttr goodsAttr) {
       baseMapper.insertGoodsAttr(goodsAttr);
        List<GoodsAttrValue> list = goodsAttr.getAttrValue();
        for (GoodsAttrValue goodsAttrValue : list) {
            goodsAttrValue.setId(null);
            goodsAttrValue.setGoodsId(goodsAttr.getGoodsId());
            goodsAttrValue.setAttrId(goodsAttr.getId());
            goodsAttrValueService.save(goodsAttrValue);
        }
        return 1;
    }

    @Override
    public List<GoodsAttr> findByGoodsId(Long goodsId) {
        List<GoodsAttr> list = findAllByGoodsId(goodsId);
        for (GoodsAttr goodsAttr : list) {
            List<GoodsAttrValue> valueList = goodsAttrValueService.findAllByGoodsId(goodsAttr.getGoodsId());
            goodsAttr.setAttrValue(valueList);
        }
        return list;
    }


}