package com.ghy.order.service.impl;

import com.ghy.order.domain.OrderTemplate;
import com.ghy.order.domain.OrderTemplateGoods;
import com.ghy.order.mapper.OrderTemplateMapper;
import com.ghy.order.service.OrderTemplateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

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

@Service
public class OrderTemplateServiceImpl implements OrderTemplateService {

    @Resource
    private OrderTemplateMapper mapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(OrderTemplate orderTemplate) {
        int count = mapper.insert(orderTemplate);
        // 保存选中的商品信息
        saveGoods(orderTemplate);
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(OrderTemplate orderTemplate) {
        int count = mapper.update(orderTemplate);
        // 全量替换模板的商品信息
        mapper.deleteGoods(orderTemplate.getId());
        saveGoods(orderTemplate);
        return count;
    }

    /**
     * 保存订单模板中选中的商品信息
     */
    private void saveGoods(OrderTemplate orderTemplate) {
        List<OrderTemplateGoods> goods = orderTemplate.getGoods();
        if (!CollectionUtils.isEmpty(goods)) {
            for (OrderTemplateGoods x : goods) {
                x.setOrderTemplateId(orderTemplate.getId());
                mapper.insertGoods(x);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        // 删除模板关联的商品信息
        mapper.deleteGoods(id);
        // 删除模板
        return mapper.delete(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchDelete(Set<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return 0;
        } else {
            ids.forEach(x -> mapper.deleteGoods(x));
            return mapper.batchDelete(ids);
        }
    }

    @Override
    public OrderTemplate selectById(Long id) {
        List<OrderTemplateGoods> goods = mapper.selectGoods(id);
        OrderTemplate orderTemplate = mapper.selectById(id);
        orderTemplate.setGoods(goods);
        return orderTemplate;
    }

    @Override
    public List<OrderTemplate> select(OrderTemplate orderTemplate) {
        List<OrderTemplate> list = mapper.select(orderTemplate);
        for (OrderTemplate item : list) {
            List<OrderTemplateGoods> goods = mapper.selectGoods(item.getId());
            item.setGoods(goods);
        }
        return list;
    }

    @Override
    public List<OrderTemplate> selectByUserId(Long userId) {
        OrderTemplate param = new OrderTemplate();
        param.setUserId(userId);
        return select(param);
    }
}
