package com.gree.mall.manager.logic.goods;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.goods.GoodsCategoryBean;
import com.gree.mall.manager.commonmapper.CustomGoodsCategoryMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import net.bytebuddy.asm.Advice;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class GoodsCategoryLogic {

    @Resource
    CustomGoodsCategoryMapper customGoodsCategoryMapper;
    @Resource
    GoodsCategoryService goodsCategoryService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    GoodsMaterialService goodsMaterialService;
    @Autowired
    GoodsSpecService goodsSpecService;
    @Autowired
    EsGoodsService esGoodsService;
    @Autowired
    CommonLogic commonLogic;

    @Autowired
    GoodsCategoryItemService goodsCategoryItemService;

    /**
     * 分类管理列表
     *
     * @param level
     * @param status
     * @return
     */
    public List<GoodsCategoryBean> list(Integer type,Integer level, String name, Boolean status, HttpServletRequest request) {
        //获取当前登录企业微信id
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();
        if(type == null){
            type = 1;
        }
        return customGoodsCategoryMapper.list(type,level, status, name, companyWechatIds);
    }

    /**
     * 新增分类
     *
     * @param goodsCategoryBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsCategoryBean goodsCategoryBean, HttpServletRequest request) {
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
//        if (StringUtils.isBlank(adminUser.getCompanyWechatId())) {
//            throw new RemoteServiceException("非租户账号不可操作当前信息");
//        }
        GoodsCategoryBean goodsCategory = goodsCategoryBean;
        if(!CollectionUtils.isEmpty(goodsCategoryBean.getChildren())){
            goodsCategory = goodsCategoryBean.getChildren().get(0);
        }
        if(goodsCategory.getType() == null){
            goodsCategory.setType(1);
        }
        //检查名称不可重复
        Integer count = goodsCategoryService.lambdaQuery()
                .ne(StringUtils.isNotBlank(goodsCategory.getCategoryId()), GoodsCategory::getCategoryId, goodsCategory.getCategoryId())
                .eq(GoodsCategory::getType,goodsCategory.getType())
                .eq(GoodsCategory::getName, goodsCategory.getName())
                .eq(GoodsCategory::getCompanyWechatId, adminUser.getCompanyWechatId()).count();
        if(count > 0){
            throw new RemoteServiceException("分类名称【"+goodsCategory.getName()+"】已存在");
        }
        //最多只能2级
        if(StringUtils.isNotBlank(goodsCategory.getParentId())) {
            goodsCategory.setLevel(2);
        }else{
            goodsCategory.setLevel(1);
        }
        goodsCategory.setCreateTime(new Date());
        goodsCategory.setCompanyWechatId(adminUser.getCompanyWechatId());
        goodsCategory.setCompanyName(adminUser.getCompanyName());
        //goodsCategory.setCreateTime(new Date());
        goodsCategory.insert();

    }

    /**
     * 修改分类
     *
     * @param goodsCategory
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(GoodsCategory goodsCategory) {
        GoodsCategory old = goodsCategoryService.getById(goodsCategory.getCategoryId());
        //检查名称不可重复
        Integer count = goodsCategoryService.lambdaQuery()
                .ne(GoodsCategory::getCategoryId, goodsCategory.getCategoryId())
                .eq(GoodsCategory::getType,old.getType())
                .eq(GoodsCategory::getName, goodsCategory.getName())
                .eq(GoodsCategory::getCompanyWechatId, old.getCompanyWechatId()).count();
        if(count > 0){
            throw new RemoteServiceException("分类名称【"+goodsCategory.getName()+"】已存在");
        }
        goodsCategoryService.updateById(goodsCategory);
        //如果有子集，覆盖子集的一些参数
//        goodsCategoryService.lambdaUpdate()
//                .set(GoodsCategory::getIsPromotionDiscount,goodsCategory.getIsPromotionDiscount())
//                .eq(GoodsCategory::getParentId,goodsCategory.getCategoryId()).update();
    }



    /**
     * 删除分类
     *
     * @param categoryId
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String categoryId) {
//        goodsCategoryService.removeById(categoryId);
        //查询分类和子类
        List<GoodsCategory> list = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getCategoryId, categoryId)
                .or()
                .eq(GoodsCategory::getParentId, categoryId).list();
        List<String> goodsCategoryIds = list.stream().map(GoodsCategory::getCategoryId).collect(Collectors.toList());
        Integer count = goodsService.lambdaQuery().in(Goods::getCategoryId, goodsCategoryIds).count();
        if(count > 0){
            throw new RemoteServiceException("分类已被商品使用，不可删除");
        }
        Integer count1 = goodsMaterialService.lambdaQuery().in(GoodsMaterial::getMainId, goodsCategoryIds).count();
        if(count1 > 0){
            throw new RemoteServiceException("服务分类已被物料使用，不可删除");
        }
        Integer count2 = goodsSpecService.lambdaQuery().in(GoodsSpec::getMainId, goodsCategoryIds).count();
        if(count2 > 0){
            throw new RemoteServiceException("服务分类已被商品规格使用，不可删除");
        }
        Integer count3 = esGoodsService.lambdaQuery().in(EsGoods::getCategoryId, goodsCategoryIds).count();
        if(count3 > 0){
            throw new RemoteServiceException("分类已被商品使用，不可删除");
        }


        // 删除子类别
        goodsCategoryService.lambdaUpdate()
                .eq(GoodsCategory::getCategoryId, categoryId)
                .or()
                .eq(GoodsCategory::getParentId, categoryId)
                .remove();

        goodsCategoryItemService.lambdaUpdate()
                .eq(GoodsCategoryItem::getServiceCategoryId, categoryId)
                .or()
                .eq(GoodsCategoryItem::getMainId, categoryId)
                .or()
                .eq(GoodsCategoryItem::getSmallId, categoryId).remove();


    }

    /**
     * 分类详情
     */
    public GoodsCategory detail(String goodsCategoryId) {
        return goodsCategoryService.getById(goodsCategoryId);
    }

}
