package com.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platform.dao.*;
import com.platform.entity.*;
import com.platform.service.GoodsService;
import com.platform.service.GoodsSpecificationService;
import com.platform.utils.RRException;
import com.platform.utils.ShiroUtils;
import com.platform.vo.GoodsSpecificationValueVo;
import com.platform.vos.CurrentUserLoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Service实现类
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-21 21:19:49
 */
@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private GoodsCustomDao goodsCustomDao;

    @Autowired
    private GoodsAttributeDao goodsAttributeDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private GoodsGalleryDao goodsGalleryDao;

    @Autowired
    private BrandServiceImpl brandService;
    @Autowired
    private GoodsSpecificationService goodsSpecificationService;

    @Override
    public GoodsEntity queryObject(Integer id) {
        GoodsEntity goodsEntity = goodsDao.queryObject(id);
        Map map = new HashMap();
        if(goodsEntity == null){
            return null;
        }
        map.put("goodsId", goodsEntity.getId() + "");
        goodsEntity.setGoodsSpecificationList(goodsSpecificationService.queryList(map));
        goodsEntity.setProductList(productDao.queryList(map));
        BrandEntity brandEntity = brandService.queryObject(goodsEntity.getBrandId());
        if(null != brandEntity){
            goodsEntity.setBrandName(brandEntity.getName());
        }
        return goodsEntity;
    }

    @Override
//    @DataFilter(userAlias = "nideshop_goods.create_user_id", deptAlias = "nideshop_goods.create_user_dept_id")
    public List<GoodsEntity> queryList(Map<String, Object> map) {
        return goodsDao.queryList(map);
    }

    @Override
    public List<Map<String ,Object>> queryGoodsCategory(QueryWrapper<GoodsEntity> queryWrapper) {
        return  goodsCustomDao.getGoodsCategory(queryWrapper);
    }

    @Override
    public List<GoodsEntity> queryListWithoutFilter(Integer brandId , Integer isDelete,
                                                    String sidx , String order,
                                                    Integer offset, Integer limit) {
        return goodsDao.queryListCustom( brandId ,  isDelete , sidx ,  order, offset,  limit);
    }

    @Override
    public IPage<Map<String,Object>> queryListTwoWithoutFilter(IPage<Map<String,Object>> iPage, Integer brandId, Integer categoryId, String goodsName) {
        return goodsCustomDao.queryGoodsByBrandId(iPage ,brandId ,categoryId , goodsName);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return goodsDao.queryTotal(map);
    }

    @Override
    public Integer queryTotalWithoutFilter(Integer brandId , Integer isDelete ,
                                           String sidx , String order,
                                           Integer offset, Integer limit) {
        return goodsDao.queryTotalCustom(brandId, isDelete , sidx, order ,offset,limit);
    }

