package com.ghy.goods.service.impl;

import com.ghy.common.constant.UserConstants;
import com.ghy.common.core.text.Convert;
import com.ghy.common.exception.ServiceException;
import com.ghy.common.utils.StringUtils;
import com.ghy.goods.domain.Goods;
import com.ghy.goods.mapper.GoodsMapper;
import com.ghy.goods.service.GoodsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 *  商品模块实现类
 * @author clunt
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Override
    public int insertGoods(Goods goods) {
        return goodsMapper.insertGoods(goods);
    }

    @Override
    public int updateGoods(Goods goods) {
        return goodsMapper.updateGoods(goods);
    }

    @Override
    public List<Goods> selectGoodsList(Goods goods) {
        return goodsMapper.selectGoodsList(goods);
    }

    @Override
    public Goods selectById(Long goodsId) {
        return goodsMapper.selectById(goodsId);
    }

    @Override
    public int deleteGoodsByIds(String ids) {
        Long[] goodsIds = Convert.toLongArray(ids);
        for (Long goodsId : goodsIds)
        {
            Goods goods = selectById(goodsId);
            if (countUserGoodsById(goods) > 0)
            {
                throw new ServiceException(String.format("%1$s正在使用,不能删除", goods.getGoodsName()));
            }
        }
        return goodsMapper.deleteGoodsByIds(goodsIds);
    }

    @Override
    public String checkGoodsNameUnique(Goods goods) {
        Long goodsId = StringUtils.isNull(goods.getGoodsId()) ? -1L : goods.getGoodsId();
        Goods info = goodsMapper.checkGoodsNameUnique(goods.getGoodsName());
        if (StringUtils.isNotNull(info) && info.getGoodsId().longValue() != goodsId.longValue())
        {
            return UserConstants.GOODS_NAME_NOT_UNIQUE;
        }
        return UserConstants.GOODS_NAME_UNIQUE;
    }

    @Override
    public String checkGoodsCodeUnique(Goods goods) {
        Long goodsId = StringUtils.isNull(goods.getGoodsId()) ? -1L : goods.getGoodsId();
        Goods info = goodsMapper.checkGoodsCodeUnique(goods.getGoodsCode());
        if (StringUtils.isNotNull(info) && info.getGoodsId().longValue() != goodsId.longValue())
        {
            return UserConstants.GOODS_CODE_NOT_UNIQUE;
        }
        return UserConstants.GOODS_CODE_UNIQUE;
    }


    public int countUserGoodsById(Goods goods){
        //TODO 校验商品是否上架
        return 0;
    }

}
