
package com.tmerclub.cloud.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.tmerclub.cloud.api.product.dto.BrandShopDTO;
import com.tmerclub.cloud.common.constant.Constant;
import com.tmerclub.cloud.common.constant.StatusEnum;
import com.tmerclub.cloud.common.database.dto.PageDTO;
import com.tmerclub.cloud.common.database.util.PageUtil;
import com.tmerclub.cloud.common.database.vo.PageVO;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.i18n.I18nMessage;
import com.tmerclub.cloud.common.i18n.LanguageEnum;
import com.tmerclub.cloud.common.product.constant.BrandType;
import com.tmerclub.cloud.common.product.vo.BrandVO;
import com.tmerclub.cloud.product.dto.BrandDTO;
import com.tmerclub.cloud.product.dto.BrandSigningDTO;
import com.tmerclub.cloud.product.mapper.BrandLangMapper;
import com.tmerclub.cloud.product.mapper.BrandMapper;
import com.tmerclub.cloud.product.mapper.BrandShopMapper;
import com.tmerclub.cloud.product.mapper.SpuMapper;
import com.tmerclub.cloud.product.model.BrandLang;
import com.tmerclub.cloud.product.model.BrandShop;
import com.tmerclub.cloud.product.model.CategoryBrand;
import com.tmerclub.cloud.product.service.BrandShopService;
import com.tmerclub.cloud.product.service.CategoryBrandService;
import com.tmerclub.cloud.product.vo.BrandShopVO;
import com.tmerclub.cloud.product.vo.BrandSigningVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 品牌店铺关联信息
 *
 * @author tmerclub
 * @date 2021-04-30 13:21:10
 */
@Service
public class BrandShopServiceImpl implements BrandShopService {

    @Autowired
    private BrandShopMapper brandShopMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private BrandLangMapper brandLangMapper;
    @Autowired
    private CategoryBrandService categoryBrandService;
    @Autowired
    private SpuMapper spuMapper;

    private static final Logger log = LoggerFactory.getLogger(BrandShopServiceImpl.class);

    @Override
    public PageVO<BrandShop> page(PageDTO pageDTO) {
        return PageUtil.doPage(pageDTO, () -> brandShopMapper.list());
    }

    @Override
    public BrandShop getByBrandShopId(Long brandShopId) {
        return brandShopMapper.getByBrandShopId(brandShopId);
    }

    @Override
    public void save(BrandShop brandShop) {
        brandShopMapper.save(brandShop);
    }

    @Override
    public void update(BrandShop brandShop) {
        brandShopMapper.update(brandShop);
    }

    @Override
    public void deleteById(Long brandShopId) {
        brandShopMapper.deleteById(brandShopId);
    }