//    @Override
//    @Transactional
//    public int save(GoodsEntity goods) {
//        SysUserEntity user = ShiroUtils.getUserEntity();
//        Map<String, Object> map = new HashMap<>();
//        map.put("name", goods.getName());
//        List<GoodsEntity> list = queryList(map);
//        if (null != list && list.size() != 0) {
//            throw new RRException("商品名称已存在！");
//        }
//        Integer id = goodsDao.queryMaxId() + 1;
//        goods.setId(id);
//
//        //保存产品信息
//        ProductEntity productEntity = new ProductEntity();
//        productEntity.setGoodsId(id);
//        productEntity.setGoodsSn(goods.getGoodsSn());
//        productEntity.setGoodsNumber(goods.getGoodsNumber());
//        productEntity.setRetailPrice(goods.getRetailPrice());
//        productEntity.setMarketPrice(goods.getMarketPrice());
//        productEntity.setGoodsSpecificationIds("");
//        productDao.save(productEntity);
//
//        goods.setAddTime(new Date());
//        goods.setPrimaryProductId(productEntity.getId());
//
//        //保存商品详情页面显示的属性
//        List<GoodsAttributeEntity> attributeEntityList = goods.getAttributeEntityList();
//        if (null != attributeEntityList && attributeEntityList.size() > 0) {
//            for (GoodsAttributeEntity item : attributeEntityList) {
//                item.setGoodsId(id);
//                goodsAttributeDao.save(item);
//            }
//        }
//
//        //商品轮播图
//        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
//        if (null != galleryEntityList && galleryEntityList.size() > 0) {
//            for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
//                galleryEntity.setGoodsId(id);
//                goodsGalleryDao.save(galleryEntity);
//            }
//        }
//
//        goods.setIsDelete(0);
//        goods.setCreateUserDeptId(user.getDeptId());
//        goods.setCreateUserId(user.getUserId());
//        goods.setUpdateUserId(user.getUserId());
//        goods.setUpdateTime(new Date());
//        return goodsDao.save(goods);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(GoodsEntity goods) {
        CurrentUserLoginVo user = ShiroUtils.getUserEntity();
        Map<String, Object> map = new HashMap<>();
        map.put("name", goods.getName());
        List<GoodsEntity> list = queryList(map);
        if (null != list && list.size() != 0) {
            throw new RRException("商品名称已存在！");
        }
        //TODO:去掉，修改成自动生成ID的方式
        int last = null != goodsDao.queryMaxId() ? goodsDao.queryMaxId() : 0;
        Integer id = last  + 1;
        goods.setId(id);

        goods.setIsDelete(0);
        goods.setCreateUserDeptId(user.getCompanyId());
        goods.setUpdateUserId(user.getId());
        goods.setUpdateTime(new Date());
        goods.setAddTime(new Date());


        //保持产品贵和信息
        List<GoodsSpecificationEntity> goodsSpecificationList = goods.getGoodsSpecificationList();
        List<GoodsSpecificationEntity> latestGoodsSpecificationList = new ArrayList<>();
        for(GoodsSpecificationEntity goodsSpecificationEntity : goodsSpecificationList){
            goodsSpecificationEntity.setGoodsId(goods.getId());
            List<GoodsSpecificationValueVo> valueVoList = goodsSpecificationEntity.getVal();
            if(!CollectionUtils.isEmpty(valueVoList)){
                for (GoodsSpecificationValueVo valueVo : valueVoList){
                    GoodsSpecificationEntity newEntity = new GoodsSpecificationEntity();
                    BeanUtils.copyProperties(goodsSpecificationEntity , newEntity);
                    newEntity.setPicUrl(valueVo.getPicUrl());
                    newEntity.setValue(valueVo.getName());
                    newEntity.setUuid(valueVo.getUuid());
                    goodsSpecificationService.save(newEntity);
                    latestGoodsSpecificationList.add(newEntity);
                }
            }else{
                goodsSpecificationService.save(goodsSpecificationEntity);
                latestGoodsSpecificationList.add(goodsSpecificationEntity);
            }

        }

        //保存产品设置信息
        int goodsNum = 0;
        List<ProductEntity> productList = goods.getProductList();
        String goodsSpecificationIds = "";
        String uuidLink = "";
        String[] uuids = null;
        Map<String, Object> param = null;
        GoodsSpecificationEntity goodsSpecificationEntity = null;
        if(productList != null || productList.size() > 0){
            for(ProductEntity productEntity : productList){
                if(productEntity.getUuidLink() == null){
                    throw new RRException("参数uuiLink为空");
                }
                goodsSpecificationIds = "";
                uuidLink = productEntity.getUuidLink();
                uuids = uuidLink.split("_");
                for(String uuid : uuids){
                    goodsSpecificationEntity = findEntityByUuidAndGoodsId(uuid , goods.getId() , latestGoodsSpecificationList);
                    if(goodsSpecificationEntity != null){
                        goodsSpecificationIds = goodsSpecificationIds + "_" + goodsSpecificationEntity.getId();
                    }
                }
                productEntity.setGoodsSpecificationIds(goodsSpecificationIds);
                productEntity.setGoodsId(id);
                productEntity.setUuidLink(uuidLink);
                productDao.save(productEntity);

                if(productEntity.getGoodsNumber() != null){
                    goodsNum += productEntity.getGoodsNumber();
                }
            }
        }
        goods.setGoodsNumber(goodsNum);
        goodsDao.save(goods);

        //商品轮播图
        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
        if (null != galleryEntityList && galleryEntityList.size() > 0) {
            for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
                galleryEntity.setGoodsId(id);
                goodsGalleryDao.save(galleryEntity);
            }
        }

        //保存商品详情页面显示的属性
        List<GoodsAttributeEntity> attributeEntityList = goods.getAttributeEntityList();
        if (null != attributeEntityList && attributeEntityList.size() > 0) {
            for (GoodsAttributeEntity item : attributeEntityList) {
                item.setGoodsId(id);
                goodsAttributeDao.save(item);
            }
        }

        return id;
    }

    private GoodsSpecificationEntity findEntityByUuidAndGoodsId(String uuid , int goodsId , List<GoodsSpecificationEntity> specificationEntityList){
        if(!CollectionUtils.isEmpty(specificationEntityList)){
            for(GoodsSpecificationEntity entity : specificationEntityList){
                if(entity.getGoodsId() == goodsId && StringUtils.equals(uuid , entity.getUuid())){
                    return entity;
                }
            }
        }
        return null;
    }

    @Override
    @Transactional
    public int update(GoodsEntity goods) {
        CurrentUserLoginVo user = ShiroUtils.getUserEntity();
        goods.setUpdateUserId(user.getId());
        goods.setUpdateTime(new Date());
        goodsDao.update(goods);

        //先全部删除规格信息和设置信息
        goodsSpecificationService.deleteByGoodsId(goods.getId());
        productDao.deleteByGoodsId(goods.getId());

        //保持产品规格信息
        List<GoodsSpecificationEntity> goodsSpecificationList = goods.getGoodsSpecificationList();
        for(GoodsSpecificationEntity goodsSpecificationEntity : goodsSpecificationList){
            goodsSpecificationEntity.setGoodsId(goods.getId());
            goodsSpecificationService.save(goodsSpecificationEntity);
        }

        //保存产品设置信息
        List<ProductEntity> productList = goods.getProductList();
        String goodsSpecificationIds = "";
        String uuidLink = "";
        String[] uuids = null;
        Map<String, Object> param = null;
        GoodsSpecificationEntity goodsSpecificationEntity = null;
        if(productList != null || productList.size() > 0){
            for(ProductEntity productEntity : productList){
                goodsSpecificationIds = "";
                uuidLink = productEntity.getUuidLink();
                if(StringUtils.isNotBlank(uuidLink)){
                    uuids = uuidLink.split("_");
                    if(null != uuids){
                        for(String uuid : uuids){
                            param = new HashMap<>();
                            param.put("uuid", uuid);
                            param.put("goodsId", goods.getId());
                            goodsSpecificationEntity = goodsSpecificationService.queryObjectBykeyAndGoodsId(param);
                            if(goodsSpecificationEntity != null){
                                goodsSpecificationIds = goodsSpecificationIds + "_" + goodsSpecificationEntity.getId();
                            }
                        }
                    }

                }
                productEntity.setGoodsSpecificationIds(goodsSpecificationIds);
                productEntity.setGoodsId(goods.getId());
                productEntity.setUuidLink(uuidLink);
                productDao.save(productEntity);
            }
        }

        List<GoodsAttributeEntity> attributeEntityList = goods.getAttributeEntityList();
        if (null != attributeEntityList && attributeEntityList.size() > 0) {
            for (GoodsAttributeEntity goodsAttributeEntity : attributeEntityList) {
                int result = goodsAttributeDao.updateByGoodsIdAttributeId(goodsAttributeEntity);
                if (result == 0) {
                    goodsAttributeDao.save(goodsAttributeEntity);
                }
            }
        }

        //修改时全删全插
        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("goodsId", goods.getId());
        goodsGalleryDao.deleteByGoodsId(map);

        if (null != galleryEntityList && galleryEntityList.size() > 0) {
            for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
                galleryEntity.setGoodsId(goods.getId());
                goodsGalleryDao.save(galleryEntity);
            }
        }
        return goods.getId();
    }

