package com.kmall.admin.service.impl;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.dao.*;
import com.kmall.admin.entity.*;
import com.kmall.admin.service.GoodsService;
import com.kmall.api.contants.Dict;
import com.kmall.common.entity.SysUserEntity;
import com.kmall.common.utils.*;
import com.kmall.common.utils.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service实现类
 *
 * @author Scott
 * @email
 * @date 2017-08-21 21:19:49
 */
@Service("goodsService")
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private GoodsAttributeDao goodsAttributeDao;
    @Autowired
    private AttributeCategoryDao attributeCategoryDao;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private GoodsGalleryDao goodsGalleryDao;
    @Autowired
    private GoodsSpecificationDao goodsSpecificationDao;
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private GoodsGroupDao goodsGroupDao;
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public GoodsEntity queryObject(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("goodsId", id);
        List<GoodsAttributeEntity> attributeEntities = goodsAttributeDao.queryList(map);
        List<ProductEntity> productEntityList = productDao.queryList(map);
        GoodsEntity entity = goodsDao.queryObject(id);
        entity.setAttributeEntityList(attributeEntities);
        entity.setProductEntityList(productEntityList);
        return entity;
    }

    @Override
    public List<GoodsEntity> queryList(Map<String, Object> map) {
        return goodsDao.queryList(map);
    }

    @Override
    public List<GoodsEntity> querySame(Map<String, Object> map) {
        return goodsDao.querySame(map);
    }

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

    @Override
    @Transactional
    public int save(GoodsEntity goods) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(goods);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("attributeCategory", "商品分类");
        builder.put("categoryId", "商品二级分类");
        builder.put("goodsSn", "商品编码");
        builder.put("goodsBizType", "货品业务类型");
        builder.put("name", "商品名称");
        builder.put("brandId", "品牌");
        builder.put("freightId", "运费模版");
        builder.put("goodsDesc", "商品描述");
        builder.put("isOnSale", "上架");
        builder.put("goodsUnit", "商品单位");
        builder.put("primaryPicUrl", "商品主图");
        builder.put("listPicUrl", "商品列表图");
        builder.put("goodsRate", "商品税率");
        builder.put("retailPrice", "零售价格");
        builder.put("isHot", "热销");

        if (!Dict.orderBizType.item_11.getItem().equals(goods.getGoodsBizType())) {
            // 海关信息，普通货物可不添加
            builder.put("sku", "SKU");
            builder.put("prodBarcode", "产品编码");
            builder.put("brand", "产品品牌");
            builder.put("unitCode", "计量单位代码");
            builder.put("cusGoodsCode", "海关商品编码");
            builder.put("ciqProdModel", "国检规格型号");
            builder.put("oriCntCode", "原产国代码");
            builder.put("cusDeclEle", "海关申报要素");
            builder.put("cusRecCode", "海关备案编号");
        }
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }

        // 商品轮播图
        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
        if (galleryEntityList == null || galleryEntityList.size() <= 0) {
            throw new RRException("至少添加一张商品轮播图！");
        }

        SysUserEntity user = ShiroUtils.getUserEntity();
        Map<String, Object> map = new HashMap<>();
        map.put("isSame", "true");
        map.put("sku", goods.getSku());
        map.put("goodsSn", goods.getGoodsSn());
        map.put("goodsBizType", goods.getGoodsBizType());
        List<GoodsEntity> list = querySame(map);
        if (list != null && list.size() != 0) {
            throw new RRException("已存在该商品编码或该货品业务类型下已存在此SKU！");
        }

        // 添加商品
        goods.setAttributeCategory(categoryDao.queryObject(goods.getCategoryId()).getParentId());
        goods.setAddTime(new Date());
        goods.setIsDelete(0);
        goods.setIsNew(0);
        goods.setCreateUserId(user.getUserId());
        goods.setUpdateUserId(user.getUserId());
        goods.setUpdateTime(new Date());
        goods.setModTime(new Date());
        goods.setCreateTime(new Date());

        // 新增商品
        goodsDao.save(goods);
        Long id = goods.getId();

        // 添加商品轮播图
        for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
            galleryEntity.setGoodsId(id);
            goodsGalleryDao.save(galleryEntity);
        }

        // 添加商品参数
        List<GoodsAttributeEntity> attributeEntityList = goods.getAttributeEntityList();
        if (attributeEntityList != null && attributeEntityList.size() > 0) {
            for (GoodsAttributeEntity item : attributeEntityList) {
                if (item.getIsDelete() == 0) {
                    if (item.getAttributeId() != null && StringUtils.isNotEmpty(item.getValue())) {
                        item.setGoodsId(id);
                        goodsAttributeDao.save(item);
                    } else if (item.getAttributeId() != null && StringUtils.isNullOrEmpty(item.getValue())) {
                        throw new RRException("商品属性【" + attributeCategoryDao.queryObject(item.getAttributeId()).getName() + "】值不能为空！");
                    } else if (item.getAttributeId() == null) {
                        continue;
                    }
                }
            }
        }

        // 添加产品
        ProductEntity product = new ProductEntity();
        product.setGoodsId(id);
        product.setGoodsSn(goods.getGoodsSn());
        // 保税商品,普通货物暂不添加商品规格
        if (!Dict.orderBizType.item_11.getItem().equals(goods.getGoodsBizType())) {
            // 添加商品规格
            GoodsSpecificationEntity goodsSpecification = new GoodsSpecificationEntity();
            goodsSpecification.setGoodsId(id);
            goodsSpecification.setValue(goods.getCiqProdModel());
            goodsSpecification.setSpecificationId(1);
            goodsSpecificationDao.save(goodsSpecification);

            product.setGoodsSpecificationIds(goodsSpecification.getId().toString());
            product.setGoodsSpecificationNameValue(goodsSpecification.getValue());
        }

        return productDao.save(product);
    }

    @Override
    @Transactional
    public int update(GoodsEntity goods) {
        Map<String, Object> valideDate = MapBeanUtil.fromObject(goods);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("attributeCategory", "商品分类");
        builder.put("categoryId", "商品二级分类");
        builder.put("goodsSn", "商品编码");
        builder.put("goodsBizType", "货品业务类型");
        builder.put("name", "商品名称");
        builder.put("brandId", "品牌");
        builder.put("freightId", "运费模版");
        builder.put("goodsDesc", "商品描述");
        builder.put("isOnSale", "上架");
        builder.put("goodsUnit", "商品单位");
        builder.put("primaryPicUrl", "商品主图");
        builder.put("listPicUrl", "商品列表图");
        builder.put("goodsRate", "商品税率");
        builder.put("isHot", "热销");

        if (!Dict.orderBizType.item_11.getItem().equals(goods.getGoodsBizType())) {
            // 海关信息，普通货物可不添加
            builder.put("sku", "SKU");
            builder.put("retailPrice", "零售价");
            builder.put("prodBarcode", "产品编码");
            builder.put("brand", "产品品牌");
            builder.put("unitCode", "计量单位代码");
            builder.put("cusGoodsCode", "海关商品编码");
            builder.put("ciqProdModel", "国检规格型号");
            builder.put("oriCntCode", "原产国代码");
            builder.put("cusDeclEle", "海关申报要素");
            builder.put("cusRecCode", "海关备案编号");
        }
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }

        // 商品轮播图
        List<GoodsGalleryEntity> galleryEntityList = goods.getGoodsImgList();
        if (galleryEntityList == null || galleryEntityList.size() <= 0) {
            throw new RRException("至少保留一张商品轮播图！");
        }

        SysUserEntity user = ShiroUtils.getUserEntity();
        Map<String, Object> map = new HashMap<>();
        map.put("isSame", "true");
        map.put("sku", goods.getSku());
        map.put("goodsSn", goods.getGoodsSn());
        map.put("goodsBizType", goods.getGoodsBizType());
        map.put("id", goods.getId());
        List<GoodsEntity> list = querySame(map);
        if (list != null && list.size() != 0) {
            throw new RRException("已存在该商品编码或该货品业务类型下已存在此SKU！");
        }

        // 修改商品
        goods.setAttributeCategory(categoryDao.queryObject(goods.getCategoryId()).getParentId());
        goods.setIsDelete(0);
        goods.setIsNew(0);
        goods.setUpdateUserId(user.getUserId());
        goods.setUpdateTime(new Date());
        goods.setModTime(new Date());

        // 修改商品
        goodsDao.update(goods);

        // 保税商品修改各个门店商品价格
        if (!Dict.orderBizType.item_11.getItem().equals(goods.getGoodsBizType())) {
            List<ProductStoreRelaEntity> productStoreRelaEntityList = productStoreRelaDao.queryByGoodsId(goods.getId());
            if (productStoreRelaEntityList != null && productStoreRelaEntityList.size() > 0) {
                for (ProductStoreRelaEntity productStoreRela : productStoreRelaEntityList) {
                    productStoreRela.setRetailPrice(goods.getRetailPrice());
                    productStoreRela.setMarketPrice(goods.getMarketPrice());
                    productStoreRelaDao.update(productStoreRela);
                }
            }
        }

        // 修改商品轮播图
        goodsGalleryDao.deleteByGoodsId(goods.getId());
        for (GoodsGalleryEntity galleryEntity : galleryEntityList) {
            galleryEntity.setGoodsId(goods.getId());
            goodsGalleryDao.save(galleryEntity);
        }

        // 修改商品参数
        List<GoodsAttributeEntity> attributeEntityList = goods.getAttributeEntityList();
        if (attributeEntityList != null && attributeEntityList.size() > 0) {
            for (GoodsAttributeEntity item : attributeEntityList) {
                if (item.getIsDelete() == 0) {
                    if (item.getAttributeId() != null && StringUtils.isNotEmpty(item.getValue())) {
                        item.setGoodsId(goods.getId());
                        goodsAttributeDao.save(item);
                    } else if (item.getAttributeId() != null && StringUtils.isNullOrEmpty(item.getValue())) {
                        throw new RRException("商品属性【" + attributeCategoryDao.queryObject(item.getAttributeId()).getName() + "】值不能为空！");
                    } else if (item.getId() != null) {
                        goodsAttributeDao.update(item);
                    } else if (item.getAttributeId() == null) {
                        continue;
                    }
                } else if (item.getIsDelete() == 1) {
                    goodsAttributeDao.delete(item.getId());
                }
            }
        }

        // 修改产品
        ProductEntity product = productDao.queryObjectBySn(goods.getGoodsSn());
        // 保税商品,普通货物暂不添加商品规格
        if (!Dict.orderBizType.item_11.getItem().equals(goods.getGoodsBizType())) {
            // 添加商品规格
            GoodsSpecificationEntity goodsSpecification = goodsSpecificationDao.queryByGoodsId(goods.getId());
            goodsSpecification.setValue(goods.getCiqProdModel());
            goodsSpecificationDao.update(goodsSpecification);

            product.setGoodsSpecificationNameValue(goodsSpecification.getValue());
        }

        return productDao.update(product);
    }

    @Override
    public int delete(Integer id) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = goodsDao.queryObject(id);
        goodsEntity.setIsDelete(1);
        goodsEntity.setIsOnSale(0);
        goodsEntity.setUpdateUserId(user.getUserId());
        goodsEntity.setUpdateTime(new Date());
        //更新团购
        Map params = new HashMap();
        params.put("goodsId", id);
        List<GoodsGroupEntity> groupVos = goodsGroupDao.queryList(params);
        if (null != groupVos && groupVos.size() > 0) {
            for (GoodsGroupEntity groupVo : groupVos) {
                groupVo.setOpenStatus(3);
                goodsGroupDao.update(groupVo);
            }
        }
        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) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        int result = 0;
        for (Integer id : ids) {
            GoodsEntity goodsEntity = queryObject(id);
            goodsEntity.setIsDelete(0);
            goodsEntity.setIsOnSale(1);
            goodsEntity.setUpdateUserId(user.getUserId());
            goodsEntity.setUpdateTime(new Date());
            result += goodsDao.update(goodsEntity);
        }
        return result;
    }

    @Override
    public int enSale(Integer id) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        if (1 == goodsEntity.getIsOnSale()) {
            throw new RRException("此商品已处于上架状态！");
        }
        goodsEntity.setIsOnSale(1);
        goodsEntity.setUpdateUserId(user.getUserId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }

    @Override
    public int unSale(Integer id) {
        SysUserEntity user = ShiroUtils.getUserEntity();
        GoodsEntity goodsEntity = queryObject(id);
        if (0 == goodsEntity.getIsOnSale()) {
            throw new RRException("此商品已处于下架状态！");
        }
        goodsEntity.setIsOnSale(0);
        goodsEntity.setUpdateUserId(user.getUserId());
        goodsEntity.setUpdateTime(new Date());
        return goodsDao.update(goodsEntity);
    }

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

    @Override
    public int unSaleBatch(Integer[] ids) {
        int result = 0;
        SysUserEntity user = ShiroUtils.getUserEntity();
        for (Integer id : ids) {
            GoodsEntity goodsEntity = queryObject(id);
            goodsEntity.setIsOnSale(0);
            goodsEntity.setUpdateUserId(user.getUserId());
            goodsEntity.setUpdateTime(new Date());
            result += goodsDao.update(goodsEntity);
        }
        return result;
    }

    @Override
    @Transactional
    public int uploadExcel(MultipartFile file) {
        SysUserEntity user = ShiroUtils.getUserEntity();

        List<String[]> list = ExcelImport.getExcelData(file);
        // 取门店名称
        StoreEntity storeEntity = storeDao.queryObjectByName(list.get(0)[3]);
        if (null == storeEntity) {
            return 0;
        }
        //去除表头两行、底部合计
        if (list != null && list.size() > 3) {
            ProductStoreRelaEntity storeRelaEntity;
            ProductEntity productEntity;
            for (int i = 2; i < list.size() - 1; i++) {
                String[] item = list.get(i);
                String goodsSn = item[0];
                productEntity = productDao.queryObjectBySn(goodsSn);
                if (StringUtils.isNullOrEmpty(goodsSn)) {
                    continue;
                }
                if (null == productEntity || null == productEntity.getId()) {
                    continue;
                }
                storeRelaEntity = productStoreRelaDao.queryByStoreIdProductId(storeEntity.getId(), productEntity.getId());
                if (null != storeRelaEntity && null != storeRelaEntity.getId()) {
                    storeRelaEntity.setRetailPrice(new BigDecimal(item[6]));
                    storeRelaEntity.setStockNum(Integer.valueOf(item[3].replace(".00", "")));
                    storeRelaEntity.setStockPrice(new BigDecimal(item[4]));
                    productStoreRelaDao.update(storeRelaEntity);
                } else {
                    storeRelaEntity = new ProductStoreRelaEntity();
                    storeRelaEntity.setGoodsId(productEntity.getGoodsId());
                    storeRelaEntity.setProductId(productEntity.getId());
                    storeRelaEntity.setRetailPrice(new BigDecimal(item[6]));
                    storeRelaEntity.setMarketPrice(new BigDecimal(item[6]));
                    storeRelaEntity.setStockNum(Integer.valueOf(item[3]));
                    storeRelaEntity.setStockPrice(new BigDecimal(item[4]));
                    storeRelaEntity.setStoreId(storeEntity.getId());
                    productStoreRelaDao.save(storeRelaEntity);
                }
            }
        }
        return 1;
    }

    public GoodsEntity queryObjectBySn(String goodsSn) {
        return goodsDao.queryObjectBySn(goodsSn);
    }
}
