package com.slodon.b2b2c.model.goods;

import com.slodon.b2b2c.core.constant.GoodsConst;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.b2b2c.dao.read.goods.GoodsBrandReadMapper;
import com.slodon.b2b2c.dao.read.goods.GoodsCategoryReadMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsBrandWriteMapper;
import com.slodon.b2b2c.dao.write.goods.GoodsCategoryBindBrandWriteMapper;
import com.slodon.b2b2c.goods.dto.ApplyBrandAddDTO;
import com.slodon.b2b2c.goods.dto.ApplyBrandUpdateDTO;
import com.slodon.b2b2c.goods.dto.GoodsBrandAddDTO;
import com.slodon.b2b2c.goods.dto.GoodsBrandUpdateDTO;
import com.slodon.b2b2c.goods.example.GoodsBrandExample;
import com.slodon.b2b2c.goods.example.GoodsCategoryBindBrandExample;
import com.slodon.b2b2c.goods.pojo.GoodsBrand;
import com.slodon.b2b2c.goods.pojo.GoodsCategory;
import com.slodon.b2b2c.seller.pojo.Vendor;
import com.slodon.b2b2c.vo.goods.GoodsBrandFrontVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class GoodsBrandModel {

    @Resource
    private GoodsBrandReadMapper goodsBrandReadMapper;
    @Resource
    private GoodsBrandWriteMapper goodsBrandWriteMapper;
    @Resource
    private GoodsCategoryBindBrandWriteMapper goodsCategoryBindBrandWriteMapper;
    @Resource
    private GoodsCategoryReadMapper goodsCategoryReadMapper;

    /**
     * 新增商品品牌
     *
     * @param goodsBrand
     * @return
     */
    public Integer saveGoodsBrand(GoodsBrand goodsBrand) {
        int count = goodsBrandWriteMapper.insert(goodsBrand);
        if (count == 0) {
            throw new MallException("添加商品品牌失败，请重试");
        }
        return goodsBrand.getBrandId();
    }

    /**
     * 新增品牌
     *
     * @param goodsBrandAddDTO
     * @param adminId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer saveGoodsBrand(Integer adminId, GoodsBrandAddDTO goodsBrandAddDTO) {
        //判断品牌名称是否重复
        GoodsBrandExample example = new GoodsBrandExample();
        example.setBrandName(goodsBrandAddDTO.getBrandName());
        example.setWebSite(goodsBrandAddDTO.getWebSite());
        List<GoodsBrand> list = goodsBrandReadMapper.listByExample(example);
        if (!CollectionUtils.isEmpty(list)) {
            throw new MallException("品牌名称已存在，请重新填写");
        }

        //插入品牌表
        GoodsBrand goodsBrandInsert = new GoodsBrand();
        goodsBrandInsert.setWebSite(goodsBrandAddDTO.getWebSite());
        goodsBrandInsert.setBrandName(goodsBrandAddDTO.getBrandName());
        goodsBrandInsert.setBrandDesc(goodsBrandAddDTO.getBrandDesc());
        goodsBrandInsert.setImage(goodsBrandAddDTO.getImage());
        goodsBrandInsert.setBrandInitial(StringUtil.GetFirstChar(goodsBrandAddDTO.getBrandName()));
        goodsBrandInsert.setIsRecommend(GoodsConst.IS_BRAND_RECOMMEND_YES);
        goodsBrandInsert.setSort(GoodsConst.BRAND_SORT);
        goodsBrandInsert.setCreateAdminId(adminId);
        goodsBrandInsert.setCreateTime(new Date());
        goodsBrandInsert.setApplyVendorId(0L);
        goodsBrandInsert.setApplyStoreId(0L);
        goodsBrandInsert.setState(GoodsConst.BRAND_STATE_1);
        return this.saveGoodsBrand(goodsBrandInsert);
    }

    /**
     * 商户申请品牌
     *
     * @param applyBrandAddDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveSellersBrand(ApplyBrandAddDTO applyBrandAddDTO, Vendor vendor) {
        //判断品牌名称是否重复
        GoodsBrandExample example = new GoodsBrandExample();
        example.setBrandName(applyBrandAddDTO.getBrandName());
        example.setWebSite(applyBrandAddDTO.getWebSite());
        example.setApplyStoreId(vendor.getStoreId());
        List<GoodsBrand> list = goodsBrandReadMapper.listByExample(example);
        AssertUtil.isTrue(!CollectionUtils.isEmpty(list), "品牌名称已存在，请重新填写");

        //查询分类信息
        GoodsCategory goodsCategory3 = goodsCategoryReadMapper.getByPrimaryKey(applyBrandAddDTO.getCategoryId());
        AssertUtil.notNull(goodsCategory3, "分类有误");
        GoodsCategory goodsCategory2 = goodsCategoryReadMapper.getByPrimaryKey(goodsCategory3.getPid());
        GoodsCategory goodsCategory1 = goodsCategoryReadMapper.getByPrimaryKey(goodsCategory2.getPid());

        //插入品牌表
        GoodsBrand goodsBrandInsert = new GoodsBrand();
        goodsBrandInsert.setWebSite(applyBrandAddDTO.getWebSite());
        goodsBrandInsert.setBrandName(applyBrandAddDTO.getBrandName());
        goodsBrandInsert.setBrandDesc(applyBrandAddDTO.getBrandDesc());
        goodsBrandInsert.setImage(applyBrandAddDTO.getImage());
        goodsBrandInsert.setBrandInitial(StringUtil.GetFirstChar(applyBrandAddDTO.getBrandName()));
        goodsBrandInsert.setIsRecommend(GoodsConst.IS_BRAND_RECOMMEND_YES);
        goodsBrandInsert.setSort(GoodsConst.BRAND_SORT);
        goodsBrandInsert.setCreateAdminId(0);
        goodsBrandInsert.setCreateTime(new Date());
        goodsBrandInsert.setApplyVendorId(vendor.getVendorId());
        goodsBrandInsert.setApplyStoreId(vendor.getStoreId());
        goodsBrandInsert.setStoreName(vendor.getStore().getStoreName());
        goodsBrandInsert.setState(GoodsConst.BRAND_STATE_2);
        goodsBrandInsert.setGoodsCategoryId1(goodsCategory1.getCategoryId());
        goodsBrandInsert.setGoodsCategoryId2(goodsCategory2.getCategoryId());
        goodsBrandInsert.setGoodsCategoryId3(goodsCategory3.getCategoryId());
        goodsBrandInsert.setGoodsCategoryPath(goodsCategory1.getCategoryName() + "->" + goodsCategory2.getCategoryName() + "->" + goodsCategory3.getCategoryName());
        return this.saveGoodsBrand(goodsBrandInsert);
    }

    /**
     * 根据brandId删除商品品牌
     *
     * @param brandId brandId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteGoodsBrand(Integer brandId) {
        if (StringUtils.isEmpty(brandId)) {
            throw new MallException("请选择要删除的数据");
        }
        //删除商品分类与品牌定关系表
        GoodsCategoryBindBrandExample categoryBindBrandExample = new GoodsCategoryBindBrandExample();
        categoryBindBrandExample.setBrandId(brandId);
        goodsCategoryBindBrandWriteMapper.deleteByExample(categoryBindBrandExample);
        //删除品牌
        int count = goodsBrandWriteMapper.deleteByPrimaryKey(brandId);
        if (count == 0) {
            log.error("根据brandId：" + brandId + "删除商品品牌失败");
            throw new MallException("删除商品品牌失败,请重试");
        }
        return count;
    }

    /**
     * 根据categoryId删除商品品牌
     *
     * @param categoryId categoryId
     * @return
     */
    public Integer delGoodsBrandByCategoryId(Integer categoryId) {
        if (StringUtils.isEmpty(categoryId)) {
            throw new MallException("请选择要删除的数据");
        }
        GoodsBrandExample goodsBrandExample = new GoodsBrandExample();
        goodsBrandExample.setGoodsCategoryId3(categoryId);
        return goodsBrandWriteMapper.deleteByExample(goodsBrandExample);
    }

    /**
     * 根据brandId更新商品品牌
     *
     * @param goodsBrand
     * @return
     */
    public Integer updateGoodsBrand(GoodsBrand goodsBrand) {
        if (StringUtils.isEmpty(goodsBrand.getBrandId())) {
            throw new MallException("请选择要修改的数据");
        }
        int count = goodsBrandWriteMapper.updateByPrimaryKeySelective(goodsBrand);
        if (count == 0) {
            log.error("根据brandId：" + goodsBrand.getBrandId() + "更新商品品牌失败");
            throw new MallException("更新商品品牌失败,请重试");
        }
        return count;
    }


    /**
     * 根据brandId更新商品品牌
     *
     * @param goodsBrandUpdateDTO
     * @param adminId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer updateGoodsBrand(Integer adminId, GoodsBrandUpdateDTO goodsBrandUpdateDTO) throws Exception {
        //判断品牌名称是否重复
        GoodsBrandExample example = new GoodsBrandExample();
        example.setWebSite(goodsBrandUpdateDTO.getWebSite());
        example.setBrandName(goodsBrandUpdateDTO.getBrandName());
        example.setBrandIdNotEquals(goodsBrandUpdateDTO.getBrandId());
        List<GoodsBrand> list = goodsBrandReadMapper.listByExample(example);
        AssertUtil.isTrue(!CollectionUtils.isEmpty(list), "品牌名称已存在，请重新填写");

        //修改品牌表
        GoodsBrand goodsBrandUpdate = new GoodsBrand();
        PropertyUtils.copyProperties(goodsBrandUpdate, goodsBrandUpdateDTO);
        goodsBrandUpdate.setUpdateTime(new Date());
        goodsBrandUpdate.setUpdateAdminId(adminId);
        return this.updateGoodsBrand(goodsBrandUpdate);
    }

    /**
     * 根据brandId更新商户申请的品牌
     *
     * @param applyBrandUpdateDTO
     * @param vendor
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer updateSellersBrand(ApplyBrandUpdateDTO applyBrandUpdateDTO, Vendor vendor) {
        //判断品牌名称是否重复
        GoodsBrandExample example = new GoodsBrandExample();
        example.setBrandName(applyBrandUpdateDTO.getBrandName());
        example.setWebSite(applyBrandUpdateDTO.getWebSite());
        example.setBrandIdNotEquals(applyBrandUpdateDTO.getBrandId());
        example.setApplyStoreId(vendor.getStoreId());
        List<GoodsBrand> list = goodsBrandReadMapper.listByExample(example);
        AssertUtil.isTrue(!CollectionUtils.isEmpty(list), "品牌名称已存在，请重新填写");

        //查询已有品牌,判断是否是当前店铺的品牌
        GoodsBrand goodsBrand = getGoodsBrandByBrandId(applyBrandUpdateDTO.getBrandId());
        AssertUtil.isTrue(!goodsBrand.getApplyStoreId().equals(vendor.getStoreId()), "没有操作权限");

        //更新品牌表
        GoodsBrand goodsBrandUpdate = new GoodsBrand();
        goodsBrandUpdate.setBrandId(applyBrandUpdateDTO.getBrandId());
        goodsBrandUpdate.setWebSite(applyBrandUpdateDTO.getWebSite());
        goodsBrandUpdate.setBrandName(applyBrandUpdateDTO.getBrandName());
        goodsBrandUpdate.setBrandDesc(applyBrandUpdateDTO.getBrandDesc());
        goodsBrandUpdate.setImage(applyBrandUpdateDTO.getImage());
        goodsBrandUpdate.setBrandInitial(StringUtil.GetFirstChar(applyBrandUpdateDTO.getBrandName()));
        goodsBrandUpdate.setUpdateTime(new Date());
        goodsBrandUpdate.setIsRecommend(GoodsConst.IS_BRAND_RECOMMEND_YES);
        goodsBrandUpdate.setSort(GoodsConst.BRAND_SORT);
        goodsBrandUpdate.setFailReason("");
        goodsBrandUpdate.setState(GoodsConst.BRAND_STATE_2);
        if (!goodsBrand.getGoodsCategoryId3().equals(applyBrandUpdateDTO.getCategoryId())) {
            //查询分类信息
            GoodsCategory goodsCategory3 = goodsCategoryReadMapper.getByPrimaryKey(applyBrandUpdateDTO.getCategoryId());
            AssertUtil.notNull(goodsCategory3, "分类有误");
            GoodsCategory goodsCategory2 = goodsCategoryReadMapper.getByPrimaryKey(goodsCategory3.getPid());
            GoodsCategory goodsCategory1 = goodsCategoryReadMapper.getByPrimaryKey(goodsCategory2.getPid());

            goodsBrandUpdate.setGoodsCategoryId1(goodsCategory1.getCategoryId());
            goodsBrandUpdate.setGoodsCategoryId2(goodsCategory2.getCategoryId());
            goodsBrandUpdate.setGoodsCategoryId3(goodsCategory3.getCategoryId());
            goodsBrandUpdate.setGoodsCategoryPath(goodsCategory1.getCategoryName() + "->" + goodsCategory2.getCategoryName() + "->" + goodsCategory3.getCategoryName());
        }
        return this.updateGoodsBrand(goodsBrandUpdate);
    }

    /**
     * 根据brandId获取商品品牌详情
     *
     * @param brandId brandId
     * @return
     */
    public GoodsBrand getGoodsBrandByBrandId(Integer brandId) {
        return goodsBrandReadMapper.getByPrimaryKey(brandId);
    }

    /**
     * 根据条件获取商品品牌列表
     *
     * @param example 查询条件信息
     * @param pager   分页信息
     * @return
     */
    public List<GoodsBrand> getGoodsBrandList(GoodsBrandExample example, PagerInfo pager) {
        List<GoodsBrand> goodsBrandList;
        if (pager != null) {
            pager.setRowsCount(goodsBrandReadMapper.countByExample(example));
            goodsBrandList = goodsBrandReadMapper.listPageByExample(example, pager.getStart(), pager.getPageSize());
        } else {
            goodsBrandList = goodsBrandReadMapper.listByExample(example);
        }
        return goodsBrandList;
    }

    /**
     * 获取条件获取品牌数量
     *
     * @param example 查询条件信息
     * @return
     */
    public Integer getBrandCount(GoodsBrandExample example) {
        return goodsBrandReadMapper.countByExample(example);
    }

    /**
     * 根据条件获取商品品牌列表
     *
     * @param pager 分页信息
     * @return
     */
    public List<GoodsBrandFrontVO> getGoodsBrandListBy(PagerInfo pager,String webSite) {
        //根据品牌首字母分组查询
        GoodsBrandExample brandExample = new GoodsBrandExample();
        //最多26个英文字母
        List<String> list1 = goodsBrandReadMapper.groupListFieldsPageByExample(0, 26, webSite);
        pager.setRowsCount(list1.size());
        //分组查询
        List<String> list = goodsBrandReadMapper.groupListFieldsPageByExample(pager.getStart(), pager.getPageSize(), webSite);

        //响应
        List<GoodsBrandFrontVO> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (String brandInitial : list) {
                //循环一次为一个品牌首字母
                GoodsBrandFrontVO vo = new GoodsBrandFrontVO();
                vo.setBrandInitial(brandInitial);

                //按照品牌首字母重新查询品牌集合
                GoodsBrandExample example = new GoodsBrandExample();
                example.setBrandInitial(brandInitial);
                example.setWebSite(webSite);
                List<GoodsBrand> brandList = goodsBrandReadMapper.listByExample(example);

                List<GoodsBrandFrontVO.GoodsBrandInfo> infos = new ArrayList<>();
                brandList.forEach(goodsBrand -> {
                    GoodsBrandFrontVO.GoodsBrandInfo goodsBrandInfo = new GoodsBrandFrontVO.GoodsBrandInfo(goodsBrand);
                    infos.add(goodsBrandInfo);
                });
                vo.setGoodsBrandInfoList(infos);

                //vos集合添加数据
                vos.add(vo);
            }
        }
        return vos;
    }

    /**
     * 删除商品品牌
     *
     * @param brandIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteBrand(String brandIds) {
        //删除商品分类与品牌定关系表
        GoodsCategoryBindBrandExample bindBrandExample = new GoodsCategoryBindBrandExample();
        bindBrandExample.setBrandIdIn(brandIds);
        goodsCategoryBindBrandWriteMapper.deleteByExample(bindBrandExample);

        //删除商品品牌
        GoodsBrandExample example = new GoodsBrandExample();
        example.setBrandIdIn(brandIds);
        int count = goodsBrandWriteMapper.deleteByExample(example);
        if (count == 0) {
            throw new MallException("删除商品品牌失败,请重试");
        }
        return count;
    }
}