package com.younike.system.service.impl;

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.common.utils.id.GoodsIndexGenerate;
import com.younike.common.utils.id.IndexGenerate;
import com.younike.system.domain.*;
import com.younike.system.domain.vo.*;
import com.younike.system.mapper.GoodsMapper;
import com.younike.system.param.GoodsParam;
import com.younike.system.param.GoodsQueryParam;
import com.younike.system.param.GroupGoodsAddParam;
import com.younike.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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;

    @Autowired
    private IGoodsServerDimensionService goodsServerDimensionService;

    @Autowired
    private ICateDimensionService cateDimensionService;

    @Autowired
    private IServerTimeService serverTimeService;

    @Autowired
    private IOrderGoodsService orderGoodsService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    IGoodsService goodsService;

    @Autowired
    IGoodsSpecificationService goodsSpecificationService;


    @Override
    public int save(GoodsFormVO goodsFormVO) {
        boolean isCreate = Objects.isNull(goodsFormVO.getGoodsId());
        Goods pojo = new Goods();
        BeanUtils.copyBeanProp(pojo, goodsFormVO);
        // 设置商品编号
        pojo.setGoodsIndex(GoodsIndexGenerate.getGoodsIndex());
        // 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) {
        Long userId = SecurityUtils.getUserId();
        Merchant merchant = merchantService.selectMerchantByAdminId(userId);
        if (Objects.isNull(merchant)){
            throw new ServiceException("当前用户不存在店铺信息，无法查询");
        }
        goods.setMerchantId(merchant.getMerchantId());
        // 查询预订服务
        goods.setIsGroupGoods("0");
        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 AjaxResult onShelf(Long goodsId) {
        Goods param = new Goods();
        param.setGoodsId(goodsId);
        param.setIsSale(1);
        GoodsFormVO detail = goodsService.detail(goodsId);
        //System.out.println(detail);
        if (ObjectUtils.isEmpty(detail)){
            return AjaxResult.error("该服务不存在");
        }
        if (detail.getServerUserList().size()<1){
            return AjaxResult.error("该服务无服务人员，请添加服务人员");
        }
        if (this.updateGoods(param)<1){
            return AjaxResult.error("上架失败");
        }

        return AjaxResult.success("上架成功");
    }

    @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) {
        Goods goods = goodsMapper.selectGoodsByGoodsId(goodsId);
        if (Objects.isNull(goods)) {
            throw new ServiceException("商品不存在或已被删除");
        }
        return goods;
    }

    /**
     * 查询商品列表
     *
     * @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) {
        if ("1".equals(goods.getIsGroupGoods())) {
            List<GoodsVo> goodsVos = goodsMapper.seekGroupList(goods);
            return goodsVos;
        }
        List<GoodsVo> goodsVo = goodsMapper.seekCrewList(goods);
        return goodsVo;
    }
    /**
     * 搜索商家
     *
     * @param goods
     * @return
     */
    @Override
    public List<GoodsVo> seekMerchantList(GoodsParam goods) {
        List<GoodsVo> goodsVos = goodsMapper.seekMerchantList(goods);
//        if (CollectionUtils.isNotEmpty(goodsVos)) {
//            // 过滤掉个人商家
//            goodsVos = goodsVos.stream().filter(vo -> Objects.equals(vo.getMerchantType(), 0)).collect(Collectors.toList());
//            // 根据商品id过滤商家相同服务
//            goodsVos = goodsVos.stream().collect(
//                    collectingAndThen(
//                            toCollection(() -> new TreeSet<>(Comparator.comparing(GoodsVo::getGoodsId))), ArrayList::new));
//            Collections.sort(goodsVos, Comparator.comparing(GoodsVo::getRate).reversed());
//            Collections.sort(goodsVos, Comparator.comparing(GoodsVo::getOrderCount).reversed());
//        }
        return goodsVos;
    }

    /**
     * 运营端 删除服务
     *
     * @param goods
     * @return
     */
    @Override
    public AjaxResult adminDeleteGoods(Goods goods) {
        //根据服务id查询是否有订单非已取消与已退款状态
        List<Order> orderList = orderService.adminDeleteGoods(goods.getGoodsId());
        if (orderList.size() > 0) {
            return AjaxResult.error("当前服务有订单未完成，不可删除");
        }
        //进行更新数据
        if (this.updateGoods(goods) > 0) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    /**
     * 店铺管理
     * 删除服务
     *
     * @param goodsId
     * @return
     */
    @Override
    public AjaxResult merchantRemove(Long goodsId) {
        List<Order> orderList = orderService.adminDeleteGoods(goodsId);
        if (orderList.size() > 0) {
            return AjaxResult.error("当前服务有订单未完成，不可删除");
        }
        Goods param = new Goods();
        param.setGoodsId(goodsId);
        param.setDelFlag("2");

        //进行更新数据
        if (this.updateGoods(param) > 0) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    /**
     * 查询服务人员是否有关联的上架的服务（如果有，校验服务是否只有这一个要删除的服务人员）
     *
     * @param serverIds
     * @return
     */
    @Override
    public List<GoodsVo> merchanServerUserId(Long[] serverIds) {
        return goodsMapper.merchanServerUserId(serverIds);
    }

    /**
     * 运营端：服务上架
     *
     * @param goods
     * @return
     */
    @Override
    public AjaxResult adminTakeOn(Goods goods) {
        //根据服务id查询服务人员
        GoodsFormVO detail = goodsService.detail(goods.getGoodsId());
        if (ObjectUtils.isEmpty(detail)) {
            return AjaxResult.error("服务不存在");
        }
        if (detail.getServerUserList().size() < 1) {
            return AjaxResult.error("该服务无服务人员，请添加服务人员后重试！");
        }
        if (this.updateGoods(goods) < 1) {
            return AjaxResult.error("服务上架失败！");
        }

        return AjaxResult.success("上架成功");
    }

    /**
     * 新增团购商品
     *
     * @param groupGoodsAddParam
     * @return
     */
    @Override
    public AjaxResult saveGroupGoods(GroupGoodsAddParam groupGoodsAddParam) {
        boolean isAdd = Objects.isNull(groupGoodsAddParam.getGoodsId());
        // 拷贝数据
        Goods pojo = new Goods();
        BeanUtils.copyBeanProp(pojo, groupGoodsAddParam);
        // 设置商品编号
        pojo.setGoodsIndex(IndexGenerate.getGoodsIndex());
        // 设置团购商品标识
        pojo.setIsGroupGoods("1");
        // 保存商品信息
        Long currentUser = SecurityUtils.getUserId();
        if (isAdd){
            Merchant merchant = merchantService.selectMerchantByAdminId(currentUser);
            if (Objects.isNull(merchant)){
                throw new ServiceException("当前用户不存在店铺信息，无法新增");
            }
            pojo.setMerchantId(merchant.getMerchantId());
            pojo.setCreateBy(currentUser == null ? "-" : currentUser.toString());
            pojo.setUpdateBy(currentUser == null ? "-" : currentUser.toString());
        } else {
            pojo.setUpdateBy(currentUser == null ? "-" : currentUser.toString());
            pojo.setUpdateTime(LocalDateTime.now());
        }
        // 执行新增或编辑操作
        int result = isAdd ? goodsMapper.insertGoods(pojo) : goodsMapper.updateGoods(pojo);
        if (result <= 0) {
            return AjaxResult.success("保存失败!");
        }

        // 更新其他信息
        Long goodsId = pojo.getGoodsId();
        // 更新轮播图
        goodsImageService.changeGoodsImages(goodsId, groupGoodsAddParam.getImages());
        // 更新规格信息
        goodsSpecificationService.changeGoodsSpecification(goodsId, groupGoodsAddParam.getGoodsSpecificationList());
        return AjaxResult.success("保存成功");
    }

    /**
     * 查询团购服务列表
     *
     * @param goods
     * @return
     */
    @Override
    public List<GoodsVo> listGroupGoods(Goods goods) {
        Merchant merchant = merchantService.selectMerchantByAdminId(SecurityUtils.getUserId());
        if (Objects.isNull(merchant)){
            throw new ServiceException("当前用户不存在店铺信息，无法查询");
        }
        // 查询团购服务列表
        goods.setMerchantId(merchant.getMerchantId());
        goods.setIsGroupGoods("1");
        List<GoodsVo> goodsVoList = goodsMapper.selectGoodsVoList(goods);
        if (CollectionUtils.isEmpty(goodsVoList)){
            return Lists.newArrayList();
        }

        // 查询商品规格信息
        List<Long> goodsIds = goodsVoList.stream().map(Goods::getGoodsId).distinct().collect(toList());
        Map<Long, List<GoodsSpecification>> goodsSpecificationMap = goodsSpecificationService.listByGoodsIds(goodsIds)
                .stream().collect(groupingBy(GoodsSpecification::getGoodsId));
        Map<Long, List<Category>> categoryMap = categoryService.selectCategoryList(new Category())
                .stream().collect(groupingBy(Category::getCategoryId));

        // 组装返回数据
        goodsVoList.forEach(goodsVo -> {
            goodsVo.setGoodsSpecificationList(goodsSpecificationMap.get(goodsVo.getGoodsId()));
            List<Category> categoryList = categoryMap.get(goodsVo.getCateId());
            if (CollectionUtils.isNotEmpty(categoryList)){
                goodsVo.setCategoryName(categoryList.get(0).getCategoryName());
            }
        });
        return goodsVoList;
    }

    /**
     * 查询团购服务详情
     *
     * @param goodsId
     * @return
     */
    @Override
    public GoodsVo getGroupGoodsDetail(Long goodsId) {
        GoodsVo goodsVo = new GoodsVo();
        // 查询商品信息
        Goods goods = goodsMapper.selectGoodsByGoodsId(goodsId);
        // 拷贝数据
        BeanUtils.copyBeanProp(goodsVo, goods);
        // 查询商品轮播图
        List<Long> goodsIds = new ArrayList<>();
        goodsIds.add(goodsId);
        List<GoodsImage> goodsImageList = goodsImageService.goodsImageList(goodsIds);
        if (CollectionUtils.isNotEmpty(goodsImageList)) {
            goodsVo.setImages(goodsImageList.stream().map(GoodsImage::getUrl).collect(joining(",")));
        }
        // 查询商品规格信息
        goodsVo.setGoodsSpecificationList(goodsSpecificationService.listByGoodsIds(goodsIds));

        return goodsVo;
    }

    /**
     * 上架团购服务
     *
     * @param goods
     * @return
     */
    @Override
    public AjaxResult onShelfGroupGoods(Goods goods) {
//        Goods goods = new Goods();
//        goods.setGoodsId(goodsId);
        goods.setIsSale(1);
        GoodsVo groupGoodsDetail = goodsService.getGroupGoodsDetail(goods.getGoodsId());
        if (ObjectUtils.isEmpty(groupGoodsDetail)){
            return AjaxResult.error("该服务不存在");
        }

        if (this.updateGoods(goods) < 1){
            return AjaxResult.error("上架失败");
        }

        return AjaxResult.success("上架成功");
    }

    /**
     * 首页：团购商品列表
     *
     * @param goods
     * @return
     */
    @Override
    public List<GoodsVo> seekGroupList(GoodsParam goods) {
        goods.setIsGroupGoods("1");
        return goodsMapper.seekGroupList(goods);
    }

    /**
     * 会员端 首页：团购次卡主页
     *
     * @param goods
     * @return
     */
    @Override
    public AjaxResult groupGoods(GoodsParam goods) {
        GoodsVo goodsVo = goodsMapper.groupGoodsDetails(goods);
        if (ObjectUtils.isEmpty(goodsVo)) {
            return AjaxResult.error("商品信息不存在!");
        }
        return AjaxResult.success(goodsVo);

    }

    /**
     * 会员端：搜索：商家:查询商家(团购、预售)列表
     *
     * @param goods
     * @return
     */
    @Override
    public List<MerchantGoodsVo> seekMerchantGoodsList(GoodsParam goods) {
        List<MerchantGoodsVo> merchantGoodsVos = goodsMapper.seekMerchantGoodsList(goods);

        if (merchantGoodsVos.size() < 1) {
            return merchantGoodsVos;
        }
        if (goods.getBizType() == 2) {
            return merchantGoodsVos;
        }

        for (MerchantGoodsVo m : merchantGoodsVos) {

            if (m.getGoodsList().size() == 1) {
                if (m.getGroupGoodsList().size() > 0) {
                    m.getGoodsList().add(m.getGroupGoodsList().get(0));
                }
            } else if (m.getGoodsList().size() >= 2) {
                if (m.getGroupGoodsList().size() > 0) {
                    m.getGoodsList().set(1, m.getGroupGoodsList().get(0));
                }
            } else {
                if (m.getGroupGoodsList().size() > 0) {
                    m.getGoodsList().add(m.getGroupGoodsList().get(0));
                }
                if (m.getGroupGoodsList().size() > 1) {
                    m.getGoodsList().add(m.getGroupGoodsList().get(1));
                }
            }
        }
        return merchantGoodsVos;
    }

    // 批量更新服务数据，订单时统计好评率成交量评分
    @Override
    public void updateGoodsList(List<Goods> goodsList) {
        goodsMapper.updateGoodsList(goodsList);
    }

    /**
     * 首页：商家主页
     *
     * @param goods
     * @return
     */
    @Override
    public AjaxResult merchantGoods(GoodsParam goods) {
        GoodsVo merchant = goodsMapper.merchantGoods(goods);
        //判断商家服务范围是否为空，如果为空则返回系统默认服务范围
        if(ObjectUtils.isEmpty(merchant)){
            return AjaxResult.error("商品不存在");
        }
        if(ObjectUtils.isEmpty(merchant.getMerchant())){
            return AjaxResult.error("商家不存在");
        }
        if(!"001".equals(merchant.getBusinessState())){
            return AjaxResult.error("店铺不营业");
        }
        if(merchant.getMerchant().getServiceDistance()==null){
            //查询
        }
        // 查询商家该商品订单数
        merchant.setOrderCount(orderGoodsService.getOrderCountByGoodsIdAndMerchantId(goods.getGoodsId(), merchant.getMerchantId()));
        return AjaxResult.success(merchant);

    }

    /**
     * 首页：服务员主页
     * @param goods
     * @return
     */
    @Override
    public AjaxResult serverGoods(GoodsParam goods) {
        GoodsVo merchantGoodsVo = goodsMapper.serverGoods(goods);
        if (merchantGoodsVo == null) {
            return AjaxResult.error("商品信息不存在!");
        }
        // 查询商品评价维度信息
//            List<GoodsServerDimensionVo> goodsServerDimensionVoList = goodsServerDimensionService.listByServerIdAndGoodsId(merchantGoodsVo.getServerId(), merchantGoodsVo.getGoodsId());
//            merchantGoodsVo.setGoodsServerDimensionList(goodsServerDimensionVoList);
        List<GoodsServerDimensionVo> vos = goodsServerDimensionService.listByServerIdAndGoodsId(goods.getServerId(), goods.getGoodsId());
        merchantGoodsVo.setGoodsServerDimensionList(vos);
        // 查询服务人员是否接单
        ServerTimeVo serverTimeVo = serverTimeService.getServerTime(merchantGoodsVo.getServerId());
        merchantGoodsVo.setStopOrder(serverTimeVo == null ? null : serverTimeVo.getStopOrder());
        // 查询服务人员交易单数
        merchantGoodsVo.setOrderCount(orderGoodsService.getOrderCountByGoodsIdAndServerId(goods.getGoodsId(), merchantGoodsVo.getServerId()));

//        Category category = categoryService.selectCategoryByGoodsId(goods.getGoodsId());
//        String categoryParentId = category.getParentId();
//        if (categoryParentId == null) {
//            categoryParentId = String.valueOf(category.getCategoryId());
//        }
//        CateDimension cateDimension = new CateDimension();
//        cateDimension.setCategoryId(Long.valueOf(categoryParentId));
//        List<CateDimension> cateDimensions = cateDimensionService.selectCateDimensionList(cateDimension);
        return AjaxResult.success(merchantGoodsVo);
    }
}
