package com.yc.ship.module.product.service.pricespu;

import com.yc.ship.framework.common.util.collection.CollectionUtils;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.module.product.controller.admin.pricetemplate.vo.PriceSpuRespVO;
import com.yc.ship.module.product.dal.dataobject.pricespu.PriceSpuDO;
import com.yc.ship.module.product.dal.dataobject.productSpu.ProductSpuDO;
import com.yc.ship.module.product.service.productSpu.ProductSpuService;
import com.yc.ship.module.resource.controller.admin.category.vo.CategoryRespVO;
import com.yc.ship.module.resource.dal.dataobject.category.CategoryDO;
import com.yc.ship.module.resource.service.category.CategoryService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import com.yc.ship.module.product.dal.mysql.pricespu.PriceSpuMapper;

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


/**
 * 附加产品设置 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class PriceSpuServiceImpl implements PriceSpuService {

    @Resource
    private PriceSpuMapper priceSpuMapper;

    @Resource
    private ProductSpuService productSpuService;

    @Resource
    private CategoryService categoryService;


    @Override
    public List<PriceSpuRespVO> getListByObjectId(Long id) {
        List<PriceSpuDO> list = priceSpuMapper.selectListByObjectId(id);
        List<PriceSpuRespVO> respVOList = BeanUtils.toBean(list, PriceSpuRespVO.class);
        List<Long> spuIds = CollectionUtils.convertList(respVOList, PriceSpuRespVO::getSpuId);
        List<ProductSpuDO> spuList = productSpuService.getProductList(spuIds);
        Map<Long, ProductSpuDO> spuMap = CollectionUtils.convertMap(spuList, ProductSpuDO::getId);
        //产品分组
        List<Long> categoryIds = CollectionUtils.convertList(spuList, ProductSpuDO::getCategoryId);
        List<CategoryDO> categoryList = categoryService.getListByIds(categoryIds);
        Map<Long, CategoryDO> categoryMap = CollectionUtils.convertMap(categoryList, CategoryDO::getId);
        respVOList.stream().forEach(item -> {
            if(spuMap.get(item.getSpuId()) != null) {
                item.setSalePrice(spuMap.get(item.getSpuId()).getSalePrice());
                item.setProductName(spuMap.get(item.getSpuId()).getProductName());
                if(categoryMap.get(spuMap.get(item.getSpuId()).getCategoryId()) != null) {
                    item.setCategoryName(categoryMap.get(spuMap.get(item.getSpuId()).getCategoryId()).getCateName());
                }else {
                    item.setCategoryName("已下线/已删除");
                }
            }else {
                item.setSalePrice(null);
                item.setProductName("已下线/已删除");
                item.setCategoryName("已下线/已删除");
            }
        });
        return respVOList;
    }
}