package com.kmall.admin.service.impl;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.dao.*;
import com.kmall.admin.dto.CateStoreDto;
import com.kmall.admin.dto.CopyBrandDto;
import com.kmall.admin.entity.*;
import com.kmall.admin.service.BrandService;
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-19 17:59:15
 */
@Service("brandService")
public class BrandServiceImpl implements BrandService {
    @Autowired
    private BrandDao brandDao;
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private StoreDao storeDao;
    @Autowired
    private CategoryDao categoryDao;

    @Override
    public BrandEntity queryObject(Integer id) {
        return brandDao.queryObject(id);
    }

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

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

    @Override
    public int save(BrandEntity brand) {
        return brandDao.save(brand);
    }

    @Override
    public int update(BrandEntity brand) {
        return brandDao.update(brand);
    }

    @Override
    public int delete(Integer id) {
        return brandDao.delete(id);
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        for (Integer id : ids) {
            BrandEntity brand = queryObject(id);

            Map<String, Object> map = new HashMap<>();
            map.put("storeId", brand.getStoreId());
            map.put("brandId", id);
            List<ProductStoreRelaEntity> goodsList = productStoreRelaDao.queryList(map);

            if (goodsList != null && goodsList.size() > 0) {
                throw new RRException("门店【"+brand.getStoreId()+"】品牌【" + brand.getName() + "】下还存在【" + goodsList.size() + "】个商品，删除失败！");
            }
            delete(id);
        }

        return 1;
    }

    /**
     * 检查批量导入品牌数据
     * @param cateStoreDtoList
     * @return
     */
    @Override
    public CopyBrandDto checkBrandStoreUpload(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());
            }else{
                if(categoryEntity.getStoreId() != Integer.parseInt(cateStoreDto.getStoreId())){
                    throw new RRException("分类id【" + cateStoreDto.getCategoryId() + "】不属于门店id【"+cateStoreDto.getStoreId()+"】内，请检查");
                }
            }
        }
        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{
            CopyBrandDto copyBrandDto = new CopyBrandDto();
            StringBuffer storeIds = new StringBuffer();
            StringBuffer cateIds = new StringBuffer();
            for(CateStoreDto cateStoreDto : cateStoreDtoList){
                storeIds.append(cateStoreDto.getStoreId()+";");
                cateIds.append(cateStoreDto.getCategoryId()+";");
            }
            copyBrandDto.setStoreList(storeIds.toString());
            copyBrandDto.setCategoryList(cateIds.toString());
            return copyBrandDto;
        }
        return null;
    }

    public int saveCopyCategory(CopyBrandDto copyBrandDto){
        BrandEntity brandEntity = brandDao.queryObject(copyBrandDto.getBrandId());
        if(brandEntity != null){
            List<Integer> storeIdList = new ArrayList<>();
            List<Integer> cateIdList = new ArrayList<>();
            String[] storeIds = copyBrandDto.getStoreList().split(";");
            String[] cateIds = copyBrandDto.getCategoryList().split(";");
            for(int i = 0; i < storeIds.length; i++){
                storeIdList.add(Integer.valueOf(storeIds[i]));
                cateIdList.add(Integer.valueOf(cateIds[i]));
            }
            for(int i = 0; i < storeIdList.size(); i++){
                BrandEntity brand = new BrandEntity();
                StoreEntity storeEntity = storeDao.queryObject(storeIdList.get(i));
                if(storeEntity == null){
                    throw new RRException("门店不存在");
                }
                brand.setName(brandEntity.getName());
                brand.setListPicUrl(brandEntity.getListPicUrl());
                brand.setSimpleDesc(brandEntity.getSimpleDesc());
                brand.setPicUrl(brandEntity.getPicUrl());
                brand.setSortOrder(brandEntity.getSortOrder());
                brand.setIsShow(brandEntity.getIsShow());
                brand.setFloorPrice(brandEntity.getFloorPrice());
                brand.setAppListPicUrl(brandEntity.getAppListPicUrl());
                brand.setIsNew(brandEntity.getIsNew());
                brand.setNewPicUrl(brandEntity.getNewPicUrl());
                brand.setNewSortOrder(brandEntity.getNewSortOrder());
                brand.setCategoryId(cateIdList.get(i));
                brand.setMerchSn(storeEntity.getMerchSn());
                brand.setStoreId(storeIdList.get(i));
                brandDao.save(brand);
            }
        }
        return 1;
    }
}
