package com.younike.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.younike.common.core.domain.AjaxResult;
import com.younike.common.exception.ServiceException;
import com.younike.common.utils.SecurityUtils;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.system.domain.*;
import com.younike.system.domain.vo.GoodsFormVO;
import com.younike.system.domain.vo.GoodsServerVO;
import com.younike.system.domain.vo.GoodsVo;
import com.younike.system.service.*;
import com.younike.system.param.GoodsParam;
import com.younike.system.param.GoodsQueryParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.younike.system.mapper.GoodsMapper;

import static java.util.stream.Collectors.*;

/**
 * 商品Service业务层处理
 *
 * @author elev
 * @date 2022-01-06
 */
@Service
public class GoodsServiceImpl implements IGoodsService {
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private IGoodsImageService goodsImageService;
    @Autowired
    private IGoodsServerService goodsServerService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IMerchantService merchantService;

    @Override
    public int save(GoodsFormVO goodsFormVO) {
        boolean isCreate = Objects.isNull(goodsFormVO.getGoodsId());
        Goods pojo = new Goods();
        BeanUtils.copyBeanProp(pojo, goodsFormVO);

        // 1. 保存商品信息
        Long currentUser = SecurityUtils.getUserId();
        LocalDateTime now = LocalDateTime.now();
        if (isCreate){
            Merchant merchant = merchantService.selectMerchantByAdminId(currentUser);
            if (Objects.isNull(merchant)){
                throw new ServiceException("当前用户不存在店铺信息，无法新增");
            }
            pojo.setMerchantId(merchant.getMerchantId());
            pojo.setCreateTime(now);
            pojo.setCreateBy(currentUser.toString());
        } else {
            pojo.setUpdateBy(currentUser.toString());
            pojo.setUpdateTime(now);
        }
        int result =  isCreate? goodsMapper.insertGoods(pojo): goodsMapper.updateGoods(pojo);

        // 2. 更新其他信息
        Long goodsId = pojo.getGoodsId();
        goodsImageService.changeGoodsImages(goodsId, goodsFormVO.getImages());
        goodsServerService.changeGoodsServers(goodsId, goodsFormVO.getServerUserList());
        return result;
    }

    @Override
    public List<Goods> list(Goods goods) {
        Merchant merchant = merchantService.selectMerchantByAdminId(SecurityUtils.getUserId());
        if (Objects.isNull(merchant)){
            throw new ServiceException("当前用户不存在店铺信息，无法查询");
        }
        goods.setMerchantId(merchant.getMerchantId());
        List<Goods> goodsList = goodsMapper.selectGoodsList(goods);
        if (CollectionUtils.isEmpty(goodsList)){
            return Lists.newArrayList();
        }

        List<Long> goodsIds = goodsList.stream().map(Goods::getGoodsId).collect(toList());
        Map<Long, List<GoodsServerVO>> goodsServerMap = goodsServerService.goodsServerList(goodsIds)
                .stream().collect(groupingBy(GoodsServerVO::getGoodsId));
        Map<Long, List<Category>> categoryMap = categoryService.selectCategoryList(new Category())
                .stream().collect(groupingBy(Category::getCategoryId));

        goodsList.forEach(row -> {
            row.setGoodsServerList(goodsServerMap.get(row.getGoodsId()));
            List<Category> categoryList = categoryMap.get(row.getCateId());
            if (CollectionUtils.isNotEmpty(categoryList)){
                row.setCategoryName(categoryList.get(0).getCategoryName());
            }
        });
       return goodsList;
    }

    @Override
    public int remove(Long goodsId) {
        Goods param = new Goods();
        param.setGoodsId(goodsId);
        param.setDelFlag("1");
        return goodsMapper.updateGoods(param);
    }

    @Override
    public int onShelf(Long goodsId) {
        Goods param = new Goods();
        param.setGoodsId(goodsId);
        param.setIsSale(1);
        return goodsMapper.updateGoods(param);
    }

    @Override
    public int offShelf(Long goodsId) {
        Goods param = new Goods();
        param.setGoodsId(goodsId);
        param.setIsSale(0);
        return goodsMapper.updateGoods(param);
    }

    @Override
    public GoodsFormVO detail(Long goodsId) {
        GoodsFormVO result = new GoodsFormVO();
        Goods goods = goodsMapper.selectGoodsByGoodsId(goodsId);
        BeanUtils.copyBeanProp(result, goods);
        List<Long> param = new ArrayList<>();
        param.add(goodsId);
        List<Long> goodsIds = new ArrayList<>();
        goodsIds.add(goodsId);
        List<GoodsImage> goodsImageList = goodsImageService.goodsImageList(goodsIds);
        if (CollectionUtils.isNotEmpty(goodsImageList)){
            result.setImages(goodsImageList.stream().map(GoodsImage::getUrl).collect(joining(",")));
        }
        result.setServerUserList(goodsServerService.goodsServerList(param));
        return result;
    }

    @Autowired
    private GoodsCommentServiceImpl goodsCommentService;

    @Override
    public List<GoodsVo> pageList(GoodsQueryParam param) {
        return goodsMapper.pageList(param);
    }

    /**
     * 查询商品
     *
     * @param goodsId 商品主键
     * @return 商品
     */
    @Override
    public Goods selectGoodsByGoodsId(Long goodsId) {
        return goodsMapper.selectGoodsByGoodsId(goodsId);
    }

    /**
     * 查询商品列表
     *
     * @param goods 商品
     * @return 商品
     */
    @Override
    public List<Goods> selectGoodsList(Goods goods) {
        return goodsMapper.selectGoodsList(goods);
    }

    /**
     * 新增商品
     *
     * @param goods 商品
     * @return 结果
     */
    @Override
    public int insertGoods(Goods goods) {
        goods.setCreateTime(LocalDateTime.now());
        return goodsMapper.insertGoods(goods);
    }

    /**
     * 修改商品
     *
     * @param goods 商品
     * @return 结果
     */
    @Override
    public int updateGoods(Goods goods) {
        goods.setUpdateTime(LocalDateTime.now());
        return goodsMapper.updateGoods(goods);
    }

    /**
     * 批量删除商品
     *
     * @param goodsIds 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteGoodsByGoodsIds(Long[] goodsIds) {
        return goodsMapper.deleteGoodsByGoodsIds(goodsIds);
    }

    /**
     * 删除商品信息
     *
     * @param goodsId 商品主键
     * @return 结果
     */
    @Override
    public int deleteGoodsByGoodsId(Long goodsId) {
        return goodsMapper.deleteGoodsByGoodsId(goodsId);
    }

    /**
     * 搜索服务人员
     *
     * @param goods
     * @return
     */
    @Override
    public List<GoodsVo> seekCrewList(GoodsParam goods) {
            return goodsMapper.seekCrewList(goods);
    }
    /**
     * 搜索商家
     *
     * @param goods
     * @return
     */
    @Override
    public List<GoodsVo> seekMerchantList(GoodsParam goods) {
            return goodsMapper.seekMerchantList(goods);
    }
    /**
     * 首页：商家主页
     * @param goods
     * @return
     */
    @Override
    public AjaxResult merchantGoods(GoodsParam goods) {

        GoodsVo merchant=goodsMapper.merchantGoods(goods);
        return AjaxResult.success(merchant);

    }

    /**
     * 首页：服务员主页
     * @param goods
     * @return
     */
    @Override
    public AjaxResult serverGoods(GoodsParam goods) {
        GoodsVo merchant=goodsMapper.serverGoods(goods);
          return AjaxResult.success(merchant);
    }
}
