package com.kmall.admin.service.impl;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.dao.CategoryDao;
import com.kmall.admin.dao.GoodsDao;
import com.kmall.admin.dao.ProductStoreRelaDao;
import com.kmall.admin.dao.StoreDao;
import com.kmall.admin.dto.CateStoreDto;
import com.kmall.admin.dto.CopyCategoryDto;
import com.kmall.admin.entity.CategoryEntity;
import com.kmall.admin.entity.GoodsEntity;
import com.kmall.admin.entity.ProductStoreRelaEntity;
import com.kmall.admin.entity.StoreEntity;
import com.kmall.admin.service.CategoryService;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.MapBeanUtil;
import com.kmall.common.utils.R;
import com.kmall.common.utils.RRException;
import com.kmall.common.utils.ValidatorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service实现类
 *
 * @author Scott
 * @email
 * @date 2017-08-21 15:32:31
 */
@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private StoreDao storeDao;

    @Override
    public CategoryEntity queryObject(Integer id) {
        return categoryDao.queryObject(id);
    }

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

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

    @Override
    public int save(CategoryEntity category) {
        if (Dict.Level.item_L1.getItem().equals(category.getLevel())) {
            category.setParentId(0);
        } else {
            if (category.getParentId() == null) {
                throw new RRException("请选择父级分类！");
            }
        }

        Map<String, Object> valideDate = MapBeanUtil.fromObject(category);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("merchSn", "商户");
        builder.put("storeId", "门店");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(category.getLevel().equalsIgnoreCase("L1")){
            category.setParentId(0);
        }

        return categoryDao.save(category);
    }

    @Override
    public int update(CategoryEntity category) {

        Map<String, Object> valideDate = MapBeanUtil.fromObject(category);
        ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
        builder.put("merchSn", "商户");
        builder.put("storeId", "门店");
        R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
        if (Integer.valueOf(r.get("code").toString()) != 0) {
            throw new RRException(r.get("msg").toString());
        }
        if(category.getLevel().equalsIgnoreCase("L1")){
            category.setParentId(0);
        }

        return categoryDao.update(category);
    }

    @Override
    public int delete(Integer id) {
        CategoryEntity categoryEntity = categoryDao.queryObject(id);
        if(categoryEntity != null){
            if(categoryEntity.getLevel().equalsIgnoreCase(Dict.Level.item_L1.getItem())){//一级分类先删除二级分类
                Map map = new HashMap();
                map.put("parentId", categoryEntity.getId());
                List<CategoryEntity> list = categoryDao.queryList(map);
                for(CategoryEntity category: list){
                    categoryDao.delete(category.getId());
                }
                categoryDao.delete(id);
            }else{
                return categoryDao.delete(id);
            }
        }
        return 1;
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        for (Integer id : ids) {
            CategoryEntity category = queryObject(id);
            Map<String, Object> map = new HashMap<>();
            if (category.getParentId() == 0) {
                map.put("parentId", id);
                List<CategoryEntity> categoryEntityList = queryList(map);

                if (categoryEntityList != null && categoryEntityList.size() > 0) {
                    int goodsTotal = 0;
                    for (CategoryEntity categoryEntity : categoryEntityList) {
                        map.clear();
                        map.put("categoryId", categoryEntity.getId());
                        map.put("isDelete", Dict.isDelete.item_1.getItem());
                        map.put("storeId", categoryEntity.getStoreId());
                        List<ProductStoreRelaEntity> storeRelaEntityList = productStoreRelaDao.queryList(map);
                        if (storeRelaEntityList != null) {
                            goodsTotal += storeRelaEntityList.size();
                        }
                    }

                    if (goodsTotal > 0) {
                        throw new RRException("【" + category.getName() + "】商品类型下还有【" + goodsTotal + "】个商品，无法删除！");
                    } else {
                        for (CategoryEntity categoryEntity : categoryEntityList) {
                            delete(categoryEntity.getId());
                        }
                    }
                }
            } else{
                map.clear();
                map.put("categoryId",id);
                List<ProductStoreRelaEntity> storeRelaEntityList = productStoreRelaDao.queryList(map);
                if (storeRelaEntityList != null && storeRelaEntityList.size() > 0) {
                    throw new RRException("【" + category.getName() + "】商品类型下还有【" + storeRelaEntityList.size() + "】个商品，无法删除！");
                }
            }

            delete(id);
        }
        return 1;
    }

    @Override
    public CopyCategoryDto checkCateStoreUpload(List<CateStoreDto> cateStoreDtoList){
        Boolean isFalse = false;
        List<String> storeIdErrorList = new ArrayList<>();
        List<String> cateIdErrorList = new ArrayList<>();
        for(CateStoreDto cateStoreDto : cateStoreDtoList) {
            Map<String, Object> valideDate = MapBeanUtil.fromObject(cateStoreDto);
            ImmutableBiMap.Builder builder = new ImmutableBiMap.Builder();
            builder.put("categoryId", "分类id");
            builder.put("storeId", "门店id");
            R r = ValidatorUtil.isEmpty(builder.build(), valideDate);
            if (Integer.valueOf(r.get("code").toString()) != 0) {
                throw new RRException(r.get("msg").toString());
            }
            StoreEntity storeEntity = storeDao.queryObject(cateStoreDto.getStoreId());
            if (storeEntity == null) {
                isFalse = true;
                storeIdErrorList.add(cateStoreDto.getStoreId());
            }
            CategoryEntity categoryEntity = categoryDao.queryObject(cateStoreDto.getCategoryId());
            if (categoryEntity == null) {
                isFalse = true;
                cateIdErrorList.add(cateStoreDto.getCategoryId());
            }
        }
        if(isFalse){
            if(storeIdErrorList!=null && storeIdErrorList.size()>0){
                throw new RRException("门店id不存在，不存在id【" + storeIdErrorList + "】");
            }
            if(cateIdErrorList!=null && cateIdErrorList.size()>0){
                throw new RRException("分类id不存在，不存在id【" + cateIdErrorList + "】");
            }
        }else{
            CopyCategoryDto copyCategoryDto = new CopyCategoryDto();
            StringBuffer storeIds = new StringBuffer();
            StringBuffer cateIds = new StringBuffer();
            for(CateStoreDto cateStoreDto : cateStoreDtoList){
                storeIds.append(cateStoreDto.getStoreId()+";");
                cateIds.append(cateStoreDto.getCategoryId()+";");
            }
            copyCategoryDto.setStoreList(storeIds.toString());
            copyCategoryDto.setCategoryList(cateIds.toString());
            return copyCategoryDto;
        }
        return null;
    }

    public int saveCopyCategory(CopyCategoryDto copyCategoryDto){
        CategoryEntity categoryEntity = categoryDao.queryObject(copyCategoryDto.getCategoryId());
        if(categoryEntity != null){
            if(Dict.Level.item_L1.getItem().equalsIgnoreCase(categoryEntity.getLevel())){
                List<Integer> storeIdList = new ArrayList<>();
                String[] storeIds = copyCategoryDto.getStoreList().split(";");
                for(int i = 0; i < storeIds.length; i++){
                    storeIdList.add(Integer.valueOf(storeIds[i]));
                }
                for(int i = 0; i < storeIdList.size(); i++){
                    CategoryEntity category = new CategoryEntity();
                    category.setParentId(categoryEntity.getParentId());
                    StoreEntity storeEntity = storeDao.queryObject(storeIdList.get(i));
                    if(storeEntity == null){
                        throw new RRException("门店不存在");
                    }
                    category.setName(categoryEntity.getName());
                    category.setKeywords(categoryEntity.getKeywords());
                    category.setFrontDesc(categoryEntity.getFrontDesc());
                    category.setSortOrder(categoryEntity.getSortOrder());

                    category.setShowIndex(categoryEntity.getShowIndex());
                    category.setIsShow(categoryEntity.getIsShow());
                    category.setBannerUrl(categoryEntity.getBannerUrl());
                    category.setIconUrl(categoryEntity.getIconUrl());
                    category.setImgUrl(categoryEntity.getImgUrl());
                    category.setWapBannerUrl(categoryEntity.getWapBannerUrl());
                    category.setLevel(categoryEntity.getLevel());
                    category.setType(categoryEntity.getType());
                    category.setFrontName(categoryEntity.getFrontName());
                    category.setMerchSn(storeEntity.getMerchSn());
                    category.setStoreId(storeIdList.get(i));
                    categoryDao.save(category);
                }
            }else {
                List<Integer> storeIdList = new ArrayList<>();
                List<Integer> categoryIdList = new ArrayList<>();
                String[] storeIds = copyCategoryDto.getStoreList().split(";");
                String[] categoryIds = copyCategoryDto.getCategoryList().split(";");
                for(int i = 0; i < storeIds.length; i++){
                    storeIdList.add(Integer.valueOf(storeIds[i]));
                    categoryIdList.add(Integer.valueOf(categoryIds[i]));
                }
                for(int i = 0; i < storeIdList.size(); i++){
                    CategoryEntity category = new CategoryEntity();
                    StoreEntity storeEntity = storeDao.queryObject(storeIdList.get(i));
                    if(storeEntity == null){
                        throw new RRException("门店不存在");
                    }
                    CategoryEntity parentCateEntity = categoryDao.queryObject(categoryIdList.get(i));
                    if(parentCateEntity == null){
                        throw new RRException("分类不存在");
                    }
                    category.setParentId(categoryIdList.get(i));
                    category.setName(categoryEntity.getName());
                    category.setKeywords(categoryEntity.getKeywords());
                    category.setFrontDesc(categoryEntity.getFrontDesc());
                    category.setSortOrder(categoryEntity.getSortOrder());

                    category.setShowIndex(categoryEntity.getShowIndex());
                    category.setIsShow(categoryEntity.getIsShow());
                    category.setBannerUrl(categoryEntity.getBannerUrl());
                    category.setIconUrl(categoryEntity.getIconUrl());
                    category.setImgUrl(categoryEntity.getImgUrl());
                    category.setWapBannerUrl(categoryEntity.getWapBannerUrl());
                    category.setLevel(categoryEntity.getLevel());
                    category.setType(categoryEntity.getType());
                    category.setFrontName(categoryEntity.getFrontName());
                    category.setMerchSn(storeEntity.getMerchSn());
                    category.setStoreId(storeIdList.get(i));
                    categoryDao.save(category);
                }

            }
        }
        return 1;
    }
}
