package com.sqx.modules.shopping.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.shopping.controller.SkuUtil;
import com.sqx.modules.shopping.dao.*;
import com.sqx.modules.shopping.entity.*;
import com.sqx.modules.shopping.service.GoodsService;
import com.sqx.modules.shopping.service.GoodsTypeService;
import com.sqx.modules.shopping.service.SelfGoodsAttrService;
import com.sqx.modules.shopping.utils.DateUtil;
import com.sqx.modules.shopping.utils.Result;
import com.sqx.modules.shopping.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SelfGoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsJpaRepository jpaRepository;
    @Autowired
    private GoodsTypeJpaRepository goodsJpaTypeRepository;
    @Autowired
    private SelfGoodsAttrValueJpaRepository attrValueJpaRepository;
    @Autowired
    private SelfGoodsAttrValueRepository selfGoodsAttrValueRepository;
    @Autowired
    private SelfGoodsAttrJpaRepository attrJpaRepository;
    @Autowired
    private SelfGoodsAttrRepository selfGoodsAttrRepository;
    @Autowired
    private SelfGoodsAttrService goodsAttrService;
    @Autowired
    private SelfGoodsSkuJpaRepository skuJpaRepository;
    @Autowired
    private SelfGoodsVirtualJpaRepository goodsVirtualJpaRepository;
    @Autowired
    private SelfGoodsBrandJpaRepository selfGoodsBrandJpaRepository;

    @Autowired
    private GoodsTypeService goodsTypeService;

    @Autowired
    private CommonInfoService commonRepository;

    /**
     * 后台管理商品列表、创建时间排序
     * @param page 页数
     * @param size 条数
     * @param title 标题：模糊查询
     * @param type 类型
     * @param status 状态
     * @return
     */
    public Result findAll(Integer page, Integer size, String title, String type, Integer status, Integer isJiFenGoods) {
        return findAll(page, size, title, type, null, status, isJiFenGoods);
    }

    /**
     * 后台管理商品列表、创建时间排序
     * @param page 页数
     * @param size 条数
     * @param title 标题：模糊查询
     * @param type 类型
     * @param pTypeId 一级类型
     * @param status 状态
     * @return
     */
    @Override
    public Result findAll(Integer page, Integer size, String title, String type, String pTypeId, Integer status, Integer isJiFenGoods) {
        //先查询类型
        List<GoodsType> goodsTypeList;
        if(StringUtils.isNotBlank(pTypeId)){
            Specification<GoodsType> goodsTypeQc = (root, criteriaQuery, criteriaBuilder) -> {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("parentId"), pTypeId),criteriaBuilder.equal(root.get("id"), pTypeId)));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
            };
            goodsTypeList = goodsJpaTypeRepository.findAll(goodsTypeQc);
        } else {
			goodsTypeList = null;
		}
		//按照时间排序
        Pageable pageable;
        if(size == -1){
            pageable = PageRequest.of(page, Integer.MAX_VALUE, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        } else {
            pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        }
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = (root, criteriaQuery, criteriaBuilder) -> {
			List<Predicate> predicateList = new ArrayList<>();
			if (StringUtils.isNotEmpty(title)) {
				predicateList.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
			}
			if (StringUtils.isNotEmpty(type)) {
				predicateList.add(criteriaBuilder.equal(root.get("typeId"), type));
			}
            if(StringUtils.isNotBlank(pTypeId)) {
                //goodsTypeList
                CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("typeId"));
                if(goodsTypeList != null && !goodsTypeList.isEmpty()) {
                    goodsTypeList.forEach(x -> in.value(x.getId()));
                }
                predicateList.add(in);
            }
			if (status != 0) {
				predicateList.add(criteriaBuilder.equal(root.get("status"), status));
			}
			if (isJiFenGoods != null) {
				predicateList.add(criteriaBuilder.equal(root.get("isJiFenGoods"), isJiFenGoods));
			}else {
				predicateList.add(criteriaBuilder.isNull(root.get("isJiFenGoods")));
			}
			return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
		};
        //处理数据：商品分类
        Page<SelfGoods> all = jpaRepository.findAll(queryCondition, pageable);
        List<SelfGoods> list = all.getContent();
        List<GoodsType> allType = goodsJpaTypeRepository.findAll();
        for (SelfGoods g : list) {
            for (GoodsType goodsType : allType) {
                String typeId = g.getTypeId();
                if (StringUtils.isNotEmpty(typeId) && typeId.equals(goodsType.getId().toString())){
                    g.setType(goodsType);
                    break;
                }
            }
        }
        return ResultUtil.success(all);
    }
    @Override
    public Result selectListByType(String title, String type, Integer status, Integer isJiFenGoods) {
        //构造自定义查询条件
        Specification<GoodsType> queryCondition1 = (root, criteriaQuery, criteriaBuilder) -> {
			List<Predicate> predicateList = new ArrayList<>();
			predicateList.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("parentId"), "56"),criteriaBuilder.equal(root.get("id"), "56")));
			return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
		};
        List<GoodsType> materialTypes = goodsJpaTypeRepository.findAll(queryCondition1);
        Specification<SelfGoods> queryCondition = (root, criteriaQuery, criteriaBuilder) -> {
			List<Predicate> predicateList = new ArrayList<>();
			if (StringUtils.isNotEmpty(title)) {
				predicateList.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
			}
			CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("typeId"));
			for(GoodsType goodsType:materialTypes) {
				in.value(goodsType.getId());
			}
			predicateList.add(in);
			if (ObjectUtil.isNotEmpty(status)) {
				predicateList.add(criteriaBuilder.equal(root.get("status"), status));
			}
			if (ObjectUtil.isNotEmpty(isJiFenGoods)) {
				predicateList.add(criteriaBuilder.equal(root.get("isJiFenGoods"), isJiFenGoods));
			}else {
				predicateList.add(criteriaBuilder.isNull(root.get("isJiFenGoods")));
			}
			return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
		};
        //处理数据：商品分类
        List<SelfGoods> all = jpaRepository.findAll(queryCondition);
        for (SelfGoods g : all) {
            for (GoodsType goodsType : materialTypes) {
                String typeId = g.getTypeId();
                if (StringUtils.isNotEmpty(typeId) && typeId.equals(goodsType.getId().toString())){
                    g.setType(goodsType);
                    break;
                }
            }
        }
        return ResultUtil.success(all);
    }

    @Override
    public Result wlcglist(Integer page, Integer size, String sort) {
        //只查询类型是物料包的商品
        String pTypeId = "56";
        List<GoodsType> goodsTypeList;
        if(StringUtils.isNotBlank(pTypeId)){
            Specification<GoodsType> goodsTypeQc = (root, criteriaQuery, criteriaBuilder) -> {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.or(criteriaBuilder.equal(root.get("parentId"), pTypeId),criteriaBuilder.equal(root.get("id"), pTypeId)));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
            };
            goodsTypeList = goodsJpaTypeRepository.findAll(goodsTypeQc);
        } else {
            goodsTypeList = null;
        }
        //按照时间排序
        Pageable pageable;
        if(size == -1){
            pageable = PageRequest.of(page, Integer.MAX_VALUE, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        } else {
            pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        }
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicateList = new ArrayList<>();
            if(StringUtils.isNotBlank(pTypeId)) {
                //goodsTypeList
                CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("typeId"));
                if(goodsTypeList != null && !goodsTypeList.isEmpty()) {
                    goodsTypeList.forEach(x -> in.value(x.getId()));
                }
                predicateList.add(in);
            }
            return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
        };
        //处理数据：商品分类
        Page<SelfGoods> all = jpaRepository.findAll(queryCondition, pageable);
        return ResultUtil.success(all);
    }

    //虚拟商品列表
    @Override
    public Result goodsVirtualList(Integer page, Integer size, String title, String type, Integer status, Integer isExpress, Integer isJiFenGoods) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "createAt")));
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(title)) {
                    predicateList.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
                }
                if (StringUtils.isNotEmpty(type)) {
                    predicateList.add(criteriaBuilder.equal(root.get("typeId"), type));
                }
                if (status != 0) {
                    predicateList.add(criteriaBuilder.equal(root.get("status"), status));
                }
                if (isExpress != 0) {
                    predicateList.add(criteriaBuilder.equal(root.get("isExpress"), isExpress));
                }
                if (isJiFenGoods != null) {
                    if (isJiFenGoods != 0){ //虚拟商品列表包含积分虚拟商品
                        predicateList.add(criteriaBuilder.equal(root.get("isJiFenGoods"), isJiFenGoods));
                    }
                }else {
                    predicateList.add(criteriaBuilder.isNull(root.get("isJiFenGoods")));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        //处理数据：商品分类
        Page<SelfGoods> all = jpaRepository.findAll(queryCondition, pageable);
        List<SelfGoodsVirtual> virtualList = goodsVirtualJpaRepository.findAll();
        List<SelfGoods> list = all.getContent();
        for (SelfGoods g : list) {
            int sum = 0;
            int count = 0;
            for (SelfGoodsVirtual v : virtualList) {
                if (g.getId().equals(v.getGoodsId())){ //虚拟商品总数库存
                    sum++;
                    if (v.getStatus() == 1){ //未使用的库存
                        count++;
                    }
                }
            }
            g.setVirtualSum(sum);
            g.setVirtualCount(count);
        }
        return ResultUtil.success(all);
    }

    /**
     * 用户端商品列表、销量排序
     * @param page 页数
     * @param size 条数
     * @param title 标题：模糊查询
     * @return
     */
    @Override
    public Result findAllByUser(Integer page, Integer size, String type, String brandId, String title, String sort, Integer isJiFenGoods) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, sort);
        if (sort.equals("price")){
            order = new Sort.Order(Sort.Direction.ASC, sort);
        }
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(type)) {
                    predicateList.add(criteriaBuilder.equal(root.get("typeId"), type));
                }
                if (StringUtils.isNotEmpty(brandId)) {
                    predicateList.add(criteriaBuilder.equal(root.get("brandId"), brandId));
                }
                if (StringUtils.isNotEmpty(title)) {
                    predicateList.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
                }
                if (isJiFenGoods != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("isJiFenGoods"), isJiFenGoods));
                }else {
                    predicateList.add(criteriaBuilder.isNull(root.get("isJiFenGoods")));
                }
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        //处理数据：商品分类
        Page<SelfGoods> all = jpaRepository.findAll(queryCondition, pageable);
        List<SelfGoods> list = all.getContent();
        for (SelfGoods g : list) {
            Long id=g.getId();
            /*if (g.getTypeId() != null){
                g.setType(goodsJpaTypeRepository.findById(Long.valueOf(g.getTypeId())).orElse(null));
            }*/
            g.setAttr(goodsAttrService.findByGoodsId(id));
            g.setSku(skuJpaRepository.findAllByGoodsId(id));
            /*if (g.getBrandId() != null){
                g.setBrand(brandJpaRepository.findById(g.getBrandId()).orElse(null));
            }*/
            if (g.getIsExpress() == 2){ //虚拟商品库存
                g.setVirtualCount(goodsVirtualJpaRepository.findByGoodsId(g.getId()).size());
            }
        }
        return ResultUtil.success(all);
    }


    @Override
    public Result saveBody(SelfGoods entity) {
        entity.setCreateAt(DateUtil.createTime()); //创建时间
        entity.setStatus(1); //状态为默认1上架
        SelfGoods g = jpaRepository.save(entity);
        //处理规格
        List<SelfGoodsAttr> attr = entity.getAttr();
        for (SelfGoodsAttr a : attr) {
            a.setGoodsId(g.getId());
            goodsAttrService.saveBody(a);
        }
        List<SelfGoodsSku> sku = entity.getSku();
        for (SelfGoodsSku v : sku) {
            v.setGoodsId(g.getId());
            skuJpaRepository.save(v);
        }
        return ResultUtil.success(g);
    }

    @Override
    public Result updateBody(SelfGoods entity) {
        //1.修改attr
        if (entity.getAttr() != null && entity.getAttr().size()>0){
            SelfGoodsAttr selfGoodsAttr = entity.getAttr().get(0);
            if(selfGoodsAttr.getId()==null){
                goodsAttrService.deleteAttrAndValue(entity.getId());
                for(SelfGoodsAttr attr:entity.getAttr()){
                    attr.setGoodsId(entity.getId());
                    goodsAttrService.saveBody(attr);
                }
            }else{
                for(SelfGoodsAttr attr:entity.getAttr()){
                    attr.setGoodsId(entity.getId());
                    goodsAttrService.updateBody(attr);
                }
            }
        }else { //修改为单规格，删除所有attr
            goodsAttrService.deleteAttrAndValue(entity.getId());
        }
        //2.修改所有sku
        List<SelfGoodsSku> allSku = skuJpaRepository.findAllByGoodsId(entity.getId());
        skuJpaRepository.deleteAll(allSku);
        List<SelfGoodsSku> sku = entity.getSku();
        for (SelfGoodsSku v : sku) {
            v.setGoodsId(entity.getId());
            skuJpaRepository.save(v);
        }
        //3.修改商品信息
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result findOne(Long id) {
        SelfGoods g = jpaRepository.findById(id).orElse(null);
        if (g.getTypeId() != null){
            g.setType(goodsJpaTypeRepository.findById(Long.valueOf(g.getTypeId())).orElse(null));
        }
        g.setAttr(goodsAttrService.findByGoodsId(id));
        g.setSku(skuJpaRepository.findAllByGoodsId(id));
        if (g.getIsExpress() == 2){ //虚拟商品库存
            g.setVirtualCount(goodsVirtualJpaRepository.findByGoodsId(g.getId()).size());
        }
        if (g.getBrandId() != null){
            g.setBrand(selfGoodsBrandJpaRepository.findById(g.getBrandId()).orElse(null));
        }

        return ResultUtil.success(g);
    }


    @Override
    public SelfGoods findById(Long goodsId){
        return jpaRepository.findById(goodsId).orElse(null);
    }


    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }


    @Override
    public Result searchBrandList(String title) {
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (StringUtils.isNotEmpty(title)) {
                    predicateList.add(criteriaBuilder.like(root.get("title"), "%"+title+"%"));
                }
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1));
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        List<SelfGoods> goodsList = jpaRepository.findAll(queryCondition);
        List<SelfGoodsBrand> brandList = selfGoodsBrandJpaRepository.findAll();
        List<SelfGoodsBrand> result = new ArrayList<>();
        for (SelfGoods g : goodsList) {
            if (g.getBrandId() != null){
                Long brandId = g.getBrandId();
                for (SelfGoodsBrand b : brandList) {
                    if (brandId.equals(b.getBrandId())){
                        result.add(b);
                        break;
                    }
                }
            }
        }
        //利用list中的元素创建HashSet集合，此时set中进行了去重操作
        HashSet set = new HashSet(result);
        result.clear();
        result.addAll(set);
        return ResultUtil.success(result);
    }



    @Override
    public Result selectGoods(Integer page, Integer size, String sort) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, sort);
        if (sort.equals("price")){
            order = new Sort.Order(Sort.Direction.ASC, sort);
        }
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("isSelect"), 1));
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1)); //上架
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result selling(Integer page, Integer size, String sort) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, sort);
        if (sort.equals("price")){
            order = new Sort.Order(Sort.Direction.ASC, sort);
        }
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.isNull(root.get("isJiFenGoods")));
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1)); //上架
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result news(Integer page, Integer size, String sort) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, sort);
        if (sort.equals("price")){
            order = new Sort.Order(Sort.Direction.ASC, sort);
        }
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1)); //上架
                predicateList.add(criteriaBuilder.isNull(root.get("isJiFenGoods"))); //非积分商品
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result recommend(Integer page, Integer size, String sort) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, sort);
        if (sort.equals("price")){
            order = new Sort.Order(Sort.Direction.ASC, sort);
        }
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("isRecommend"), 1)); //每日推荐
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1)); //上架
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result homeGoods(Integer page, Integer size) {
        //按照时间排序
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "sales")));
        //构造自定义查询条件
        Specification<SelfGoods> queryCondition = new Specification<SelfGoods>() {
            @Override
            public Predicate toPredicate(Root<SelfGoods> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                predicateList.add(criteriaBuilder.equal(root.get("homeGoods"), 1));
                predicateList.add(criteriaBuilder.equal(root.get("status"), 1)); //上架
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }

    @Override
    public Result addSelectGoods(Long id) {
        SelfGoods one = jpaRepository.getOne(id);
        one.setIsSelect(1); //设置为精选好物
        return ResultUtil.success(this.updateBody(one));
    }

    @Override
    public Result deleteSelectGoods(String ids) {
        String[] split = ids.split(",");
        for (String id : split) {
            SelfGoods one = jpaRepository.getOne(Long.valueOf(id));
            one.setIsSelect(0); //设置为否
            this.updateBody(one);
        }
        return ResultUtil.success();
    }

    @Override
    public Result addRecommend(Long id) {
        SelfGoods one = jpaRepository.getOne(id);
        one.setIsRecommend(1); //设置为每日推荐
        return ResultUtil.success(this.updateBody(one));
    }

    @Override
    public Result deleteRecommend(String ids) {
        String[] split = ids.split(",");
        for (String id : split) {
            SelfGoods one = jpaRepository.getOne(Long.valueOf(id));
            one.setIsRecommend(0); //设置为否
            this.updateBody(one);
        }
        return ResultUtil.success();
    }

    @Override
    public void salesAddOne(Long id) {
        SelfGoods one = jpaRepository.getOne(id);
        one.setSales(one.getSales()+1);
        jpaRepository.save(one);
    }

    @Override
    public Result isFormatAttr(SelfGoodsAttr goodsAttr, String coverImg, String originalPrice, String price, String memberPrice) {
        //1.获取商品规格值
        List<SelfGoodsAttrValue> attr = goodsAttr.getAttrValue();
        int attrSize = attr.size();
        //2.准备返回值
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        //3.sku规格处理集合
        List<List<String>> skuInputList = new ArrayList<>();
        //4.循环规格值
        for (int i = 0; i < attrSize; i++) {
            //5.放入表头数据
            header.add(attr.get(i).getValue());
            //6.sku规格计算
            String detail = attr.get(i).getDetail();
            String[] split = detail.split(",");
            List<String> skuList = new ArrayList<>();
            for (int j = 0; j < split.length; j++) {
                skuList.add(split[j]);
            }
            skuInputList.add(skuList);
        }
        //8.sku规格种类
        List<List<String>> skuList = SkuUtil.skuSort(skuInputList); //计算规格种类
        for (int i = 0; i < skuList.size(); i++) {
            Map<String, Object> sku = new HashMap<>();
            List<String> strings = skuList.get(i);
            String[] arr = strings.toArray(new String[strings.size()]);
            String json = "";
            for (int j = 0; j < attrSize; j++) {
                String arrString = arr[j];
                sku.put("value"+j, arrString);
                json += arrString+",";
            }
            json = json.substring(0, json.length()-1);
            sku.put("json", json);
            sku.put("detailJson", json);
            sku.put("skuImg", coverImg);
            sku.put("skuOriginalPrice", originalPrice);
            sku.put("skuPrice", price);
            sku.put("stock", 999);
            sku.put("sales", 0);
            value.add(sku);
        }
        //表头
        header.add("图片");
        if (StringUtils.isNotEmpty(originalPrice)){
            header.add("原价");
        }
        header.add("售价");
        header.add("库存");
        header.add("销量");
        header.add("操作");
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return ResultUtil.success(map);
    }

    @Override
    public Result onlyFormatAttr(String coverImg, String originalPrice, String price, String memberPrice) {
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        //表头
        header.add("图片");
        if (StringUtils.isNotEmpty(originalPrice)){
            header.add("原价");
        }
        header.add("售价");
        header.add("库存");
        header.add("销量");
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        Map<String, Object> sku = new HashMap<>();
        sku.put("json", null);
        sku.put("detailJson", null);
        sku.put("skuImg", coverImg);
        sku.put("skuOriginalPrice", originalPrice);
        sku.put("skuPrice", price);
        sku.put("stock", 999);
        sku.put("sales", 0);
        value.add(sku);
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return ResultUtil.success(map);
    }

    /**
     * 回显sku
     * @param goodsId
     * @return
     */
    @Override
    public Result formatAttr(Long goodsId) {
        //1.获取商品规格值
        List<SelfGoodsAttrValue> attr = attrValueJpaRepository.findAllByGoodsId(goodsId);
        //sku集合
        List<SelfGoodsSku> goodsSkuList = skuJpaRepository.findAllByGoodsId(goodsId);
        int attrSize = attr.size();
        //2.准备返回值
        Map<String, Object> map = new HashMap<>();
        List<String> header = new ArrayList<>(); //表头
        List<Map<String, Object>> value = new ArrayList<>(); //规格排列组合
        if (attrSize > 0){
            //4.循环规格值
            for (int i = 0; i < attrSize; i++) {
                //5.放入表头数据
                header.add(attr.get(i).getValue());
            }
        }
        SelfGoods goods = jpaRepository.findById(goodsId).orElse(null);
        if (goods.getIsJiFenGoods() == null){ //普通商品回显表头
            //表头
            header.add("图片");
            header.add("原价");
            header.add("售价");
            header.add("库存");
            header.add("销量");
            header.add("操作");
        }else { //积分商品回显表头
            //表头
            header.add("图片");
            header.add("售价");
            header.add("库存");
            header.add("销量");
            header.add("操作");
        }
        //5.sku数据放入
        for (SelfGoodsSku s : goodsSkuList) {
            Map<String, Object> sku = new HashMap<>();
            String detailJson = s.getDetailJson();
            if (detailJson != null){
                String[] split = detailJson.split(",");
                for (int i = 0; i < split.length; i++) {
                    sku.put("value"+i, split[i]);
                }
            }
            if (goods.getIsJiFenGoods() == null){
                sku.put("detailJson", detailJson);
                sku.put("skuOriginalPrice", s.getSkuOriginalPrice());
                sku.put("skuPrice", s.getSkuPrice());
                sku.put("stock", s.getStock());
                sku.put("sales", s.getSales());
                sku.put("skuImg", s.getSkuImg());
            }else {
                sku.put("detailJson", detailJson);
                sku.put("skuPrice", s.getSkuPrice());
                sku.put("stock", s.getStock());
                sku.put("sales", s.getSales());
                sku.put("skuImg", s.getSkuImg());
            }
            value.add(sku);
        }
        //数据放入返回map
        map.put("header", header);
        map.put("value", value);
        return ResultUtil.success(map);
    }

    @Override
    public Result findAttrValue(Long goodsId) {
        List<SelfGoodsAttr> attrList = attrJpaRepository.findAllByGoodsId(goodsId);
        SelfGoodsAttr s = new SelfGoodsAttr();
        if (attrList.size() > 0 && attrList != null){
            s = attrList.get(0);
            s.setAttrValue(attrValueJpaRepository.findAllByGoodsId(goodsId));
        }
        return ResultUtil.success(s);
    }

    @Override
    public Result updateStatus(Long goodsId) {
        SelfGoods g = jpaRepository.findById(goodsId).orElse(null);
        if (g.getStatus() == 1){
            g.setStatus(2);
        }else {
            g.setStatus(1);
        }
        return ResultUtil.success(jpaRepository.save(g));
    }



}