//    @Override
//    @Transactional
//    public int update(GoodsEntity goods) {
//        SysUserEntity user = ShiroUtils.getUserEntity();
//        List<GoodsAttributeEntity> attributeEntityList = goods.getAttributeEntityList();
//        if (null != attributeEntityList && attributeEntityList.size() > 0) {
//            for (GoodsAttributeEntity goodsAttributeEntity : attributeEntityList) {
//                int result = goodsAttributeDao.updateByGoodsIdAttributeId(goodsAttributeEntity);
//                if (result == 0) {
//                    goodsAttributeDao.save(goodsAttributeEntity);
//                }
//            }
//        }
//        goods.setUpdateUserId(user.getUserId());
//        goods.setUpdateTime(new Date());
//        //商品轮播图
//        //修改时全删全插
//        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
//        Map<String, Integer> map = new HashMap<String, Integer>();
//        map.put("goodsId", goods.getId());
//        goodsGalleryDao.deleteByGoodsId(map);
//
//        if (null != galleryEntityList && galleryEntityList.size() > 0) {
//            for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
//                galleryEntity.setGoodsId(goods.getId());
//                goodsGalleryDao.save(galleryEntity);
//            }
//        }
//        return goodsDao.update(goods);
//    }

    @Override
    public int delete(Integer id) {
        CurrentUserLoginVo user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        goodsEntity.setIsDelete(1);
        goodsEntity.setIsOnSale(0);
        goodsEntity.setUpdateUserId(user.getId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }

    @Override
    @Transactional
    public int deleteBatch(Integer[] ids) {
        int result = 0;
        for (Integer id : ids) {
            result += delete(id);
        }
        return result;
    }

    @Override
    @Transactional
    public int back(Integer[] ids) {
        CurrentUserLoginVo user = ShiroUtils.getUserEntity();
        int result = 0;
        for (Integer id : ids) {
            GoodsEntity goodsEntity = queryObject(id);
            goodsEntity.setIsDelete(0);
            goodsEntity.setIsOnSale(1);
            goodsEntity.setUpdateUserId(user.getId());
            goodsEntity.setUpdateTime(new Date());
            result += goodsDao.update(goodsEntity);
        }
        return result;
    }

    @Override
    public int enSale(Integer id) {
        CurrentUserLoginVo user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        if(goodsEntity == null){
            throw new RRException("上架商品失败！");
        }
        if (goodsEntity.getIsOnSale()!=null && 1 == goodsEntity.getIsOnSale()) {
            throw new RRException("上架商品失败！");
        }
        goodsEntity.setIsOnSale(1);
        goodsEntity.setUpdateUserId(user.getId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }

    @Override
    public int unSale(Integer id) {
        CurrentUserLoginVo user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        if(goodsEntity == null){
            throw new RRException("下架商品失败！");
        }
        if (goodsEntity.getIsOnSale()!=null && 0 == goodsEntity.getIsOnSale()) {
            throw new RRException("下架商品失败！");
        }
        goodsEntity.setIsOnSale(0);
        goodsEntity.setUpdateUserId(user.getId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }

    @Override
    public int deleteByBrandId(Long brandId) {
        return goodsDao.deleteByBrandId(brandId);
    }
}
