package com.ruoyi.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.VO.SeckillGoodsVO;
import com.ruoyi.mall.domain.vo.GoodsProductVO;
import com.ruoyi.mall.domain.vo.IndexGoodsVO;
import com.ruoyi.mall.domain.vo.MallGoodsGoodsExportVO;
import com.ruoyi.mall.domain.vo.MemberCollectVO;
import com.ruoyi.mall.mapper.*;
import com.ruoyi.mall.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

/**
 * 商品Service业务层处理
 *
 * @author chang
 * @date 2021-11-25
 */
@Service
public class MallGoodsGoodsServiceImpl implements IMallGoodsGoodsService {
    @Resource
    private MallGoodsGoodsMapper mallGoodsGoodsMapper;
    @Resource
    private MallGoodsProductMapper mallGoodsProductMapper;

    @Autowired
    private IMallMemberSearchHistoryService searchHistoryService;

    @Autowired
    IMallImgService imgService;

    @Autowired
    IMallOrderCommentService orderCommentService;

    @Autowired
    IMallMemberUserService userService;

    @Resource
    private MallSeckillGoodsMapper mallSeckillGoodsMapper;

    @Resource
    private MallShopShopMapper mallShopShopMapper;
    @Resource
    IMallGoodsProductService mallGoodsProductService;
    @Resource
    private MallShopSupplierMapper mallShopSupplierMapper;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public MallGoodsGoods selectMallGoodsGoodsById(Long id) {
        MallGoodsGoods goods = mallGoodsGoodsMapper.selectMallGoodsGoodsById(id);

        List<MallGoodsProduct> list = mallGoodsProductMapper.selectMallGoodsProductByGoodsId(id);
        goods.setProList(list);
        goods.setGoodsProductList(list);

        MallImg img = new MallImg();
        img.setResId(goods.getId());
        img.setType("0");
        List<String> imgList = imgService.selectMallImgUrlVoList(img);
        goods.setGoodsBanner(StringUtils.join(imgList, ","));

        MallImg img1 = new MallImg();
        img1.setResId(goods.getId());
        img1.setType("1");
        List<String> imgList1 = imgService.selectMallImgUrlVoList(img1);
        goods.setGoodsDetail(StringUtils.join(imgList1, ","));
        return goods;
    }

    /**
     * 查询商品列表
     *
     * @param mallGoodsGoods 商品
     * @return 商品
     */
    @Override
    public List<MallGoodsGoods> selectMallGoodsGoodsList(MallGoodsGoods mallGoodsGoods) {
        List<MallGoodsGoods> list = mallGoodsGoodsMapper.selectMallGoodsGoodsList(mallGoodsGoods);
        for (MallGoodsGoods goodsVO : list) {
            MallImg img = new MallImg();
            img.setResId(goodsVO.getId());
            img.setType("0");
            List<String> imgList = imgService.selectMallImgUrlVoList(img);
            goodsVO.setGoodsBanner(StringUtils.join(imgList, ","));

            MallImg img1 = new MallImg();
            img1.setResId(goodsVO.getId());
            img1.setType("1");
            List<String> imgList1 = imgService.selectMallImgUrlVoList(img1);
            goodsVO.setGoodsDetail(StringUtils.join(imgList1, ","));
        }
        return list;
    }

    /**
     * 其他商铺/供应商商品列表
     *
     * @param mallGoodsGoods
     * @return
     */
    @Override
    public List<MallGoodsGoods> selectOtherGoodsList(MallGoodsGoods mallGoodsGoods) {
        List<MallGoodsGoods> list = mallGoodsGoodsMapper.selectOtherGoodsList(mallGoodsGoods);
        for (MallGoodsGoods goodsVO : list) {
            MallImg img = new MallImg();
            img.setResId(goodsVO.getId());
            img.setType("0");
            List<String> imgList = imgService.selectMallImgUrlVoList(img);
            goodsVO.setGoodsBanner(StringUtils.join(imgList, ","));

            MallImg img1 = new MallImg();
            img1.setResId(goodsVO.getId());
            img1.setType("1");
            List<String> imgList1 = imgService.selectMallImgUrlVoList(img1);
            goodsVO.setGoodsDetail(StringUtils.join(imgList1, ","));
        }
        return list;
    }

