package com.gree.mall.manager.logic.goods;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.activity.PromotionGoods;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.*;
import com.gree.mall.manager.commonmapper.CustomGoodsMapper;
import com.gree.mall.manager.commonmapper.GoodsCheckMapper;
import com.gree.mall.manager.constant.Constant;
import com.gree.mall.manager.enums.FreightTypeEnum;
import com.gree.mall.manager.enums.GoodsTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.common.FucaiLogic;
import com.gree.mall.manager.logic.user.UserLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GoodsLogic {
    @Resource
    CommonLogic commonLogic;
    @Autowired
    FucaiLogic fucaiLogic;

    @Resource
    CustomGoodsMapper customGoodsMapper;
    @Resource
    GoodsService goodsService;
    @Resource
    GoodsSpecService goodsSpecService;
    @Autowired
    GoodsTagRelaService goodsTagRelaService;

    @Resource
    SecKillActivityService secKillActivityService;
    @Resource
    SecKillActivitySpecService secKillActivitySpecService;
    @Autowired
    private CarouselMapService carouselMapService;
    @Autowired
    private GoodsCheckMapper goodsCheckMapper;
    @Autowired
    private GoodsTemplateService goodsTemplateService;
    @Autowired
    private CommonFileService commonFileService;
    @Value("${goods.share.limit.percent}")
    private String percentLimit;
    @Autowired
    GoodsPackagePopService goodsPackagePopService;
    @Autowired
    GoodsPackageUserRelaService goodsPackageUserRelaService;
    @Autowired
    GoodsMaterialService goodsMaterialService;
    @Autowired
    UserLogic userLogic;
    @Autowired
    GoodsMaterialStorageService goodsMaterialStorageService;

    /**
     * 商品列表
     *
     * @param flag
     * @param keyword
     * @param startPrice
     * @param endPrice
     * @param startShare
     * @param endShare
     * @param goodsSortJson
     * @param categoryId
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<GoodsSpecBean> page(String isTrade,String flag, String keyword, BigDecimal startPrice, BigDecimal endPrice,
                                     BigDecimal startShare, BigDecimal endShare,
                                     String goodsSortJson, String categoryId, Boolean status,List<String> goodsTypes,
                                     Integer pageNum, Integer pageSize, HttpServletRequest request) {

        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        String sortStr = null;
        if (goodsSortJson != null && !goodsSortJson.trim().equals("")) {
            JSONArray goodsSortBeanArray = JSON.parseArray(StringEscapeUtils.unescapeJava(goodsSortJson));
            sortStr = GoodsSortBean.convertColumn(goodsSortBeanArray);
        }
        List<String> categoryIds = new ArrayList<>();
        if (StringUtils.isNotBlank(categoryId)) {
            categoryIds.add(categoryId);
        }
        if(CollectionUtils.isEmpty(goodsTypes)){
            goodsTypes = new ArrayList<>();
            goodsTypes.add(GoodsTypeEnum.COMMON.toString());
        }

        IPage<GoodsSpecBean> goodsSpecBeanIPage = customGoodsMapper.pageList(new Page<>(pageNum, pageSize),isTrade, flag, keyword, startPrice,
                endPrice, startShare, endShare, sortStr, categoryIds, status, goodsTypes,companyWechatIds);

        //商品规格
        List<GoodsSpecBean> records = new ArrayList<>();
        for (GoodsSpecBean goodsSpecBean : goodsSpecBeanIPage.getRecords()) {
            String goodsId = goodsSpecBean.getGoodsId();
            List<GoodsSpec> list = goodsSpecService.lambdaQuery().eq(GoodsSpec::getGoodsId, goodsId).list();
            List<GoodsSpecVO> goodsSpecVOS = BeanUtil.copyToList(list, GoodsSpecVO.class);
            for(GoodsSpecVO goodsSpecVO : goodsSpecVOS){
                GoodsMaterial goodsMaterial = goodsMaterialService.getById(goodsSpecVO.getGoodsCode());

                List<GoodsMaterialStorage> goodsMaterialStorages = goodsMaterialStorageService.lambdaQuery().eq(GoodsMaterialStorage::getGoodsMaterialId, goodsSpecVO.getGoodsCode())
                        .list();
                if(goodsMaterial != null){
                    goodsSpecVO.setGoodsMaterialName(goodsMaterial.getGoodsName());

                    goodsSpecVO.setGoodsMaterialStock(goodsMaterialStorages.stream().map(GoodsMaterialStorage::getStockQty).reduce(Integer::sum).orElse(0));

                    goodsSpecBean.setAllStockNum(goodsSpecBean.getAllStockNum() != null?goodsSpecBean.getAllStockNum()+goodsMaterialStorages.stream().map(GoodsMaterialStorage::getStockQty).reduce(Integer::sum).orElse(0):
                            goodsMaterialStorages.stream().map(GoodsMaterialStorage::getStockQty).reduce(Integer::sum).orElse(0));
                }
            }
            goodsSpecBean.setGoodsSpecs(goodsSpecVOS);
            records.add(goodsSpecBean);
        }
        goodsSpecBeanIPage.setRecords(records);
        return goodsSpecBeanIPage;
    }


    /**
     * 套购商品列表
     * @param keyword
     * @param startPrice
     * @param endPrice
     * @param startShare
     * @param endShare
     * @param goodsSortJson
     * @param categoryId
     * @param status
     * @param pageNum
     * @param pageSize
     * @param request
     * @return
     */
    public IPage<GoodsPackageList> packageList( String keyword, BigDecimal startPrice, BigDecimal endPrice,
                                     BigDecimal startShare, BigDecimal endShare,
                                     String goodsSortJson, String categoryId, Boolean status,
                                     Integer pageNum, Integer pageSize, HttpServletRequest request) {

        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        String sortStr = null;
        if (goodsSortJson != null && !goodsSortJson.trim().equals("")) {
            JSONArray goodsSortBeanArray = JSON.parseArray(StringEscapeUtils.unescapeJava(goodsSortJson));
            sortStr = GoodsSortBean.convertColumn(goodsSortBeanArray);
        }
        List<String> categoryIds = new ArrayList<>();
        if (StringUtils.isNotBlank(categoryId)) {
            categoryIds.add(categoryId);
        }

        IPage<GoodsPackageList> goodsPackageListIPage = customGoodsMapper.queryGoodsPackageList(new Page<>(pageNum, pageSize), keyword, startPrice,
                endPrice, startShare, endShare, sortStr, categoryIds, status, companyWechatIds);

        return goodsPackageListIPage;
    }


    /**
     * 根据类型查询商品
     * @param categoryIds
     * @param request
     * @return
     */
    public List<GoodsSpecBean> listbycategory(List<String> categoryIds, HttpServletRequest request) {

        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();


        IPage<GoodsSpecBean> goodsSpecBeanIPage = customGoodsMapper.pageList(new Page<>(1, -1), null,null, null, null,
                null, null, null, null, categoryIds, null, null,companyWechatIds);
        //添加规格
        List<GoodsSpecBean> records = goodsSpecBeanIPage.getRecords();
        for (GoodsSpecBean record : records) {
            List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery()
                    .eq(GoodsSpec::getGoodsId, record.getGoodsId())
                    .eq(GoodsSpec::getDel, false)
                    .list();

            List<GoodsSpecVO> goodsSpecVOS = BeanUtil.copyToList(goodsSpecs, GoodsSpecVO.class);
            for(GoodsSpecVO goodsSpecVO : goodsSpecVOS){
                GoodsMaterial goodsMaterial = goodsMaterialService.getById(goodsSpecVO.getGoodsCode());
                if(goodsMaterial != null){
                    goodsSpecVO.setGoodsMaterialName(goodsMaterial.getGoodsName());
                    goodsSpecVO.setGoodsMaterialStock(goodsMaterial.getStockQty());
                    goodsSpecVO.setCostAmount(goodsMaterial.getCostAmount());
                }
            }
            record.setGoodsSpecs(goodsSpecVOS);
        }
        goodsSpecBeanIPage.setRecords(records);
        return goodsSpecBeanIPage.getRecords();
    }


    /**
     * 商品上下架
     *
     * @param goodsId
     * @param status
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(String goodsId, Boolean status) throws RemoteServiceException {
        if (!status) {
            List<SecKillActivitySpec> secKillActivitySpecs = secKillActivitySpecService.lambdaQuery()
                    .eq(SecKillActivitySpec::getGoodsId, goodsId)
                    .list();
            Integer activityCount = 0;
            for (SecKillActivitySpec secKillActivitySpec : secKillActivitySpecs) {

                activityCount += secKillActivityService.lambdaQuery()
                        .eq(SecKillActivity::getSecKillId, secKillActivitySpec.getSecKillId())
                        .ge(SecKillActivity::getEndTime, new Date())
                        .eq(SecKillActivity::getStatus, true)
                        .eq(SecKillActivity::getDel, false)
                        .count();
            }

            if (activityCount > 0) {
                throw new RemoteServiceException("商品处于秒杀活动中，操作失败!");
            }
        }
        goodsService.lambdaUpdate()
                .eq(Goods::getGoodsId, goodsId)
                .set(Goods::getStatus, status)
                .update();

        if (!status) {
            carouselMapService.lambdaUpdate().eq(CarouselMap::getGoodsId, goodsId).remove();
        }
    }


    /**
     * 删除商品
     *
     * @param goodsId
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String goodsId) throws RemoteServiceException {
        //检查是否存在秒杀活动
        List<SecKillActivitySpec> secKillActivitySpecs = secKillActivitySpecService.lambdaQuery()
                .eq(SecKillActivitySpec::getGoodsId, goodsId)
                .list();
        Integer activityCount = 0;
        for (SecKillActivitySpec secKillActivitySpec : secKillActivitySpecs) {

            activityCount += secKillActivityService.lambdaQuery()
                    .eq(SecKillActivity::getSecKillId, secKillActivitySpec.getSecKillId())
                    .ge(SecKillActivity::getEndTime, new Date())
                    .eq(SecKillActivity::getStatus, true)
                    .eq(SecKillActivity::getDel, false)
                    .count();
        }

        if (activityCount > 0) {
            throw new RemoteServiceException("商品处于秒杀活动中，操作删除失败!");
        }

        //检查是否在上架状态
        Integer count = goodsService.lambdaQuery()
                .eq(Goods::getGoodsId, goodsId)
                .eq(Goods::getStatus, true)
                .count();
        if (count > 0) {
            throw new RemoteServiceException("商品处于上架状态，操作删除失败!");
        }

        goodsService.lambdaUpdate()
                .eq(Goods::getGoodsId, goodsId)
                .remove();
        goodsSpecService.lambdaUpdate().eq(GoodsSpec::getGoodsId, goodsId).remove();
    }

    /**
     * 商品详情
     * @param goodsId
     * @return
     */
    public GoodsSpecBean detail(String goodsId) throws RemoteServiceException {
        Goods goods = goodsService.getById(goodsId);
        List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery()
                .eq(GoodsSpec::getGoodsId, goodsId)
                .eq(GoodsSpec::getDel, false)
                .list();



        //商品库存
        Integer goodsStock = goodsSpecs.stream().collect(Collectors.summingInt(x -> x.getStockNum()));

        GoodsSpecBean goodsBean = new GoodsSpecBean();
        if (goods == null) {
            throw new RemoteServiceException("商品不存在");
        }
        BeanUtils.copyProperties(goods, goodsBean);


        List<GoodsSpecVO> goodsSpecVOS = BeanUtil.copyToList(goodsSpecs, GoodsSpecVO.class);
        for(GoodsSpecVO goodsSpecVO : goodsSpecVOS){
            GoodsMaterial goodsMaterial = goodsMaterialService.getById(goodsSpecVO.getGoodsCode());

            List<GoodsMaterialStorage> goodsMaterialStorages = goodsMaterialStorageService.lambdaQuery().eq(GoodsMaterialStorage::getGoodsMaterialId, goodsSpecVO.getGoodsCode())
                    .list();

            if(goodsMaterial != null){
                goodsSpecVO.setGoodsMaterialName(goodsMaterial.getGoodsName());
                goodsSpecVO.setGoodsMaterialStock(goodsMaterial.getStockQty());
                goodsSpecVO.setCostAmount(goodsMaterial.getCostAmount());

                goodsSpecVO.setGoodsMaterialName(goodsMaterial.getGoodsName());

                goodsSpecVO.setGoodsMaterialStock(goodsMaterialStorages.stream().map(GoodsMaterialStorage::getStockQty).reduce(Integer::sum).orElse(0));

                goodsSpecVO.setCostAmount(goodsMaterial.getCostAmount());
            }
        }
        goodsBean.setGoodsSpecs(goodsSpecVOS);
        goodsBean.setImages(commonLogic.queryFileByObjId(goods.getGoodsId(), Constant.Img.GOODS_IMG));
        goodsBean.setStock(goodsStock);
        List<GoodsTemplate> goodsTemplates = goodsTemplateService.lambdaQuery()
                .eq(GoodsTemplate::getGoodsId, goodsId)
                .orderByDesc(GoodsTemplate::getCreateTime)
                .list();
        if (goodsTemplates != null && goodsTemplates.size() > 0) {
            goodsBean.setTemplateId(goodsTemplates.get(0).getTemplateId());
        }
        //查询商品标签
        List<GoodsTagRela> goodsTagRela = goodsTagRelaService.lambdaQuery().eq(GoodsTagRela::getGoodsId, goodsId)
                .eq(GoodsTagRela::getType,1).list();
        if(goodsTagRela.size() > 0){
            List<String> tagList = goodsTagRela.stream().map(GoodsTagRela::getGoodsTagName).collect(Collectors.toList());
            goodsBean.setTags(tagList);
        }

        List<GoodsTagRela> goodsTagRelas = goodsTagRelaService.lambdaQuery().eq(GoodsTagRela::getGoodsId, goodsId)
                .eq(GoodsTagRela::getType,2).list();
        if(goodsTagRelas.size() > 0){
            List<String> tagList = goodsTagRelas.stream().map(GoodsTagRela::getGoodsTagName).collect(Collectors.toList());
            goodsBean.setTagsLabel(tagList);
        }
        if(StringUtils.equals(goodsBean.getGoodsType(),GoodsTypeEnum.PACKAGE.toString())) {
            //套购商品--指定人员列表
            goodsBean.setUsers(this.getPackageUseUserList(goodsBean.getGoodsId(), null));
        }

        return goodsBean;
    }

    /**
     * 套购商品-商品配置列表
     */
    public List<GoodsPackageBean> popList(String goodsId,Integer type){
        //套购商品
        Goods goods = goodsService.getById(goodsId);
        if(!StringUtils.equals(goods.getGoodsType(),GoodsTypeEnum.PACKAGE.toString())){
            throw new RemoteServiceException("非套餐商品");
        }

        //套购商品--商品配置
        List<GoodsPackagePop> list = goodsPackagePopService.lambdaQuery()
                .eq(GoodsPackagePop::getGoodsPackageId, goodsId)
                .eq(GoodsPackagePop::getType,type).list();

        Map<String,List<GoodsPackagePopBean>> map = new LinkedHashMap<>();
        for (GoodsPackagePop bean : list) {
            List<GoodsPackagePopBean> goodsPackagePops = map.get(bean.getGoodsId());
            if(goodsPackagePops == null){
                goodsPackagePops = new ArrayList<>();
            }
            GoodsPackagePopBean newBean = new GoodsPackagePopBean();
            BeanUtils.copyProperties(bean,newBean);

            GoodsSpec goodsSpec = goodsSpecService.getById(bean.getGoodsSpecId());
            newBean.setSpecName(goodsSpec.getName());
            newBean.setSpecValue(goodsSpec.getSpecValue());
            newBean.setStock(goodsSpec.getStockNum());

            goodsPackagePops.add(newBean);
            map.put(bean.getGoodsId(),goodsPackagePops);
        }
        //商品
        List<GoodsPackageBean> goodsList = new ArrayList<>();
        for(String gdsId : map.keySet()){

            Goods nGoods = goodsService.getById(gdsId);

            GoodsPackagePopBean goodsPackagePop = map.get(gdsId).get(0);
            GoodsPackageBean bean = new GoodsPackageBean();
            bean.setImgUrl(nGoods.getImgUrl());
            bean.setGoodsName(nGoods.getGoodsName());
            bean.setGoodsPackagePopList(map.get(gdsId));
            bean.setSortNum(goodsPackagePop.getSortNum());
            goodsList.add(bean);
        }
      return goodsList;
    }



    /**
     * 添加商品
     *
     * @param goodsBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsBean goodsBean, HttpServletRequest request) throws RemoteServiceException {
        if (StringUtils.equals(goodsBean.getGoodsType(),GoodsTypeEnum.COMMON.toString())
                && (goodsBean.getGoodsSpecs() == null || goodsBean.getGoodsSpecs().size() == 0)) {
            //如果是规格没有抛出异常
            throw new RemoteServiceException("至少要有一个规格!");
        }
        //设置企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }
        goodsBean.setCompanyWechatId(adminUser.getCompanyWechatId());
        goodsBean.setCompanyName(adminUser.getCompanyName());

        Date creatDate = new Date();
        List<GoodsSpec> goodsSpecList = goodsBean.getGoodsSpecs();
        if(CollectionUtils.isNotEmpty(goodsSpecList)) {
            Collections.sort(goodsSpecList, (o1, o2) -> o1.getPrice().compareTo(o2.getPrice()));
            goodsBean.setGoodsPrice(goodsSpecList.get(0).getPrice());
            goodsBean.setOrgGoodsPrice(goodsSpecList.get(0).getOrgPrice());
        }
        goodsBean.setCreateTime(creatDate);
        goodsService.save(goodsBean);

        if(CollectionUtils.isNotEmpty(goodsBean.getGoodsSpecs())) {

            List<GoodsSpec> goodsSpecs = goodsBean.getGoodsSpecs();
            for(GoodsSpec goodsSpec:goodsSpecs){

                GoodsMaterial goodsMaterial = goodsMaterialService.getById(goodsSpec.getGoodsCode());
                if(goodsMaterial != null){
                    goodsSpec.setSpecValue(goodsMaterial.getSpecsName());
                }

                goodsSpec.setGoodsId(goodsBean.getGoodsId())
                        .setCompanyWechatId(goodsBean.getCompanyWechatId())
                        .setCompanyName(goodsBean.getCompanyName())
                        .setCreateTime(creatDate).setDel(false)
                        //.setSpecValue(goodsSpec.getSpecValue())
                        .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getShareAmount())) //限制金额40%
                        .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getSharePercent() != null  //分销比列不为0覆盖分销金额
                                && goodsSpec.getSharePercent().compareTo(new Double("0.00")) > 0 ?
                                goodsSpec.getPrice().multiply(new BigDecimal(goodsSpec.getSharePercent() / 100.0))
                                        .setScale(2, BigDecimal.ROUND_DOWN)
                                : goodsSpec.getShareAmount()))
                        .setInnerShareAmount(getInnerShareAmount(goodsSpec));//需最后设置
            }

        }

        if (StringUtils.isNotBlank(goodsBean.getTemplateId())) {
            GoodsTemplate goodsTemplate = new GoodsTemplate();
            goodsTemplate.setGoodsId(goodsBean.getGoodsId());
            goodsTemplate.setTemplateId(goodsBean.getTemplateId());
            goodsTemplate.setCreateTime(new Date());
            goodsTemplate.setCompanyWechatId(goodsBean.getCompanyWechatId());
            goodsTemplate.setCompanyName(goodsBean.getCompanyName());
            goodsTemplateService.save(goodsTemplate);
        }

        //查询物料信息
        fucaiLogic.getWuliao(goodsSpecList);
        //批量保存商品规格
        if(CollectionUtils.isNotEmpty(goodsSpecList))
            goodsSpecService.saveBatch(goodsSpecList);

        //保存轮播图
        if (goodsBean.getImages() != null && goodsBean.getImages().size() > 0) {
            List<String> imageIdList = goodsBean.getImages().stream().map(CommonFile::getId).collect(Collectors.toList());
            commonLogic.bindFile(goodsBean.getGoodsId(), Constant.Img.GOODS_IMG, imageIdList);
        }
        //save tags
        this.saveGoodsTagRela(goodsBean.getTags(),goodsBean.getGoodsId(),1);
        this.saveGoodsTagRela(goodsBean.getTagsLabel(),goodsBean.getGoodsId(),2);

        //套购商品处理
        //this.saveGoodsPackage(goodsBean);
    }

    /**
     * 保存标签
     */
    public void saveGoodsTagRela(List<String> tags,String goodsId,Integer type){

        if(CollectionUtils.isEmpty(tags)){
            goodsTagRelaService.lambdaUpdate().eq(GoodsTagRela::getGoodsId,goodsId).eq(GoodsTagRela::getType,type).remove();
            return;
        }
        //先删后加
        goodsTagRelaService.lambdaUpdate().eq(GoodsTagRela::getGoodsId,goodsId).eq(GoodsTagRela::getType,type).remove();
        for(String tag:tags){
            GoodsTagRela goodsTagRela = new GoodsTagRela();
            goodsTagRela.setGoodsTagName(tag);
            goodsTagRela.setCreateTime(new Date());
            goodsTagRela.setGoodsId(goodsId);
            goodsTagRela.setType(type);
            goodsTagRela.insert();
        }

    }


    /**
     *  限制最大分账
     * @param price
     * @param shareAmount
     * @return
     */
    private BigDecimal limitShareAmount(BigDecimal price, BigDecimal shareAmount) {
        if(price == null){
            throw new RemoteServiceException("销售价不能为空");
        }
        if(shareAmount == null){
            throw new RemoteServiceException("佣金或分销金额不能为空");
        }
        BigDecimal shareLimit = price.multiply(new BigDecimal(percentLimit));
        return shareAmount.compareTo(shareLimit) < 1 ?
                shareAmount.setScale(2, BigDecimal.ROUND_DOWN)
                : shareLimit.setScale(2, BigDecimal.ROUND_DOWN);
    }

    /**
     * 获取内部分销金额
     */
    private BigDecimal getInnerShareAmount(GoodsSpec goodsSpec) {
        BigDecimal innerShareAmount = goodsSpec.getInnerShareAmount();
        Double innerSharePercent = goodsSpec.getInnerSharePercent();
        BigDecimal price = goodsSpec.getPrice();

        //以内部分销比列为准
        if (innerSharePercent != null && innerSharePercent.compareTo(new Double("0.00")) > 0) {
            // price * innerSharePercent/100 = 内部分销金额
            innerShareAmount = price.multiply(new BigDecimal(innerSharePercent / 100.0)).setScale(2, BigDecimal.ROUND_DOWN);

            return limitShareAmount(price, innerShareAmount);
        }
        //没有比列有金额以金额为准
        else if (innerShareAmount != null) {
            goodsSpec.setInnerSharePercent(new Double("0.00"));
            return limitShareAmount(price, innerShareAmount);
        }

        goodsSpec.setInnerSharePercent(goodsSpec.getSharePercent());
        return goodsSpec.getShareAmount();
    }

    /**
     * 编辑商品
     *
     * @param goodsBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(GoodsBean goodsBean, HttpServletRequest request) throws RemoteServiceException {

        //检查是否存在秒杀活动
        if (StringUtils.equals(goodsBean.getGoodsType(),GoodsTypeEnum.COMMON.toString())
                && (goodsBean.getGoodsSpecs() == null || goodsBean.getGoodsSpecs().size() == 0)) {
            throw new RemoteServiceException("至少要有一个规格!");
        }

        //设置企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }
        goodsBean.setCompanyWechatId(adminUser.getCompanyWechatId());
        goodsBean.setCompanyName(adminUser.getCompanyName());



        List<GoodsSpec> notRemoveList = new ArrayList<>();
        //查找未删除的规格
        if(CollectionUtils.isNotEmpty(goodsBean.getGoodsSpecs())) {
            notRemoveList = goodsBean.getGoodsSpecs().stream()
                    .filter(goodsSpec -> StringUtils.isNotBlank(goodsSpec.getGoodsSpecId()))
                    .map(goodsSpec -> goodsSpec.setGoodsId(goodsBean.getGoodsId())
                            .setCompanyWechatId(goodsBean.getCompanyWechatId())
                            .setCompanyName(goodsBean.getCompanyName())
                            .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getShareAmount()))  //限制金额40%
                            .setShareAmount(limitShareAmount(goodsSpec.getPrice(),      //比列>0 覆盖分销金额
                                    goodsSpec.getSharePercent() != null && goodsSpec.getSharePercent().compareTo(new Double("0.00")) > 0 ?
                                            goodsSpec.getPrice().multiply(new BigDecimal(goodsSpec.getSharePercent() / 100.0)).setScale(2, BigDecimal.ROUND_DOWN)
                                            : goodsSpec.getShareAmount()
                            ))
                            .setInnerShareAmount(getInnerShareAmount(goodsSpec))//需最后设置
                    )
                    .collect(Collectors.toList());


            //更新主表信息
            List<GoodsSpec> goodsSpecList = goodsBean.getGoodsSpecs();
            if(CollectionUtils.isNotEmpty(goodsSpecList)) {
                Collections.sort(goodsSpecList, (o1, o2) -> o1.getPrice().compareTo(o2.getPrice()));
                goodsBean.setGoodsPrice(goodsSpecList.get(0).getPrice());
                goodsBean.setOrgGoodsPrice(goodsSpecList.get(0).getOrgPrice());
            }
            //查询物料信息
            fucaiLogic.getWuliao(goodsSpecList);
        }
        goodsService.updateById(goodsBean);

        //未删除的规格id
        List<String> goodsSpecIds = notRemoveList.stream().map(GoodsSpec::getGoodsSpecId).collect(Collectors.toList());

        //更新轮播图
        List<String> imageIdList = goodsBean.getImages().stream()
                .map(CommonFile::getId)
                .collect(Collectors.toList());
        commonLogic.bindFile(goodsBean.getGoodsId(), Constant.Img.GOODS_IMG, imageIdList);
        //更改不在未删除规格list里面的规格id为删除状态
        goodsSpecService.lambdaUpdate()
                .eq(GoodsSpec::getGoodsId, goodsBean.getGoodsId())
                .notIn(!CollectionUtils.isEmpty(goodsSpecIds), GoodsSpec::getGoodsSpecId, goodsSpecIds)
                .set(GoodsSpec::getDel, true)
                .update();

        if (notRemoveList.size() > 0) {
            //更改存在的规格内容
            goodsSpecService.updateBatchById(notRemoveList);
        }
        //查找规格id为空的 添加到从表
        if(CollectionUtils.isNotEmpty(goodsBean.getGoodsSpecs())) {

            List<GoodsSpec> addGoodsSpecList = goodsBean.getGoodsSpecs();
            for(GoodsSpec goodsSpec:addGoodsSpecList){

                GoodsMaterial goodsMaterial = goodsMaterialService.getById(goodsSpec.getGoodsCode());
                if(goodsMaterial != null){
                    goodsSpec.setSpecValue(goodsMaterial.getSpecsName());
                }

                goodsSpec.setGoodsId(goodsBean.getGoodsId())
                        .setCompanyWechatId(goodsBean.getCompanyWechatId())
                        .setCompanyName(goodsBean.getCompanyName())
                        //.setSpecValue(goodsSpec.getSpecValue())
                        .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getShareAmount())) //限制金额40%
                        .setShareAmount(limitShareAmount(goodsSpec.getPrice(), goodsSpec.getSharePercent() != null  //分销比列不为0覆盖分销金额
                                && goodsSpec.getSharePercent().compareTo(new Double("0.00")) > 0 ?
                                goodsSpec.getPrice().multiply(new BigDecimal(goodsSpec.getSharePercent() / 100.0))
                                        .setScale(2, BigDecimal.ROUND_DOWN)
                                : goodsSpec.getShareAmount()))
                        .setInnerShareAmount(getInnerShareAmount(goodsSpec));//需最后设置
            }

            if (addGoodsSpecList.size() > 0) {
                goodsSpecService.saveOrUpdateBatch(addGoodsSpecList);
            }
        }
        //save tags
        this.saveGoodsTagRela(goodsBean.getTags(),goodsBean.getGoodsId(),1);
        this.saveGoodsTagRela(goodsBean.getTagsLabel(),goodsBean.getGoodsId(),2);

        //套购商品处理
        //this.saveGoodsPackage(goodsBean);
    }

    /**
     * 添加套购商品
     */
//    public void saveGoodsPackage(GoodsBean goodsBean){
//        if(!StringUtils.equals(goodsBean.getGoodsType(),GoodsTypeEnum.PACKAGE.toString())){
//            return;
//        }
//        if(StringUtils.isBlank(goodsBean.getPackagePop()) || goodsBean.getPackagePop().indexOf(":") == -1){
//            throw new RemoteServiceException("请填写正确的比例,例如 2:1");
//        }
//        List<GoodsPackagePop> goodsPackagePops = goodsBean.getGoodsPackagePops();
//        if(CollectionUtils.isEmpty(goodsPackagePops)){
//            throw new RemoteServiceException("请配置套购的比例商品");
//        }
//        List<GoodsPackagePop> distinctList = goodsPackagePops.stream().distinct().collect(Collectors.toList());
//        if(goodsPackagePops.size() != distinctList.size()){
//            throw new RemoteServiceException("禁止配置重复的机型");
//        }
//        //计算最低销售价格，最低分佣金额
//        BigDecimal totalMinPrice = BigDecimal.valueOf(0);
//        BigDecimal totalMinShareAmount = BigDecimal.valueOf(0);
//        //判断条件的比例和对应的机型是否合格
//        String[] split = goodsBean.getPackagePop().split(":");
//        for (int i = 1;i <= split.length; i++) {
//            int a = i;
//            long count = goodsPackagePops.stream().filter(v -> v.getType().intValue() == a).count();
//            if(count == 0){
//                throw new RemoteServiceException("条件比例与商品配置错误");
//            }
//            //判断比例格式是否正确
//            try {
//                int i1 = Integer.parseInt(split[i - 1]);
//            }catch(Exception e){
//                throw new RemoteServiceException("请填写正确的比例,例如  1:2");
//            }
//            BigDecimal minPrice = null;
//            BigDecimal minShareAmount = null;
//            for(GoodsPackagePop goodsPackagePop : goodsPackagePops) {
//                if(i != goodsPackagePop.getType()){
//                    continue;
//                }
//                //计算最低销售金额和分佣金额
//                BigDecimal minPrice2 = goodsPackagePop.getPrice().multiply(new BigDecimal(split[goodsPackagePop.getType() - 1])).setScale(2, BigDecimal.ROUND_HALF_UP);
//                if (minPrice == null || minPrice.doubleValue() > minPrice2.doubleValue()) {
//                    minPrice = minPrice2;
//                }
//                BigDecimal minShareAmount2 = minPrice2.multiply(goodsPackagePop.getShareRate()).setScale(2, BigDecimal.ROUND_HALF_UP);
//                if (minShareAmount == null || minShareAmount.doubleValue() > minShareAmount2.doubleValue()) {
//                    minShareAmount = minShareAmount2;
//                }
//            }
//            totalMinPrice = totalMinPrice.add(minPrice);
//            totalMinShareAmount = totalMinShareAmount.add(minShareAmount);
//        }
//
//        //添加配置机型
//        goodsPackagePopService.lambdaUpdate().eq(GoodsPackagePop::getGoodsPackageId,goodsBean.getGoodsId()).remove();
//        for(GoodsPackagePop goodsPackagePop : goodsPackagePops){
//            goodsPackagePop.setGoodsPackageId(goodsBean.getGoodsId());
//        }
//        goodsPackagePopService.saveBatch(goodsPackagePops);
//        //添加指定人员
//        if(goodsBean.getPackageUserType() == 0 && CollectionUtils.isEmpty(goodsBean.getGoodsPackageUserRelas())){
//            throw new RemoteServiceException("请选择指定用户");
//        }
//        for(GoodsPackageUserRela rela : goodsBean.getGoodsPackageUserRelas()){
//            rela.setGoodsId(goodsBean.getGoodsId());
//            rela.setCreateTime(new Date());
//        }
//        goodsBean.setPackageMinAmount(totalMinPrice);
//        goodsBean.setPackageMinShareAmount(totalMinShareAmount);
//        goodsBean.updateById();
//
//        goodsPackageUserRelaService.lambdaUpdate().eq(GoodsPackageUserRela::getGoodsId,goodsBean.getGoodsId()).remove();
//        goodsPackageUserRelaService.saveBatch(goodsBean.getGoodsPackageUserRelas());
//    }

    /**
     * 分类统计
     */
    public GoodsTypeCount countByType(HttpServletRequest request) {
        //获取当前登录微信企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        GoodsTypeCount goodsTypeCount = customGoodsMapper.countByType(companyWechatIds);
        //查询已售罄的商品数量
        goodsTypeCount.setYsq(customGoodsMapper.ysq(companyWechatIds));
        goodsTypeCount.setHdz(customGoodsMapper.countByFlag(companyWechatIds));
        return goodsTypeCount;
    }

    /**
     * 商品上下架
     * @param goodsIdList
     * @param action
     */
    public void goodsOnOff(List<String> goodsIdList, Boolean action) {
        goodsService.lambdaUpdate()
                .in(Goods::getGoodsId, goodsIdList)
                .set(Goods::getStatus, action)
                .update();
        if (!action) {
            carouselMapService.lambdaUpdate().in(CarouselMap::getGoodsId, goodsIdList).remove();
        }
    }

    /**
     * 商品模板
     * @param goodsTemplateBean
     * @param request
     */
    public void goodsTemplate(GoodsTemplateBean goodsTemplateBean, HttpServletRequest request) {

        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
            throw new RemoteServiceException("非租户账号不可操作当前信息");
        }

        if (goodsTemplateBean.getGoodsIdList() == null || goodsTemplateBean.getGoodsIdList().size() < 1) {
            return;
        }
        List<GoodsTemplate> goodsTemplateList = new ArrayList<>();
        for (String goodsId : goodsTemplateBean.getGoodsIdList()) {
            GoodsTemplate goodsTemplate = new GoodsTemplate();
            goodsTemplate.setGoodsId(goodsId);
            goodsTemplate.setTemplateId(goodsTemplateBean.getTemplateId());
            goodsTemplate.setCreateTime(new Date());
            goodsTemplate.setCompanyWechatId(adminUser.getCompanyWechatId());
            goodsTemplate.setCompanyName(adminUser.getCompanyName());
            goodsTemplateList.add(goodsTemplate);
        }
        goodsTemplateService.saveBatch(goodsTemplateList);
    }


    public Integer secCheck(String goodsId) {
        Integer count = goodsCheckMapper.checkGoodsSec(goodsId);
        return count;
    }

    public List<String> secCheckBatch(List<String> goodsIdList) {
        List<String> secGoodsIds = goodsCheckMapper.checkGoodsSecBatch(goodsIdList);
        return secGoodsIds;
    }

    @Transactional
    public Goods clone(String goodsId) {
        Goods goods = goodsService.getById(goodsId);
        if (goods != null) {
            goods.setGoodsId(null);
            goods.setCreateTime(new Date());
            goods.setPromotionGroup(false);
            goodsService.save(goods);
        }
        List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery()
                .eq(GoodsSpec::getGoodsId, goodsId)
                .list();
        if (goodsSpecs != null && goodsSpecs.size() > 0) {
            for (GoodsSpec goodsSpec : goodsSpecs) {
                goodsSpec.setGoodsId(goods.getGoodsId());
                goodsSpec.setGoodsSpecId(null);
                goodsSpec.setCreateTime(new Date());
                goodsSpecService.save(goodsSpec);
            }
        }
        List<CommonFile> commonFiles = commonFileService.lambdaQuery()
                .eq(CommonFile::getObjId, goodsId)
                .eq(CommonFile::getObjType, Constant.Img.GOODS_IMG)
                .list();

        if (commonFiles != null && commonFiles.size() > 0) {
            for (CommonFile commonFile : commonFiles) {
                commonFile.setObjId(goods.getGoodsId());
                commonFile.setId(null);
                commonFile.setCreateTime(new Date());
                commonFileService.save(commonFile);
            }
        }
        List<CarouselMap> carouselMaps = carouselMapService.lambdaQuery()
                .eq(CarouselMap::getGoodsId, goodsId)
                .list();
        if (carouselMaps != null && carouselMaps.size() > 0) {
            for (CarouselMap carouselMap : carouselMaps) {
                carouselMap.setGoodsId(goods.getGoodsId());
                carouselMap.setId(null);
                carouselMap.setCreateTime(new Date());
                carouselMapService.save(carouselMap);
            }
        }
        List<GoodsTemplate> goodsTemplateList = goodsTemplateService.lambdaQuery()
                .eq(GoodsTemplate::getGoodsId, goodsId)
                .list();
        if (goodsTemplateList != null && goodsTemplateList.size() > 0) {
            List<GoodsTemplate> saveGoodsTemplateList = new ArrayList<>();
            goodsTemplateList.forEach(o -> {
                o.setGoodsId(goods.getGoodsId()).setCreateTime(new Date()).setGoodsTemplateId(null);
                saveGoodsTemplateList.add(o);
            });
            goodsTemplateService.saveBatch(saveGoodsTemplateList);
        }
        return goods;
    }

    @Transactional
    public void goodsFreight(GoodsFreightBean goodsFreightBean) {
        goodsService.lambdaUpdate()
                .in(Goods::getGoodsId, goodsFreightBean.getGoodsIdList())
                .set(Goods::getFreightTemplateId, goodsFreightBean.getFreightTemplateId())
                .set(Goods::getFreightType, FreightTypeEnum.TEMPLATE.toString())
                .update();
    }

    /**
     * 用 商品规格的 分销金额 覆盖其 为null的 内部分销金额
     */
    public void syncGoodsSpecInnerShareMsg(HttpServletRequest request){
        String companyWechatId = commonLogic.getAdminUser(request).getCompanyWechatId();
        if(StringUtils.isBlank(companyWechatId)){
            throw new RemoteServiceException("运营账号暂无权限操作");
        }

        customGoodsMapper.syncGoodsSpecInnerShareMsg(companyWechatId);

    }


    /**
     * 修改商品水印和有效时间
     */
    public void updateGoodsLogo(List<String> goodsIds,String logo,String logoStartTime,String logoEndTime) throws ParseException {
        goodsService.lambdaUpdate()
                .set(Goods::getLogo,logo)
                .set(Goods::getLogoStartTime,DateUtils.parseDate(logoStartTime))
                .set(Goods::getLogoEndTime,DateUtils.parseDate(logoEndTime))
                .in(Goods::getGoodsId,goodsIds)
                .update();
    }

    /**
     *  套购商品指定人员列表
     */
    public List<User> getPackageUseUserList(String goodsId,String mobile){
        List<GoodsPackageUserRela> list = goodsPackageUserRelaService.lambdaQuery()
                .eq(GoodsPackageUserRela::getGoodsId, goodsId)
                .like(StringUtils.isNotBlank(mobile), GoodsPackageUserRela::getMobile, mobile).list();
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<String> userIds = list.stream().map(GoodsPackageUserRela::getUserId).collect(Collectors.toList());
        List<User> users = userLogic.getById(userIds);
        return users;
    }

    /**
     * 套购商品-导入指定人员
     */
    public List<User> importPackageUser(List<Object> list){
        if(CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        List<String> mobiles = new ArrayList<>();
        for(Object o : list){
            List<Object> row = (List<Object>) o;
            mobiles.add((String)row.get(1));
        }
        List<User> users = userLogic.getByMobile(mobiles);
        return users;
    }

    public List<Goods> getById(List<String> goodsIds){
        List<Goods> goodsList = goodsService.lambdaQuery().in(Goods::getGoodsId, goodsIds).list();
        return goodsList;
    }

    public List<GoodsSpec> getSpec(List<String> goodsIds){
        List<GoodsSpec> goodsSpecs = goodsSpecService.lambdaQuery().in(GoodsSpec::getGoodsId, goodsIds).list();
        return goodsSpecs;
    }

    public void batchUp(List<String> goodsIds, String isTrade) {
        goodsService.lambdaUpdate()
                .in(Goods::getGoodsId,goodsIds)
                .set(Goods::getIsTrade,isTrade).update();
    }
}