    @Override
    public BrandSigningVO listSigningByShopId(Long shopId, Integer sysType) {
        // 查询平台品牌签约列表
        List<BrandShopVO> platformBrandList = brandShopMapper.listByShopIdAndType(shopId, BrandType.PLATFORM.value(), I18nMessage.getLang(), sysType);
        // 查询店铺自定义品牌签约列表
        List<BrandShopVO> customizeBrandList = brandShopMapper.listByShopIdAndType(shopId, BrandType.CUSTOMIZE.value(), I18nMessage.getLang(), sysType);
        categoryBrandService.loadCategoryToBrandSigningVO(platformBrandList);
        categoryBrandService.loadCategoryToBrandSigningVO(customizeBrandList);
        BrandSigningVO brandSigningVO = new BrandSigningVO();
        brandSigningVO.setCustomizeBrandList(customizeBrandList);
        brandSigningVO.setPlatformBrandList(platformBrandList);
        return brandSigningVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signingBrands(BrandSigningDTO brandSigningDTO, Long shopId, Integer sysType) {
        if (Objects.equals(Constant.PLATFORM_SHOP_ID, shopId)) {
            // 防止误删平台品牌
            return;
        }
        List<BrandShopDTO> platformBrandList = brandSigningDTO.getPlatformBrandList();
        List<BrandShopDTO> customizeBrandList = brandSigningDTO.getCustomizeBrandList();
        if (platformBrandList.size() + customizeBrandList.size() > Constant.SIGNING_BRAND_LIMIT_NUM) {
            throw new LuckException("签约的品牌数量不能超过" + Constant.SIGNING_BRAND_LIMIT_NUM);
        }
        // 删除已签约的信息
        brandShopMapper.deleteBatchByShopId(shopId, sysType);
        // 处理签约的平台品牌
        if (Objects.nonNull(brandSigningDTO.getPlatformBrandList()) && brandSigningDTO.getPlatformBrandList().size() != 0) {
            List<BrandVO> brandVOList = brandMapper.listByIds(platformBrandList.stream().map(BrandShopDTO::getBrandId).collect(Collectors.toList()));
            if (brandVOList.size() != platformBrandList.size()) {
                throw new LuckException("平台品牌签约信息错误");
            }
            // 插入品牌签约关联信息
            brandShopMapper.insertBatch(shopId, platformBrandList, BrandType.PLATFORM.value(), sysType);
        }
        // 处理新增的自定义品牌
        // 查询之前新增的自定义品牌列表
        List<BrandVO> oldBrandVOList = brandMapper.listByShopId(shopId, sysType);
        if (oldBrandVOList.size() != 0) {
            // 删除店铺自定义的品牌信息
            brandMapper.deleteBatchByShopId(shopId, sysType);
            brandLangMapper.deleteBatchByBrandIds(oldBrandVOList.stream().map(BrandVO::getBrandId).collect(Collectors.toList()));
        }
        if (Objects.nonNull(brandSigningDTO.getCustomizeBrandList()) && brandSigningDTO.getCustomizeBrandList().size() != 0) {
            // 重新新增店铺自定义的品牌信息列表

            customizeBrandList.forEach(item -> {
                List<BrandLang> brandLangList = brandLangMapper.selectByBrandNamesCnOrEn(item.getName(), item.getName());
                //判断品牌名称是否重复
                if (!brandLangList.isEmpty()) {
                    log.info("品牌名重复了");
                    throw new LuckException("品牌名不能重复");
                }
                item.setShopId(shopId);
                item.setSysType(sysType);
                item.setBrandId(null);
                item.setIsTop(0);
                item.setSeq(0);
                item.setStatus(StatusEnum.WAIT_AUDIT.value());
            });
            brandMapper.insertBatchByBrandShopList(customizeBrandList);
            brandLangMapper.insertBatch(customizeBrandList, LanguageEnum.LANGUAGE_ZH_CN.getLang());
            brandLangMapper.insertBatch(customizeBrandList, LanguageEnum.LANGUAGE_EN.getLang());
            brandShopMapper.insertBatch(shopId, customizeBrandList, BrandType.CUSTOMIZE.value(), sysType);
            batchCategoryBrand(customizeBrandList);
        }
    }

    @Override
    public void updateTypeByShopId(Long shopId, Integer type, Integer sysType) {
        brandShopMapper.updateTypeByShopId(shopId, type, sysType);
    }

    @Override
    public void deleteByBrandId(Long brandId) {
        brandShopMapper.deleteByBrandId(brandId);
    }

    @Override
    public void insertBatchByShopId(List<BrandShopDTO> brandShopDTOList, Long shopId, Integer sysType) {
        if (CollUtil.isEmpty(brandShopDTOList)) {
            return;
        }
        int signedCount = brandShopMapper.countByShopIdAndBrandId(shopId, null, sysType);
        if (signedCount + brandShopDTOList.size() > Constant.SIGNING_BRAND_LIMIT_NUM) {
            throw new LuckException("签约的品牌数量不能超过" + Constant.SIGNING_BRAND_LIMIT_NUM);
        }
        brandShopMapper.insertBatch(shopId, brandShopDTOList, BrandType.PLATFORM.value(), sysType);
    }

    @Override
    public int countByShopIdAndBrandId(Long shopId, Long brandId, Integer sysType) {
        return brandShopMapper.countByShopIdAndBrandId(shopId, brandId, sysType);
    }

    private void batchCategoryBrand(List<BrandShopDTO> customizeBrandList) {
        List<CategoryBrand> categoryBrands = new ArrayList<>(Constant.INITIAL_CAPACITY);
        for (BrandShopDTO brandShopDTO : customizeBrandList) {
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(brandShopDTO.getBrandId());
            categoryBrand.setCategoryId(brandShopDTO.getCategoryId());
            categoryBrands.add(categoryBrand);
        }
        categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSigningBrand(Long brandShopId) {
        BrandShop brandShop = brandShopMapper.getByBrandShopId(brandShopId);
        if (Objects.isNull(brandShop)) {
            throw new LuckException("找不到当前签约品牌,请刷新后重试");
        }
        Long brandId = brandShop.getBrandId();
        Long shopId = brandShop.getShopId();
        Integer sysType = brandShop.getSysType();
        spuMapper.updateSpuByBrandIdAndShopId(Collections.singletonList(brandId), shopId, sysType);
        brandMapper.batchUpdateSpuCount(Collections.singletonList(brandId));
        brandShopMapper.deleteById(brandShopId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSigningBrand(BrandSigningDTO brandSigningDTO, Long shopId, Integer sysType) {
        List<BrandShopDTO> platformBrandList = brandSigningDTO.getPlatformBrandList();
        List<BrandShopDTO> customizeBrandList = brandSigningDTO.getCustomizeBrandList();

        Map<Long, BrandShopDTO> applySigningBrandMap = platformBrandList.stream().collect(Collectors.toMap(BrandShopDTO::getBrandId, brandShopDTO -> brandShopDTO));

        List<Long> signedBrandIdList = brandShopMapper.listBrandIdByShopId(shopId, sysType);
        signedBrandIdList.forEach(applySigningBrandMap::remove);
        // 查询已有的平台品牌
        BrandDTO brandDTO = new BrandDTO();
        brandDTO.setShopId(Constant.PLATFORM_SHOP_ID);
        brandDTO.setStatus(StatusEnum.ENABLE.value());
        List<BrandVO> brandVOList = brandMapper.listByParams(brandDTO);
        Set<Long> platformBrandSet = brandVOList.stream().map(BrandVO::getBrandId).collect(Collectors.toSet());
        // 删除新增品牌中所含有的但平台不存在的品牌
        for (Map.Entry<Long, BrandShopDTO> brandShopEntry : applySigningBrandMap.entrySet()) {
            Long brandId = brandShopEntry.getKey();
            if (!platformBrandSet.contains(brandId)) {
                applySigningBrandMap.remove(brandId);
            }
        }
        platformBrandList = new ArrayList<>(applySigningBrandMap.values());
        if (platformBrandList.size() + customizeBrandList.size() > Constant.SIGNING_BRAND_LIMIT_NUM) {
            throw new LuckException("签约的品牌数量不能超过" + Constant.SIGNING_BRAND_LIMIT_NUM);
        }

        // 插入品牌签约关联信息
        if (CollUtil.isNotEmpty(platformBrandList)) {
            brandShopMapper.insertBatch(shopId, platformBrandList, BrandType.PLATFORM.value(), sysType);
        }

        // 处理新增的自定义品牌
        // todo 处理方式暂不明确（1、直接把店铺自定义品牌转成平台品牌  2、审核通过后再进行转换）
        if (CollUtil.isEmpty(customizeBrandList)) {
            return;
        }
        // 查询之前新增的自定义品牌列表
        List<BrandVO> oldBrandVOList = brandMapper.listByShopId(shopId, sysType);
        if (CollUtil.isNotEmpty(oldBrandVOList)) {
            // 删除店铺自定义的品牌信息
            List<Long> brandIdList = oldBrandVOList.stream().map(BrandVO::getBrandId).collect(Collectors.toList());
            brandMapper.deleteBatchByShopId(shopId, sysType);
            brandLangMapper.deleteBatchByBrandIds(brandIdList);
            categoryBrandService.deleteByBrandIdList(brandIdList);
        }
        if (CollUtil.isNotEmpty(customizeBrandList)) {
            // 重新新增店铺自定义的品牌信息列表
            customizeBrandList.forEach(item -> {
                item.setShopId(shopId);
                item.setSysType(sysType);
                item.setBrandId(null);
                item.setIsTop(0);
                item.setSeq(0);
                item.setStatus(StatusEnum.ENABLE.value());
            });
            brandMapper.insertBatchByBrandShopList(customizeBrandList);
            brandLangMapper.insertBatch(customizeBrandList, LanguageEnum.LANGUAGE_ZH_CN.getLang());
            brandLangMapper.insertBatch(customizeBrandList, LanguageEnum.LANGUAGE_EN.getLang());
            brandShopMapper.insertBatch(shopId, customizeBrandList, BrandType.CUSTOMIZE.value(), sysType);
            batchCategoryBrand(customizeBrandList);
        }
    }
}