    /**
     * 查询商品列表
     *
     * @return 商品
     */
    @Override
    public List<MallGoodsGoods> goodsGoodsSelectList() {
        MallGoodsGoods mallGoodsGoods = new MallGoodsGoods();
        mallGoodsGoods.setStatus("0");
        return mallGoodsGoodsMapper.selectMallGoodsGoodsList(mallGoodsGoods);
    }


    /**
     * 常用清单
     *
     * @return 商品集合
     */
    @Override
    public PageInfo<IndexGoodsVO> commonGoodsList(Integer pageNum, Integer pageSize, String userId) {
        PageHelper.startPage(pageNum, pageSize);
        List<IndexGoodsVO> list = mallGoodsGoodsMapper.commonGoodsList(userId);
        if (list.size() > 0) {
            for (IndexGoodsVO indexGoodsVO : list) {
                Long goodsId = indexGoodsVO.getId();
                //规格列表
                indexGoodsVO.setProList(mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(goodsId));
            }
        }
        PageInfo<IndexGoodsVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 查询商品列表
     *
     * @param mallGoodsGoods 商品
     * @return 商品
     */
    @Transactional
    @Override
    public PageInfo<IndexGoodsVO> selectMallGoodsGoodsListByPage(Integer pageNum, Integer pageSize, MallGoodsGoodsDTO mallGoodsGoods, String userId) {
        if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsName()) && !StringUtils.isEmpty(userId)) {
            MallMemberSearchHistory search = new MallMemberSearchHistory();
            search.setGoodName(mallGoodsGoods.getGoodsName());
            search.setUserId(Long.parseLong(userId));
            List<MallMemberSearchHistoryDto> list = searchHistoryService.selectMallMemberSearchHistoryList(search);
            if (list.size() > 0) {
                MallMemberSearchHistoryDto mallMemberSearchHistory = list.get(0);
                MallMemberSearchHistory result = new MallMemberSearchHistory();
                BeanUtils.copyProperties( mallMemberSearchHistory,result);
                result.setCreateAt(DateUtils.getTime());
                searchHistoryService.updateMallMemberSearchHistory(result);
            } else {
                MallMemberSearchHistory searchHistory = new MallMemberSearchHistory();
                searchHistory.setCreateAt(DateUtils.getTime());
                searchHistory.setGoodName(mallGoodsGoods.getGoodsName());
                searchHistory.setUserId(Long.parseLong(userId));
                searchHistoryService.insertMallMemberSearchHistory(searchHistory);
            }
        }
        PageHelper.startPage(pageNum, pageSize);
//        List<IndexGoodsVO> list = mallGoodsGoodsMapper.selectMallGoodsGoodsListVO(mallGoodsGoods);
        List<IndexGoodsVO> list = mallGoodsGoodsMapper.selectMallGoodsGoodsListDTO(mallGoodsGoods);
        if (!list.isEmpty()) {
            MallMemberUser mallMemberUser = new MallMemberUser();
            // 用户信息
            if (StringUtils.isNotBlank(userId)) {
                mallMemberUser = userService.selectMallMemberUserById(Long.parseLong(userId));
            }

            try {
                CountDownLatch countDownLatch = new CountDownLatch(list.size());
                for (IndexGoodsVO indexGoodsVO : list) {
                    MallMemberUser finalMallMemberUser = mallMemberUser;
                    threadPoolTaskExecutor.execute(() -> {

                        Long goodsId = indexGoodsVO.getId();
                        //规格列表
                        //indexGoodsVO.setProList(mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(goodsId));
                        List<GoodsProductVO> proList = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(goodsId);
                        indexGoodsVO.setProList(proList);
                        // VIP价
                        if (finalMallMemberUser != null && "1".equals(finalMallMemberUser.getVip())) {
                            if (proList.size() > 1) {
                                indexGoodsVO.setVipPriceRangeHigh(proList.get(0).getPriceVip().toString());
                                indexGoodsVO.setVipPriceRangeLow(proList.get(proList.size() - 1).getPriceVip().toString());
                            } else {
                                indexGoodsVO.setVipPriceRangeHigh(proList.get(0).getPriceVip().toString());
                                indexGoodsVO.setVipPriceRangeLow(indexGoodsVO.getPriceRangeHigh());
                            }
                        } else {
                            indexGoodsVO.setPriceVip(null);
                        }
                        if (proList.size() >= 1) {
                            indexGoodsVO.setPriceRangeHigh(proList.get(0).getPrice().toString());
                            indexGoodsVO.setPriceRangeLow(proList.get(proList.size() - 1).getPrice().toString());
                            if(indexGoodsVO.getKilograms()!=null){
                                BigDecimal kilograms = new BigDecimal(indexGoodsVO.getKilograms());
                                BigDecimal pricePerKg = proList.get(0).getPrice()
                                        .divide(kilograms, 2, RoundingMode.HALF_UP)
                                        .divide(new BigDecimal(2), 2, RoundingMode.HALF_UP);
                                BigDecimal bigDecimal = pricePerKg.setScale(2, RoundingMode.HALF_UP);
                                indexGoodsVO.setKilogramsPrice(bigDecimal);
                            }
                        } else {
                            indexGoodsVO.setPriceRangeHigh(proList.get(0).getPrice().toString());
                            indexGoodsVO.setPriceRangeLow(indexGoodsVO.getPriceRangeHigh());
                        }

                        countDownLatch.countDown();
                    });
                }
                countDownLatch.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        PageInfo<IndexGoodsVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 新增商品
     *
     * @param mallGoodsGoods 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMallGoodsGoods(MallGoodsGoods mallGoodsGoods) {
        // 获取登陆用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MallShopShop mallShopShop = mallShopShopMapper.selectMallShopShopBySysUserId(loginUser.getUserId());
        if (mallShopShop != null) {
            mallGoodsGoods.setShopId(mallShopShop.getShopId());
            mallGoodsGoods.setSupplierId(-1L);
        } else {
            mallGoodsGoods.setShopId(0L);
        }
        MallShopSupplier mallShopSupplier = mallShopSupplierMapper.selectMallShopSupplierBySysUserId(loginUser.getUserId());
        if (mallShopSupplier != null) {
            mallGoodsGoods.setSupplierId(mallShopSupplier.getSupplierId());
            mallGoodsGoods.setShopId(mallShopSupplier.getShopId());
        }

        if (mallShopShop == null && mallShopSupplier == null) {
            mallGoodsGoods.setShopId(0L);
        }

        mallGoodsGoods.setCreateAt(DateUtils.getTime());
        // 默认待审核
        mallGoodsGoods.setCheckStatus(0);
        // 复制商品不审核
        if (ObjectUtils.isNotEmpty(mallGoodsGoods.getIsCopy()) && mallGoodsGoods.getIsCopy() == 1) {
            mallGoodsGoods.setCheckStatus(1);
        }
        int count = mallGoodsGoodsMapper.insertMallGoodsGoods(mallGoodsGoods);
        if (count > 0) {
            // for (MallGoodsProduct goodsProduct: mallGoodsGoods.getProList()){
            //     goodsProduct.setGoodsId(mallGoodsGoods.getId());
            //     goodsProduct.setCreateAt(DateUtils.getTime());
            //     mallGoodsProductMapper.insertMallGoodsProduct(goodsProduct);
            // }

            List<MallGoodsProduct> goodsProductList = mallGoodsGoods.getGoodsProductList();
            if (goodsProductList.size() > 0) {
                for (MallGoodsProduct goodsProduct : goodsProductList) {
                    goodsProduct.setGoodsId(mallGoodsGoods.getId());

                    if (ObjectUtils.isNotEmpty(mallGoodsGoods.getIsCopy()) && mallGoodsGoods.getIsCopy() == 0) {
                        goodsProduct.setCopyId(0L);
                    }
                }
                // 批量新增商品规格
                int i = mallGoodsProductMapper.bathInsertListMallGoodsProduct(goodsProductList);

                if (i > 0) {
                    mallGoodsProductService.setDefault(mallGoodsGoods.getId());
                    mallGoodsProductService.selectMallGoodsProductById(mallGoodsGoods.getId());
                }
            }


            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsBanner())) {
                String goodsBanner = mallGoodsGoods.getGoodsBanner();
                goodsBanner = goodsBanner.replace("[", "");
                goodsBanner = goodsBanner.replace("]", "");
                goodsBanner = goodsBanner.replace("\"", "");
                String[] urlList = goodsBanner.split(",");
                for (String urlStr : urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("0");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);
                }
            }

            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsDetail())) {
                String goodsDetail = mallGoodsGoods.getGoodsDetail();
                goodsDetail = goodsDetail.replace("[", "");
                goodsDetail = goodsDetail.replace("]", "");
                goodsDetail = goodsDetail.replace("\"", "");
                String[] urlList = goodsDetail.split(",");
                for (String urlStr : urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("1");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);
                }
            }
        }
        return count;
    }

    /**
     * 修改商品
     *
     * @param mallGoodsGoods 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMallGoodsGoods(MallGoodsGoods mallGoodsGoods) {
        // 获取登陆用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (ObjectUtils.isEmpty(loginUser)) {
            return -1;
        }
        //MallShopShop mallShopShop = mallShopShopMapper.selectMallShopShopBySysUserId(loginUser.getUserId());
        //if (mallGoodsGoods.getShopId() == null) {
        //    if (mallShopShop != null) {
        //        mallGoodsGoods.setShopId(mallShopShop.getShopId());
        //        mallGoodsGoods.setSupplierId(-1L);
        //    }
        //    else {
        //        mallGoodsGoods.setShopId(0L);
        //    }
        //}
        //MallShopSupplier mallShopSupplier = mallShopSupplierMapper.selectMallShopSupplierBySysUserId(loginUser.getUserId());
        //if (mallShopSupplier != null) {
        //    mallGoodsGoods.setSupplierId(mallShopSupplier.getSupplierId());
        //    mallGoodsGoods.setShopId(mallShopSupplier.getShopId());
        //}
        //
        //if (mallShopShop == null && mallShopSupplier == null) {
        //    mallGoodsGoods.setShopId(0L);
        //}

        mallGoodsGoods.setUpdateAt(DateUtils.getTime());
        int count = mallGoodsGoodsMapper.updateMallGoodsGoods(mallGoodsGoods);

        // 修改复制商品信息
        if (mallGoodsGoods.getIsCopy() == 0) {
            mallGoodsGoods.setCopyId(mallGoodsGoods.getId());
            mallGoodsGoodsMapper.updateCopyMallGoodsGoods(mallGoodsGoods);
        }

        if (count > 0) {
            // mallGoodsProductMapper.removeByGoodsId(mallGoodsGoods.getId());
            // for (MallGoodsProduct product: mallGoodsGoods.getProList()){
            //     product.setDelFlag("0");
            //     mallGoodsProductMapper.updateMallGoodsProduct(product);
            // }

            List<MallGoodsProduct> goodsProductList = mallGoodsGoods.getGoodsProductList();
            if (goodsProductList.size() > 0) {
                List<MallGoodsProduct> insertList = new ArrayList<>();// 新增
                List<MallGoodsProduct> updateList = new ArrayList<>();// 修改
                List<MallGoodsProduct> deleteList = new ArrayList<>();// 删除

                for (MallGoodsProduct goodsProduct : goodsProductList) {
                    if (goodsProduct.getId() == null) {
                        goodsProduct.setGoodsId(mallGoodsGoods.getId());
                        if (mallGoodsGoods.getIsCopy() == 0) {
                            goodsProduct.setCopyId(0L);
                        }
                        insertList.add(goodsProduct);
                    } else {
                        updateList.add(goodsProduct);
                    }
                }

                // 修改前商品规格
                List<MallGoodsProduct> oldProductList = mallGoodsProductMapper.selectMallGoodsProductByGoodsId(mallGoodsGoods.getId());
                if (oldProductList.size() > 0) {
                    for (MallGoodsProduct oldProduct : oldProductList) {
                        // 是否存在
                        boolean isExistence = updateList.stream().anyMatch(p -> p.getId().equals(oldProduct.getId()));
                        if (!isExistence) {
                            deleteList.add(oldProduct);
                        }
                    }
                }

                if (insertList.size() > 0) {
                    // 批量新增
                    mallGoodsProductMapper.bathInsertListMallGoodsProduct(insertList);
                }
                if (updateList.size() > 0) {
                    // 批量修改
                    // mallGoodsProductMapper.bathUpdateListMallGoodsProduct(updateList);
                    for (MallGoodsProduct product : updateList) {
                        mallGoodsProductMapper.updateMallGoodsProduct(product);
                    }
                }
                if (deleteList.size() > 0) {
                    // 批量删除
                    mallGoodsProductMapper.bathDeleteListMallGoodsProduct(deleteList);
                }

                mallGoodsProductService.setDefault(mallGoodsGoods.getId());

                // 非复制商品编辑规格 复制商品也编辑规格
                if (mallGoodsGoods.getIsCopy() == 0) {
                    if (insertList.size() > 0 || updateList.size() > 0 || deleteList.size() > 0) {
                        // 相关复制商品列表
                        List<MallGoodsGoods> copyGoodsList = mallGoodsGoodsMapper.selectMallGoodsGoodsListByCopyId(mallGoodsGoods.getId());
                        if (copyGoodsList.size() > 0) {
                            // 全删除规格
                            mallGoodsProductMapper.bathCopyDeleteListMallGoodsProduct(copyGoodsList);

                            List<MallGoodsProduct> productList = mallGoodsProductMapper.selectMallGoodsProductByGoodsId(mallGoodsGoods.getId());

                            List<MallGoodsProduct> insertCopyList = new ArrayList<>();// 新增复制商品规格
                            for (MallGoodsGoods goodsGoods : copyGoodsList) {
                                for (MallGoodsProduct goodsProduct : productList) {
                                    MallGoodsProduct product = new MallGoodsProduct();
                                    product.setGoodsId(goodsGoods.getId());
                                    product.setIsDefault(goodsProduct.getIsDefault());
                                    product.setProductName(goodsProduct.getProductName());
                                    product.setPrice(goodsProduct.getPrice());
                                    product.setPriceVip(goodsProduct.getPriceVip());
                                    product.setNum(goodsProduct.getNum());
                                    product.setCopyId(goodsProduct.getId());
                                    insertCopyList.add(product);
                                }
                            }
                            mallGoodsProductMapper.bathCopyInsertListMallGoodsProduct(insertCopyList);
                        }
                    }
                }

            } else {
                // 无规格 全删除
                mallGoodsProductMapper.removeByGoodsId(mallGoodsGoods.getId());

                List<MallGoodsGoods> copyGoodsList = mallGoodsGoodsMapper.selectMallGoodsGoodsListByCopyId(mallGoodsGoods.getId());
                if (copyGoodsList.size() > 0) {
                    // 全删除规格
                    mallGoodsProductMapper.bathCopyDeleteListMallGoodsProduct(copyGoodsList);
                }
            }

            // 复制商品图
            List<MallImg> copyGoodsImgList = new ArrayList<>();
            // 复制商品
            List<MallGoodsGoods> copyGoodsList = mallGoodsGoodsMapper.selectMallGoodsGoodsListByCopyId(mallGoodsGoods.getId());

            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsBanner())) {
                //删除来的图片重新添加
                MallImg deleteImgVO = new MallImg();
                deleteImgVO.setType("0");
                deleteImgVO.setResId(mallGoodsGoods.getId());
                imgService.deleteMallImgByImgVO(deleteImgVO);

                String goodsBanner = mallGoodsGoods.getGoodsBanner();
                goodsBanner = goodsBanner.replace("[", "");
                goodsBanner = goodsBanner.replace("]", "");
                goodsBanner = goodsBanner.replace("\"", "");
                String[] urlList = goodsBanner.split(",");
                for (String urlStr : urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("0");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);

                    if (copyGoodsList.size() > 0) {
                        for (MallGoodsGoods goodsGoods : copyGoodsList) {
                            MallImg copyBannerImg = new MallImg();
                            copyBannerImg.setImg(urlStr);
                            copyBannerImg.setType("0");
                            copyBannerImg.setResId(goodsGoods.getId());
                            copyBannerImg.setCreateAt(DateUtils.getTime());
                            copyGoodsImgList.add(copyBannerImg);
                        }
                    }


                }
            }

            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsDetail())) {
                //删除来的图片重新添加
                MallImg deleteImgVO1 = new MallImg();
                deleteImgVO1.setType("1");
                deleteImgVO1.setResId(mallGoodsGoods.getId());
                imgService.deleteMallImgByImgVO(deleteImgVO1);

                String goodsDetail = mallGoodsGoods.getGoodsDetail();
                goodsDetail = goodsDetail.replace("[", "");
                goodsDetail = goodsDetail.replace("]", "");
                goodsDetail = goodsDetail.replace("\"", "");
                String[] urlList = goodsDetail.split(",");
                for (String urlStr : urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("1");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);

                    if (copyGoodsList.size() > 0) {
                        for (MallGoodsGoods goodsGoods : copyGoodsList) {
                            MallImg copyDetailImg = new MallImg();
                            copyDetailImg.setImg(urlStr);
                            copyDetailImg.setType("1");
                            copyDetailImg.setResId(goodsGoods.getId());
                            copyDetailImg.setCreateAt(DateUtils.getTime());
                            copyGoodsImgList.add(copyDetailImg);
                        }
                    }

                }
            } else {
                MallImg deleteImgVO1 = new MallImg();
                deleteImgVO1.setType("1");
                deleteImgVO1.setResId(mallGoodsGoods.getId());
                imgService.deleteMallImgByImgVO(deleteImgVO1);
            }


            if (copyGoodsList.size() > 0) {
                // 批量删除图片信息
                imgService.batchDeleteMallImgByResId(copyGoodsList);

                if (copyGoodsImgList.size() > 0) {
                    imgService.batchInsertMallImgByList(copyGoodsImgList);
                }

            }
        }
        return count;
    }

    /**
     * 修改审核状态
     *
     * @param mallGoodsGoods
     * @return
     */
    @Override
    public AjaxResult updateCheckStatus(MallGoodsGoods mallGoodsGoods) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        if (userId == 1L) {
            mallGoodsGoods.setUpdateAt(DateUtils.getTime());
            return AjaxResult.toAjax(mallGoodsGoodsMapper.updateMallGoodsGoods(mallGoodsGoods));

        } else {
            return AjaxResult.error("缺少审核权限");
        }

    }

    /**
     * 修改供应商
     *
     * @param mallGoodsGoods
     * @return
     */
    @Override
    public AjaxResult updateSupplier(MallGoodsGoods mallGoodsGoods) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        if (userId == 1L) {
            if (ObjectUtils.isEmpty(mallGoodsGoods.getSupplierArr()) || mallGoodsGoods.getSupplierArr().length == 0) {
                mallGoodsGoods.setSupplierId(-1L);
            } else {
                Long[] supplierIds = Arrays.stream(mallGoodsGoods.getSupplierArr())
                        .map(Long::valueOf)
                        .toArray(Long[]::new);
                mallGoodsGoods.setSupplierId(mallGoodsGoods.getSupplierId());
            }
            return AjaxResult.toAjax(mallGoodsGoodsMapper.updateMallGoodsGoods(mallGoodsGoods));
        } else {
            return AjaxResult.error("缺少修改供应商权限");
        }
    }

    /**
     * 修改销量
     *
     * @return 结果
     */
    @Override
    public int updateMallGoodsGoodsSaleNum(Integer goodsId, Integer count) {
        return mallGoodsGoodsMapper.updateMallGoodsGoodsSaleNum(goodsId, count);
    }

    /**
     * 修改库存
     *
     * @return 结果
     */
    @Override
    public int updateMallGoodsGoodsStock(Integer goodsId, Integer count) {
        return mallGoodsGoodsMapper.updateMallGoodsGoodsStock(goodsId, count);
    }

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

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

    @Override
    public List<IndexGoodsVO> selectMallGoodsBySales() {
        return mallGoodsGoodsMapper.selectMallGoodsBySales();
    }

    @Override
    public List<IndexGoodsVO> selectMallGoodsByCreatTime() {
        return mallGoodsGoodsMapper.selectMallGoodsByCreatTime();
    }

    @Override
    public List<IndexGoodsVO> selectMallGoodsByhot() {
        return mallGoodsGoodsMapper.selectMallGoodsByhot();
    }

    @Override
    public List<IndexGoodsVO> selectMallGoodsByTag(Integer tagId) {
        return mallGoodsGoodsMapper.selectMallGoodsByTag(tagId);
    }

    @Override
    public List<IndexGoodsVO> selectIndexMallGoodsByTag(Integer tagId, Integer pageSize) {
        return mallGoodsGoodsMapper.selectIndexMallGoodsByTag(tagId, pageSize);
    }

    @Override
    public IndexGoodsVO selectMallGoodsGoodsByIdVO(Map<String, Object> params) {
        Long goodsId = Long.parseLong(params.get("goodsId").toString());
        IndexGoodsVO goods = mallGoodsGoodsMapper.selectMallGoodsGoodsByIdVO(goodsId);
        if (goods != null) {
            List<GoodsProductVO> list = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(goodsId);
            // VIP价
            long userId = Long.parseLong(params.get("userId").toString());
            MallMemberUser mallMemberUser = userService.selectMallMemberUserById(userId);
            if (mallMemberUser != null && "1".equals(mallMemberUser.getVip())) {
                goods.setPrice(goods.getPriceVip().toString());
                if (list.size() > 0) {
                    for (GoodsProductVO goodsProductVO : list) {
                        goodsProductVO.setPrice(goodsProductVO.getPriceVip());
                    }
                }
            }
            goods.setProList(list);

            MallImg mallImg = new MallImg();
            mallImg.setResId(goods.getId());
            mallImg.setType("0");
            List<String> bannerlist = imgService.selectMallImgUrlVoList(mallImg);
            goods.setBanners(bannerlist);

            mallImg.setType("1");
            List<String> detailList = imgService.selectMallImgUrlVoList(mallImg);
            goods.setDetailUrl(detailList);

            //秒杀信息
            SeckillGoodsVO seckillGoodsVO = mallSeckillGoodsMapper.seckillGoodsInfo(params);
            if (ObjectUtils.isNotEmpty(seckillGoodsVO)) {
                goods.setSeckillGoodsVO(seckillGoodsVO);
            }

        }

        int commentTotle = orderCommentService.selectCountByGoodsId(goodsId);
        goods.setCommentTotle(commentTotle);

        //评论图片
        List<Map<String, Object>> commtentList = orderCommentService.selectTwoRecordByGoodsId(goodsId);
        for (Map<String, Object> map : commtentList) {
            String classId = map.get("id").toString();
            MallImg mallImg = new MallImg();
            mallImg.setResId(Long.parseLong(classId));
            mallImg.setType("2");
//            List<String> bannerlist = imgService.selectMallImgUrlVoList(mallImg);
            List<String> imgList = imgService.selectMallImgUrlVoList(mallImg);
            map.put("imgList", imgList);
        }
        goods.setCommentList(commtentList);

        //收藏状态
        String userId = params.get("userId").toString();
        if (StringUtils.isEmpty(userId)) {
            goods.setIsCollect("0");
        } else {
            MemberCollectVO collectVO = new MemberCollectVO();
            collectVO.setGoodsId(goodsId);
            collectVO.setMemberId(Long.parseLong(userId));
            MemberCollectVO resultCollect = userService.selectIsCollectBy(collectVO);
            if (resultCollect == null) {
                goods.setIsCollect("0");
            } else {
                goods.setIsCollect("1");
            }
        }
        return goods;
    }

    /**
     * 业务员查询所有商品
     *
     * @param params sort 排序：0-默认排序，1-价格从高到低，2-价格从低到高，3-提成从高到低，4-提成从低到高
     * @return 商品集合
     */
    @Override
    public List<Map<String, Object>> getSalesmanAllGoodsList(Map<String, Object> params) {
        return mallGoodsGoodsMapper.getSalesmanAllGoodsList(params);
    }

    /**
     * 查询筛选商品列表（商品导出）
     *
     * @param mallGoodsGoods 商品
     * @return 商品集合
     */
    @Override
    public List<MallGoodsGoodsExportVO> selectExportScreenGoodsList(MallGoodsGoods mallGoodsGoods) {
        return mallGoodsGoodsMapper.selectExportScreenGoodsList(mallGoodsGoods);
    }

    /**
     * 查询勾选商品列表（商品导出）
     *
     * @param goodsIds 商品ID
     * @return 商品集合
     */
    @Override
    public List<MallGoodsGoodsExportVO> selectExportCheckGoodsList(Long[] goodsIds) {
        return mallGoodsGoodsMapper.selectExportCheckGoodsList(goodsIds);
    }

    /**
     * 小程序上架审核隐藏商品、分类等
     *
     * @param params 参数
     * @return 结果
     */
    @Override
    public int updateXcxReviewHidden(Map<String, Object> params) {
        int showStatus = Integer.parseInt(params.get("showStatus").toString());
        mallGoodsGoodsMapper.updateXcxReviewHiddenGoods(showStatus);
        mallGoodsGoodsMapper.updateXcxReviewHiddenGoodsClass(showStatus);
        return 1;
    }

    /**
     * 批量删除复制商品
     *
     * @param ids 需要删除的商品主键集合
     * @return 结果
     */
    @Override
    public int deleteCopyMallGoodsGoodsByCopyIds(Long[] ids) {
        return mallGoodsGoodsMapper.deleteCopyMallGoodsGoodsByCopyIds(ids);
    }
    @Override
    public AjaxResult selectgoodssort() {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("code",200);
        ajaxResult.put("msg","查询成功");
        ajaxResult.put("data",mallGoodsGoodsMapper.selectgoodssort());
        return ajaxResult;
    }

    @Override
    public AjaxResult selectallGoods() {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("code",200);
        ajaxResult.put("msg","查询成功");
        ajaxResult.put("data",mallGoodsGoodsMapper.selectallGoods());
        return ajaxResult;
    }
}
