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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.gree.mall.miniapp.bean.goods.GoodsCategoryBean;
import com.gree.mall.miniapp.bean.order.GoodsCategoryItemBean;
import com.gree.mall.miniapp.bean.order.OrderCategoryItem;
import com.gree.mall.miniapp.bean.user.CurrentCompanyWechat;
import com.gree.mall.miniapp.commonmapper.CustomGoodsCategoryMapper;
import com.gree.mall.miniapp.logic.common.CommonLogic;
import com.gree.mall.miniapp.plus.entity.GoodsCategory;
import com.gree.mall.miniapp.plus.entity.GoodsCategoryItem;
import com.gree.mall.miniapp.plus.service.GoodsCategoryItemService;
import com.gree.mall.miniapp.plus.service.GoodsCategoryService;
import com.gree.mall.miniapp.utils.StringUtil;
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 javax.swing.plaf.IconUIResource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class GoodsCategoryLogic {

    @Resource
    CustomGoodsCategoryMapper customGoodsCategoryMapper;
    @Resource
    GoodsCategoryService goodsCategoryService;

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    GoodsCategoryItemService goodsCategoryItemService;

    /**
     * 分类管理列表
     * @param level
     * @param status
     * @return
     */
    public List<GoodsCategoryBean> list(Integer level, Boolean status) {
        return customGoodsCategoryMapper.list(level, status);
    }

    /**
     * 新增分类
     * @param goodsCategoryBean
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsCategoryBean goodsCategoryBean) {
        Date createDate = new Date();
        if (goodsCategoryBean.getChildren() != null) {
            List<GoodsCategory> goodsCategoryList = goodsCategoryBean.getChildren()
                    .stream()
                    .map(c -> c.setCreateTime(createDate))
                    .collect(Collectors.toList());
            goodsCategoryService.saveBatch(goodsCategoryList);
        } else {
            goodsCategoryBean.setCreateTime(createDate);
            goodsCategoryService.save(goodsCategoryBean);
        }
    }

    /**
     * 修改分类
     * @param goodsCategory
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(GoodsCategory goodsCategory) {
        goodsCategoryService.updateById(goodsCategory);
    }

//    /**
//     * 删除分类
//     * @param categoryId
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public void delete(String categoryId) {
//        goodsCategoryService.lambdaUpdate()
//                .set(GoodsCategory::getDel, true)
//                .eq(GoodsCategory::getCategoryId, categoryId)
//                .or()
//                .eq(GoodsCategory::getParentId, categoryId)
//                .update();
//    }


    public GoodsCategory queryById(String catagoryId){
        return goodsCategoryService.getById(catagoryId);
    }


    public List<GoodsCategoryBean> listGoodsCategory(HttpServletRequest request) {

        //获取当前登录企业微信id
        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat(request);
        String companyWechatIds = currentCompanyWechat.getCompanyWechatId();

        List<GoodsCategoryItem> goodsCategoryItemList = goodsCategoryItemService.lambdaQuery()
                .eq(GoodsCategoryItem::getCompanyWechatId, companyWechatIds)
                .eq(GoodsCategoryItem::getStatus, "ON")
                .eq(GoodsCategoryItem::getTypeAttribute, "SPEC")
                .select(GoodsCategoryItem::getMainId, GoodsCategoryItem::getSmallId, GoodsCategoryItem::getServiceCategoryId)
                .list();

        if (CollectionUtils.isEmpty(goodsCategoryItemList))
            return new ArrayList<>();


        List<GoodsCategory> list = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getStatus, true)
                .eq(GoodsCategory::getLevel, 1)
                .eq(GoodsCategory::getType, 2)
                .in(GoodsCategory::getCategoryId, goodsCategoryItemList.stream().map(GoodsCategoryItem::getMainId).collect(Collectors.toList()))
                .in(!StringUtil.isEmpty(companyWechatIds),GoodsCategory::getCompanyWechatId, companyWechatIds)
                .orderByAsc(GoodsCategory::getSortNum)
                .list();

        List<GoodsCategoryBean> goodsCategoryBeans = new ArrayList<>();


        for (GoodsCategory goodsCategory : list) {
            GoodsCategoryBean goodsCategoryBean = BeanUtil.toBean(goodsCategory, GoodsCategoryBean.class);

            List<GoodsCategory> children = goodsCategoryService.lambdaQuery()
                    .eq(GoodsCategory::getParentId, goodsCategory.getCategoryId())
                    .in(GoodsCategory::getCategoryId, goodsCategoryItemList.stream().map(GoodsCategoryItem::getSmallId).collect(Collectors.toList()))
                    .orderByAsc(GoodsCategory::getSortNum)
                    .list();
            List<GoodsCategoryBean> childrenBean = new ArrayList<>();
            for (GoodsCategory child : children) {
                GoodsCategoryBean childOne = BeanUtil.toBean(child, GoodsCategoryBean.class);

                List<GoodsCategory> childrenTwo = goodsCategoryService.lambdaQuery()
                        .eq(GoodsCategory::getParentId, child.getCategoryId())
                        .in(GoodsCategory::getCategoryId, goodsCategoryItemList.stream().map(GoodsCategoryItem::getServiceCategoryId).collect(Collectors.toList()))
                        .orderByAsc(GoodsCategory::getSortNum)
                        .list();

                if (CollectionUtils.isEmpty(childrenTwo))
                    continue;


                childrenBean.add(childOne);
            }

            if (CollectionUtils.isEmpty(childrenBean))
                continue;

            goodsCategoryBean.setChildren(childrenBean);

            goodsCategoryBeans.add(goodsCategoryBean);

        }

        return goodsCategoryBeans;
    }

    public List<GoodsCategoryItemBean> listCategoryItem(String mainId) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        List<GoodsCategory> list = goodsCategoryService.lambdaQuery()
                .eq(GoodsCategory::getParentId, mainId)
                .eq(GoodsCategory::getType, 3)
                .orderByAsc(GoodsCategory::getSortNum)
                .list();

        List<GoodsCategoryItemBean> goodsCategoryItemBeans = new ArrayList<>();
        for (GoodsCategory goodsCategory : list) {
            GoodsCategoryItemBean goodsCategoryItemBean = BeanUtil.toBean(goodsCategory, GoodsCategoryItemBean.class);

            List<GoodsCategoryItem> goodsCategoryItemList = goodsCategoryItemService.lambdaQuery()
                    .eq(GoodsCategoryItem::getServiceCategoryId, goodsCategory.getCategoryId())
                    .eq(GoodsCategoryItem::getCompanyWechatId, currentCompanyWechat.getCompanyWechatId())
                    .eq(GoodsCategoryItem::getStatus,"ON")
                    .list();
            if (CollectionUtils.isEmpty(goodsCategoryItemList))
                continue;


            goodsCategoryItemBean.setGoodsCategoryItems(goodsCategoryItemList);
            goodsCategoryItemBeans.add(goodsCategoryItemBean);
        }

        return goodsCategoryItemBeans;
    }


    /**
     * 计算价格
     * ids 所有型号属性
     * */
    public BigDecimal price(List<String> ids) {

        List<GoodsCategoryItem> list = goodsCategoryItemService.lambdaQuery().in(GoodsCategoryItem::getId, ids).list();

        BigDecimal bigDecimal = list.stream().map(GoodsCategoryItem::getPrice).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        if(bigDecimal.doubleValue() < 0){
            return BigDecimal.ZERO;
        }
        return bigDecimal;
    }

    public OrderCategoryItem orderCategoryItem(List<String> ids) {

        CurrentCompanyWechat currentCompanyWechat = commonLogic.getCurrentCompanyWechat();

        List<GoodsCategoryItem> list = goodsCategoryItemService.lambdaQuery().in(GoodsCategoryItem::getId, ids).list();


        GoodsCategory goodsCategory = goodsCategoryService.getById(list.get(0).getSmallId());

        OrderCategoryItem orderCategoryItem = BeanUtil.toBean(goodsCategory, OrderCategoryItem.class);

        orderCategoryItem.setGoodsCategoryItemList(list);

        List<String> itemIds = new ArrayList<>();

        for (GoodsCategoryItem goodsCategoryItem : list) {
            if (goodsCategoryItem.getTypeAttribute().equals("SPEC"))
                orderCategoryItem.setId(goodsCategoryItem.getId());
            else
                itemIds.add(goodsCategoryItem.getId());
        }

        orderCategoryItem.setItemIds(itemIds);


        BigDecimal price = this.price(ids);
        orderCategoryItem.setPayAmount(price);

        orderCategoryItem.setYjhxDkFlag(currentCompanyWechat.getYjhxDkFlag());
        return orderCategoryItem;
    }

    public BigDecimal getMaxPrice() {

        GoodsCategoryItem goodsCategoryItem = goodsCategoryItemService.lambdaQuery()
                .eq(GoodsCategoryItem::getStatus, "ON")
                .eq(GoodsCategoryItem::getTypeAttribute, "SPEC")
                .orderByDesc(GoodsCategoryItem::getMaxPrice).last("limit 1").one();

        if (goodsCategoryItem == null)
            return Convert.toBigDecimal("0");

        return goodsCategoryItem.getMaxPrice();

    }
}
