package com.kmall.admin.service.impl;

import com.google.common.collect.ImmutableBiMap;
import com.kmall.admin.dao.*;
import com.kmall.admin.dto.CopyFreightDto;
import com.kmall.admin.entity.*;
import com.kmall.admin.service.FreightService;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * Service实现类
 *
 * @author huangyq
 * @email admin@qhdswl.com
 * @date 2018-10-22 15:18:16
 */
@Service("freightService")
public class FreightServiceImpl
        implements FreightService {
    @Autowired
    private FreightDao freightDao;
    @Autowired
    private FreightItemDao freightItemDao;
    @Autowired
    private ProductStoreRelaDao productStoreRelaDao;
    @Autowired
    private StoreDao storeDao;

    @Override
    public FreightEntity queryObject(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("freId", id);
        List<FreightItemEntity> freightItemEntityList = freightItemDao.queryList(map);
        FreightEntity freightEntity = freightDao.queryObject(id);
        freightEntity.setFreightItemEntityList(freightItemEntityList);
        return freightEntity;
    }

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

    @Override
    public List<FreightEntity> queryEntity(Map<String, Object> map) {
        return freightDao.queryEntity(map);
    }

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

    @Override
    @Transactional
    public int save(FreightEntity freight) {
        Map<String, Object> map = new HashMap<>();
        map.put("storeId", freight.getStoreId());
        map.put("merchSn", freight.getMerchSn());
        map.put("name", freight.getName());
        List<FreightEntity> list = queryList(map);
        if (list != null && list.size() != 0) {
            throw new RRException("运费模版名称已存在！");
        }

        Map<String, Object> valideDate = MapBeanUtil.fromObject(freight);
        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 (Boolean.valueOf(freight.getIsDefault())) {
            freight.setIsDefault("1");
        } else {
            freight.setIsDefault("0");
        }

        // 运费详情
        List<FreightItemEntity> freightItemEntityList = freight.getFreightItemEntityList();
        if (freight.getFreightItemEntityList() == null || freight.getFreightItemEntityList().size() == 0) {
            throw new RRException("配送区域及运费不能为空");
        }

        freight.setDefaultFreight(freightItemEntityList.get(0).getFreight());
        int res = freightDao.save(freight);

        for (FreightItemEntity item : freightItemEntityList) {
            if (Boolean.valueOf(item.getDeliveryArea())) {
                item.setDeliveryArea("ALL");
            }
            if (item.getFreId() == null) {
                item.setFreId(freight.getId());
                freightItemDao.save(item);
            }
        }
        return res;
    }

    @Override
    @Transactional
    public int update(FreightEntity freight) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", freight.getId());
        map.put("storeId", freight.getStoreId());
        map.put("merchSn", freight.getMerchSn());
        map.put("name", freight.getName());
        List<FreightEntity> list = queryEntity(map);
        if (list != null && list.size() != 0) {
            throw new RRException("运费模版名称已存在！");
        }

        Map<String, Object> valideDate = MapBeanUtil.fromObject(freight);
        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 (Boolean.valueOf(freight.getIsDefault())) {
            freight.setIsDefault("1");
        } else {
            freight.setIsDefault("0");
        }

        // 运费详情
        if (freightItemDao.deleteByFreId(freight.getId()) <= 0) {
            throw new RRException("删除原运费模版详情失败！");
        }
        List<FreightItemEntity> freightItemEntityList = freight.getFreightItemEntityList();
        if (null != freightItemEntityList && freightItemEntityList.size() > 0) {
            freight.setDefaultFreight(freightItemEntityList.get(0).getFreight());
            for (FreightItemEntity item : freightItemEntityList) {
                if (Boolean.valueOf(item.getDeliveryArea())) {
                    item.setDeliveryArea("ALL");
                }
                if (item.getFreId() != null) {
                    freightItemDao.save(item);
                }
            }
        }
        return freightDao.update(freight);
    }

    @Override
    public int delete(Integer id) {
        Map<String, Object> map = new HashMap<>();
        map.put("storeId", queryObject(id).getStoreId());
        map.put("freightId", id);
//        List<GoodsEntity> list = goodsDao.queryList(map);
        List<ProductStoreRelaEntity> list = productStoreRelaDao.queryList(map);

        if (list != null && list.size() > 0) {
            throw new RRException("此运费模版还有【" + list.size() + "】商品正在使用，不能删除！");
        }
        freightItemDao.deleteByFreId(id);

        return freightDao.delete(id);
    }

    @Override
    public int deleteBatch(Integer[] ids) {
        for (int id : ids) {
            Map<String, Object> map = new HashMap<>();
            Integer storeId = queryObject(id).getStoreId();
            map.put("storeId", storeId);
            map.put("freightId", id);
            map.put("isDelete", 0);
            List<ProductStoreRelaEntity> list = productStoreRelaDao.queryList(map);

            if (list != null && list.size() > 0) {
                throw new RRException("门店【"+ storeId +"】运费模版【" + id + "】还有【" + list.size() + "】个商品正在使用，不能删除！");
            }
            freightItemDao.deleteByFreId(id);
        }
        return freightDao.deleteBatch(ids);
    }

    @Override
    @Transactional
    public int saveCopyFreight(CopyFreightDto copyFreightDto){
        FreightEntity freightEntity = freightDao.queryObject(copyFreightDto.getFreightId());
        if(freightEntity != null){
            List<Integer> storeIdList = new ArrayList<>();
            String[] storeIds = copyFreightDto.getStoreList().split(";");
            for(int i = 0; i < storeIds.length; i++){
                storeIdList.add(Integer.valueOf(storeIds[i]));
            }
            for(int i = 0; i < storeIdList.size(); i++){
                FreightEntity freight = new FreightEntity();
                StoreEntity storeEntity = storeDao.queryObject(storeIdList.get(i));
                if(storeEntity == null){
                    throw new RRException("门店不存在");
                }
                Map<String, Object> map = new HashMap<>();
                map.put("storeId", storeEntity.getId());
                map.put("merchSn", storeEntity.getMerchSn());
                map.put("name", freightEntity.getName());
                List<FreightEntity> list = queryList(map);
                if (list != null && list.size() != 0) {
                    throw new RRException("excel中的门店id【"+storeIdList.get(i)+"】运费模版名称【"+freightEntity.getName()+"】已存在！请检查！");
                }
                freight.setName(freightEntity.getName());
                freight.setTemplateType(freightEntity.getTemplateType());
                freight.setPricingManner(freightEntity.getPricingManner());
                freight.setDefaultFreight(freightEntity.getDefaultFreight());
                freight.setIsDefault(freightEntity.getIsDefault());
                freight.setMerchSn(storeEntity.getMerchSn());
                freight.setStoreId(storeIdList.get(i));
                freightDao.save(freight);
                FreightItemEntity itemEntity = freightItemDao.queryObjectByFreightId(freightEntity.getId());
                if(itemEntity != null){
                    FreightItemEntity freightItemEntity = new FreightItemEntity();
                    freightItemEntity.setFreId(freight.getId());//新增的运费id
                    freightItemEntity.setDeliveryArea(itemEntity.getDeliveryArea());
                    freightItemEntity.setFirstPiece(itemEntity.getFirstPiece());
                    freightItemEntity.setFreight(itemEntity.getFreight());
                    freightItemEntity.setContinuePiece(itemEntity.getContinuePiece());
                    freightItemEntity.setRenew(itemEntity.getRenew());
                    freightItemDao.save(freightItemEntity);
                }
            }
        }
        return 1;
    }
}
