package com.gree.mall.manager.logic.material.base;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.material.base.MaterialCategoryTree;
import com.gree.mall.manager.bean.material.base.MaterialCategoryVO;
import com.gree.mall.manager.commonmapper.MaterialMapper;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.WebsitGoodsCategory;
import com.gree.mall.manager.plus.service.WebsitGoodsCategoryService;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class MaterialCategoryLogic {

    private final CommonLogic commonLogic;
    private final MaterialMapper materialMapper;
    private final WebsitGoodsCategoryService websitGoodsCategoryService;

    public IPage<MaterialCategoryVO> page(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        FieldUtils.materialParam(zfireParamBean, MaterialCategoryVO.class, adminUser);
        return materialMapper.materialCategoryPage(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean);
    }

    public void add(WebsitGoodsCategory category) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (Objects.isNull(adminUser.getAdminCompanyWechat())) {
           throw new RemoteServiceException("平台账号禁止操作");
        }

        String companyWechatId = adminUser.getAdminCompanyWechat().getCompanyWechatId();

        if (Objects.isNull(category.getCategoryLevel())) {
            throw new RemoteServiceException("级别不能为空");
        }

        if (category.getCategoryLevel() == 1) {
            Integer count = websitGoodsCategoryService.lambdaQuery()
                    .eq(WebsitGoodsCategory::getCompanyWechatId, companyWechatId)
                    .eq(WebsitGoodsCategory::getParentCategoryId, "0")
                    .eq(WebsitGoodsCategory::getCategoryName, category.getCategoryName())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException( "大类名称: \"" + category.getCategoryName() + "\"已存在");
            }
            category.setParentCategoryId("0");
        }

        if (category.getCategoryLevel() == 2) {
            if (StringUtils.isBlank(category.getParentCategoryId())) {
                throw new RemoteServiceException("所属请选择大类");
            }

            WebsitGoodsCategory goodsCategory = websitGoodsCategoryService.getById(category.getParentCategoryId());
            category.setParentCategoryName(goodsCategory.getCategoryName());

            Integer count = websitGoodsCategoryService.lambdaQuery()
                    .eq(WebsitGoodsCategory::getCompanyWechatId, companyWechatId)
                    .eq(WebsitGoodsCategory::getParentCategoryId, category.getParentCategoryId())
                    .eq(WebsitGoodsCategory::getCategoryName, category.getCategoryName())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException( "小类名称: \"" + category.getCategoryName() + "\"已存在");
            }
        }

        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            category.setCompanyWechatId(adminUser.getAdminCompanyWechat().getCompanyWechatId());
            category.setCompanyWechatName(adminUser.getAdminCompanyWechat().getCompanyName());
        }
        category.insert();
    }

    /**
     * 商品分类树
     * @param state
     */
    public List<MaterialCategoryTree> materialCategoryTree(String state) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String companyId = Objects.isNull(adminUser.getAdminCompanyWechat()) ? "" : adminUser.getAdminCompanyWechat().getCompanyWechatId();
        List<WebsitGoodsCategory> list = websitGoodsCategoryService.lambdaQuery()
                .eq(WebsitGoodsCategory::getCompanyWechatId, companyId)
                .eq(StringUtils.isNotBlank(state), WebsitGoodsCategory::getStatus, state)
                .list();

        List<MaterialCategoryTree> trees = BeanUtil.copyToList(list, MaterialCategoryTree.class);

        List<MaterialCategoryTree> parentList = trees.stream().filter(x -> x.getParentCategoryId().equals("0")).collect(Collectors.toList());
        for(MaterialCategoryTree bean : parentList){
            bean.setChild(this.treeModule(trees, bean.getCategoryId()));
        }
        return parentList;
    }

    /**
     * 递归组装数据
     * @param list
     * @param parentId
     * @return
     */
    private List<MaterialCategoryTree> treeModule(List<MaterialCategoryTree> list, String parentId) {
        //最父级资源树
        if (parentId == null) {
            return new ArrayList<>();
        }
        List<MaterialCategoryTree> collect = list.stream()
                .filter(e -> e.getParentCategoryId().equals(parentId)).collect(Collectors.toList());
        if (collect.size() == 0) {
            return null;
        }
        for (MaterialCategoryTree bean : collect) {
            bean.setChild(this.treeModule(list, bean.getCategoryId()));
        }
        return collect;
    }

    public void update(WebsitGoodsCategory category) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        String companyWechatId = null;
        if (Objects.nonNull(adminUser.getAdminCompanyWechat())) {
            companyWechatId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }

        if (Objects.isNull(category.getCategoryLevel())) {
            throw new RemoteServiceException("级别不能为空");
        }

        if (category.getCategoryLevel() == 1) {
            Integer count = websitGoodsCategoryService.lambdaQuery()
                    .eq(WebsitGoodsCategory::getCompanyWechatId, companyWechatId)
                    .eq(WebsitGoodsCategory::getParentCategoryId, "0")
                    .eq(WebsitGoodsCategory::getCategoryName, category.getCategoryName())
                    .ne(WebsitGoodsCategory::getCategoryId, category.getCategoryId())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException( "大类名称: \"" + category.getCategoryName() + "\"已存在");
            }
            category.setParentCategoryId("0");
        }

        if (category.getCategoryLevel() == 2) {
            if (StringUtils.isBlank(category.getParentCategoryId())) {
                throw new RemoteServiceException("所属请选择大类");
            }

            Integer count = websitGoodsCategoryService.lambdaQuery()
                    .eq(WebsitGoodsCategory::getCompanyWechatId, companyWechatId)
                    .eq(WebsitGoodsCategory::getParentCategoryId, category.getParentCategoryId())
                    .eq(WebsitGoodsCategory::getCategoryName, category.getCategoryName())
                    .ne(WebsitGoodsCategory::getCategoryId, category.getCategoryId())
                    .count();
            if (count > 0) {
                throw new RemoteServiceException( "小类名称: \"" + category.getCategoryName() + "\"已存在");
            }
        }

        WebsitGoodsCategory oldCategory = websitGoodsCategoryService.getById(category.getCategoryId());
        WebsitGoodsCategory websitGoodsCategory = new WebsitGoodsCategory();
        websitGoodsCategory.setCategoryId(category.getCategoryId())
                .setCompanyWechatId(oldCategory.getCompanyWechatId())
                .setCompanyWechatName(oldCategory.getCompanyWechatName())
                .setCategoryName(category.getCategoryName())
                .setRemark(category.getRemark())
                .setSort(category.getSort())
                .setStatus(category.getStatus());
        websitGoodsCategory.updateById();
    }
}
