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

import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.activity.*;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.carouselMap.CarouselMapVO;
import com.gree.mall.manager.bean.goods.PromotionGroupListVO;
import com.gree.mall.manager.bean.order.OrderShareVO;
import com.gree.mall.manager.commonmapper.CommonPageV2Mapper;
import com.gree.mall.manager.commonmapper.PromotionMapper;
import com.gree.mall.manager.enums.OrderShareStatusEnum;
import com.gree.mall.manager.enums.OrderStatusEnum;
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 com.gree.mall.manager.utils.CommonUtils;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Service
public class PromotionGroupLogic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    PromotionGroupService promotionGroupService;
    @Autowired
    PromotionGroupSpecService promotionGroupSpecService;
    @Autowired
    PromotionGroupSpecUserService promotionGroupSpecUserService;
    @Autowired
    PromotionGroupUserService promotionGroupUserService;
    @Autowired
    OrderInfoService orderInfoService;
    @Autowired
    OrderDetailService orderDetailService;
    @Autowired
    OrderShareService orderShareService;
    @Autowired
    PromotionMapper promotionMapper;
    @Autowired
    UserService userService;
    @Autowired
    GoodsVisitService goodsVisitService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    UserVisitService userVisitService;
    @Autowired
    CommonPageV2Mapper commonPageV2Mapper;

    /**
     * 团购分类统计
     */
    public Map<String,Integer> count(HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        //已结束
        int count = promotionGroupService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()),PromotionGroup::getCompanyWechatId,adminUser.getCompanyWechatIds())
                .eq(PromotionGroup::getStatus,false).count();
        //进行中
        int count2 = promotionGroupService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()),PromotionGroup::getCompanyWechatId,adminUser.getCompanyWechatIds())
                .eq(PromotionGroup::getStatus,true).count();
        Map<String,Integer> map = new HashMap<>();
        map.put("all",count+count2);
        map.put("jxz",count2);
        map.put("yjs",count);
        return map;
    }
    /**
     * 团购活动列表
     * @param status
     * @param pageNo
     * @param pageSize
     * @return
     */
    public IPage<PromotionGroupList> list(Boolean status, Integer pageNo, Integer pageSize, HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        IPage page = promotionGroupService.lambdaQuery()
                .eq(status != null, PromotionGroup::getStatus, status)
                .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()),PromotionGroup::getCompanyWechatId,adminUser.getCompanyWechatIds())
                .orderByDesc(PromotionGroup::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
        //组装数据
        List<PromotionGroupList> list = new ArrayList<>();
        for (Object o : page.getRecords()) {
            PromotionGroup promotionGroup = (PromotionGroup) o;
            PromotionGroupList promotionGroupList = new PromotionGroupList();
            BeanUtils.copyProperties(promotionGroup,promotionGroupList);
            //参与商品数量
            Integer count = promotionGroupSpecService.lambdaQuery().eq(PromotionGroupSpec::getPromotionGroupId, promotionGroup.getPromotionGroupId()).count();
            promotionGroupList.setGoodsNum(count);
            //订单数量
            Integer orderNum = orderInfoService.lambdaQuery()
                    .notIn(OrderInfo::getOrderStatus,Arrays.asList(OrderStatusEnum.CLOSE.toString(),OrderStatusEnum.TIMEOUT.toString()))
                    .eq(OrderInfo::getPromotionGroupId, promotionGroup.getPromotionGroupId()).count();
            promotionGroupList.setOrderNum(orderNum);
            //订单台数
            Integer orderDetilNum = promotionMapper.queryTotalGoodsNum(promotionGroup.getPromotionGroupId(),null);
            promotionGroupList.setOrderDetailNum(orderDetilNum);
            //订单总金额
            BigDecimal totalAmount = promotionMapper.queryOrderTotalAmount(promotionGroup.getPromotionGroupId());
            promotionGroupList.setOrderTotalAmount(totalAmount);
            //团长分佣总额
            BigDecimal totalOrderShareAmount = promotionMapper.queryTotalShareAmount(null,promotionGroup.getPromotionGroupId(),null);
            promotionGroupList.setShareTotalAmount(totalOrderShareAmount);
            list.add(promotionGroupList);
        }
        page.setRecords(list);
        return page;
    }


    /**
     * 团购详情
     */
    public PromotionGroupBean detail(String promotionGroupId){
        PromotionGroup promotionGroup = promotionGroupService.getById(promotionGroupId);
        PromotionGroupBean bean = new PromotionGroupBean();
        BeanUtils.copyProperties(promotionGroup,bean);
        //商品
        List<PromotionGoods> goods = new ArrayList<>();
        //商品规格
        List<PromotionGroupSpec> specList = promotionGroupSpecService.lambdaQuery()
                .eq(PromotionGroupSpec::getPromotionGroupId, promotionGroupId).list();

        Map<String,List<PromotionGroupSpec>> map = new LinkedHashMap<>();
        for (PromotionGroupSpec promotionGroupSpec : specList) {
            String goodsId = promotionGroupSpec.getGoodsId();
            List<PromotionGroupSpec> promotionGroupSpecs = map.get(goodsId);
            if(promotionGroupSpecs == null){
                promotionGroupSpecs = new ArrayList<>();
            }
            promotionGroupSpecs.add(promotionGroupSpec);
            map.put(goodsId,promotionGroupSpecs);
        }
        for(String goodsId : map.keySet()){
            PromotionGroupSpec promotionGroupSpec = map.get(goodsId).get(0);
            PromotionGoods promotionGoods = new PromotionGoods();
            promotionGoods.setGoodsId(promotionGroupSpec.getGoodsId());
            promotionGoods.setGoodsImgSrc(promotionGroupSpec.getGoodsImgSrc());
            promotionGoods.setGoodsName(promotionGroupSpec.getGoodsName());
            promotionGoods.setSpecs(map.get(goodsId));
            promotionGoods.setSortNum(promotionGroupSpec.getSortNum());
            goods.add(promotionGoods);
        }
        bean.setGoods(goods);
        //查询活动团长列表
        List<PromotionGroupUser> list = promotionGroupUserService.lambdaQuery().eq(PromotionGroupUser::getPromotionGroupId, promotionGroupId).list();
        bean.setPromotionGroupUsers(list);
        return bean;
    }


    /**
     * 新增团购活动
     */
    @Transactional
    public String add(PromotionGroupBean promotionGroupBean,HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        //活动团长
        List<PromotionGroupUser> promotionGroupUsers = promotionGroupBean.getPromotionGroupUsers();
        List<String> userIds = promotionGroupUsers.stream().map(PromotionGroupUser::getUserId).collect(Collectors.toList());
        //1.保存团购活动
        promotionGroupBean.setCompanyWechatId(adminUser.getCompanyWechatId());
        promotionGroupBean.setCompanyName(adminUser.getCompanyName());
        promotionGroupBean.setCreateTime(new Date());
        promotionGroupService.save(promotionGroupBean);
        String promotionGroupId = promotionGroupBean.getPromotionGroupId();

        //2.团购商品集合
        List<PromotionGoods> goods = promotionGroupBean.getGoods();
        List<String> goodsIds = goods.stream().map(PromotionGoods::getGoodsId).collect(Collectors.toList());
        Integer count = promotionGroupSpecService.lambdaQuery().in(PromotionGroupSpec::getGoodsId, goodsIds).count();
        if(count > 0){
            throw new RemoteServiceException("存在商品已被添加到其他活动");
        }
        for(PromotionGoods pGoods : goods){
            for (PromotionGroupSpec promotionGroupSpec : pGoods.getSpecs()) {
                promotionGroupSpec.setStartTime(promotionGroupBean.getStartTime());
                promotionGroupSpec.setEndTime(promotionGroupBean.getEndTime());
                promotionGroupSpec.setCompanyWechatId(promotionGroupBean.getCompanyWechatId());
                promotionGroupSpec.setCompanyName(promotionGroupBean.getCompanyName());
                promotionGroupSpec.setSortNum(pGoods.getSortNum());
                promotionGroupSpec.setCreateTime(new Date());
            }
        }

        //3 清空活动团长
        promotionGroupUserService.lambdaUpdate().eq(PromotionGroupUser::getPromotionGroupId,promotionGroupId).remove();

        //新增团购活动规格和初始化团长
        this.addSpecUser(adminUser,promotionGroupBean,goods,userIds);

        return promotionGroupBean.getPromotionGroupId();
    }

    /**
     *  修改团购活动
     */
    @Transactional
    public void update(HttpServletRequest request, PromotionGroupBean promotionGroupBean){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);

        String promotionGroupId = promotionGroupBean.getPromotionGroupId();
        List<String> userIds = promotionGroupBean.getPromotionGroupUsers().stream().map(PromotionGroupUser::getUserId).collect(Collectors.toList());
        //1.修改团购活动
        promotionGroupService.updateById(promotionGroupBean);
        //此次提交的所有活动规格id
        List<String> promotionGroupSpecIds = new ArrayList<>();
        //此次提交的所有活动商品id
        List<String> goodsId = new ArrayList<>();
        //d需要新增的商品
        List<PromotionGoods> promotionGoodsAdd = new ArrayList<>();
        //修改旧的商品规格
        for (PromotionGoods promotionGoods : promotionGroupBean.getGoods()) {
            for (PromotionGroupSpec promotionGroupSpec : promotionGoods.getSpecs()) {

                promotionGroupSpec.setStartTime(promotionGroupBean.getStartTime());
                promotionGroupSpec.setEndTime(promotionGroupBean.getEndTime());
                promotionGroupSpec.setSortNum(promotionGoods.getSortNum());
                if(StringUtils.isNotBlank(promotionGroupSpec.getPromotionGroupSpecId())) {
                    promotionGroupSpecService.updateById(promotionGroupSpec);

                    promotionGroupSpecIds.add(promotionGroupSpec.getPromotionGroupSpecId());

                    goodsId.add(promotionGroupSpec.getGoodsId());
                }else{
                    promotionGoodsAdd.add(promotionGoods);
                }
            }
        }
        promotionGoodsAdd = promotionGoodsAdd.stream().filter(distinctByKey(PromotionGoods::getGoodsId)).collect(Collectors.toList());

        List<String> goodsIds = promotionGoodsAdd.stream().map(PromotionGoods::getGoodsId).collect(Collectors.toList());
        if(goodsIds.size() > 0) {
            Integer count = promotionGroupSpecService.lambdaQuery().in(PromotionGroupSpec::getGoodsId, goodsIds)
                    .ne(PromotionGroupSpec::getPromotionGroupId,promotionGroupId).count();
            if (count > 0) {
                throw new RemoteServiceException("存在商品已被添加到其他活动");
            }
        }

        //记录需要还原的商品(去除活动标志)
        List<PromotionGroupSpec> goodsIdListFalse = promotionGroupSpecService.lambdaQuery()
                .select(PromotionGroupSpec::getGoodsId)
                .notIn(CollectionUtils.isNotEmpty(promotionGroupSpecIds),PromotionGroupSpec::getPromotionGroupSpecId, promotionGroupSpecIds)
                .eq(PromotionGroupSpec::getPromotionGroupId,promotionGroupId)
                .list();

        //删除此次提交的活动规格之外的规格AAAA
        promotionGroupSpecService.lambdaUpdate()
                .notIn(CollectionUtils.isNotEmpty(promotionGroupSpecIds),PromotionGroupSpec::getPromotionGroupSpecId, promotionGroupSpecIds)
                .eq(PromotionGroupSpec::getPromotionGroupId, promotionGroupId)
                .remove();

        //删除此次活动规格的团长
        promotionGroupSpecUserService.lambdaUpdate()
                .eq(PromotionGroupSpecUser::getPromotionGroupId,promotionGroupId)
                .remove();

        List<String> goodsIdsFalse = goodsIdListFalse.stream().map(PromotionGroupSpec::getGoodsId).collect(Collectors.toList());
        if(goodsIdsFalse.size() > 0) {
            goodsService.lambdaUpdate()
                    .set(Goods::getPromotionGroup, false)
                    .in(Goods::getGoodsId, goodsIdsFalse).update();
        }

        //清空团购活动团长
        promotionGroupUserService.lambdaUpdate().eq(PromotionGroupUser::getPromotionGroupId,promotionGroupId).remove();

        //5.新增新的商品规格和初始化团长
        this.addSpecUser(adminUser,promotionGroupBean,promotionGoodsAdd,userIds);
    }

    /**
     * 关闭活动
     */
    public void close(){
        //查询过期了的活动
        List<PromotionGroup> list = promotionGroupService.lambdaQuery()
                .le(PromotionGroup::getEndTime, new Date())
                //.ge(PromotionGroup::getStartTime, new Date())
                .eq(PromotionGroup::getStatus, true)
                .list();

        List<String> promotionGroupIds = list.stream().map(PromotionGroup::getPromotionGroupId).collect(Collectors.toList());

        for(String promotionGroupId : promotionGroupIds) {
            this.updateStatus(promotionGroupId,false);
        }

    }

    /**
     * 修改活动状态
     */
    @Transactional
    public void updateStatus(String promotionGroupId,Boolean status){
        promotionGroupService.lambdaUpdate()
                .set(PromotionGroup::getStatus,status)
                .eq(PromotionGroup::getPromotionGroupId,promotionGroupId)
                .update();
        //如果是关闭活动，则将里面的商品都剔除团购商品并下架
        if(!status){
            List<PromotionGroupSpec> list = promotionGroupSpecService.lambdaQuery().eq(PromotionGroupSpec::getPromotionGroupId, promotionGroupId).list();
            List<String> goodsIds = list.stream().map(PromotionGroupSpec::getGoodsId).collect(Collectors.toList());
//            goodsService.lambdaUpdate()
//                    .set(Goods::getPromotionGroup,false)
//                    .set(Goods::getStatus,false)
//                    .in(Goods::getGoodsId,goodsIds).update();
            goodsService.lambdaUpdate().in(Goods::getGoodsId,goodsIds).remove();

        }
    }
    

    private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    /**
     * 新增新的商品规格和初始化团长
     */
    private void addSpecUser(AdminUserCom adminUser,PromotionGroup promotionGroup,List<PromotionGoods> goods,List<String> userIds){
        String promotionGroupId = promotionGroup.getPromotionGroupId();
        //团购商品规格集合
        List<PromotionGroupSpec> promotionGroupSpecs = new ArrayList<>();
        List<String> promotionGroupSpecIds = new ArrayList<>();
        List<String> goodsIds = new ArrayList<>();
        for (PromotionGoods good : goods) {
            for (PromotionGroupSpec promotionGroupSpec : good.getSpecs()) {
                promotionGroupSpec.setPromotionGroupSpecId(IdWorker.getIdStr());
                promotionGroupSpec.setGoodsId(good.getGoodsId());
                promotionGroupSpec.setGoodsName(good.getGoodsName());
                promotionGroupSpec.setGoodsImgSrc(good.getGoodsImgSrc());
                promotionGroupSpec.setPromotionGroupId(promotionGroupId);
                promotionGroupSpec.setCompanyWechatId(adminUser.getCompanyWechatId());
                promotionGroupSpec.setCompanyName(adminUser.getCompanyName());
                promotionGroupSpecs.add(promotionGroupSpec);

                promotionGroupSpecIds.add(promotionGroupSpec.getPromotionGroupSpecId());
                goodsIds.add(good.getGoodsId());
            }
        }
        //2.保存购商品规格
        promotionGroupSpecService.saveBatch(promotionGroupSpecs);
        //3.初始化团长
        if(CollectionUtils.isNotEmpty(userIds)){

            List<User> users = userService.lambdaQuery().in(User::getUserId, userIds).eq(User::getPromotionGroupLeader, true).list();
            List<PromotionGroupSpec> list1 = promotionGroupSpecService.lambdaQuery().eq(PromotionGroupSpec::getPromotionGroupId, promotionGroupId).list();
            List<PromotionGroupSpecUser> specUsers = new ArrayList<>();
            if(list1.size() == 0 || users.size() == 0) {
                return;
            }
            //组装活动团长
            List<PromotionGroupUser> promotionGroupUsers = new ArrayList<>();
            for(User user: users){
                PromotionGroupUser promotionGroupUser = new PromotionGroupUser();
                promotionGroupUser.setPromotionGroupId(promotionGroup.getPromotionGroupId());
                promotionGroupUser.setPromotionName(promotionGroup.getName());
                promotionGroupUser.setUserId(user.getUserId());
                promotionGroupUser.setNickName(user.getNickName());
                promotionGroupUser.setMobile(user.getMobile());
                promotionGroupUser.setAvatar(user.getAvatar());
                promotionGroupUser.setCreateTime(new Date());
                promotionGroupUser.setCompanyWechatId(adminUser.getCompanyWechatId());
                promotionGroupUser.setCompanyName(adminUser.getCompanyName());
                promotionGroupUsers.add(promotionGroupUser);
            }
            promotionGroupUserService.saveBatch(promotionGroupUsers);

            //初始化商品规格的团长
            for (PromotionGroupSpec promotionGroupSpec : list1) {
                for(User user : users){
                    PromotionGroupSpecUser promotionGroupSpecUser = new PromotionGroupSpecUser();
                    BeanUtils.copyProperties(promotionGroupSpec,promotionGroupSpecUser);
                    promotionGroupSpecUser.setUserId(user.getUserId());
                    promotionGroupSpecUser.setUserName(user.getNickName());
                    promotionGroupSpecUser.setUserPhone(user.getMobile());
                    promotionGroupSpecUser.setCreateTime(new Date());
                    promotionGroupSpecUser.setGroupPrice(promotionGroupSpec.getComGroupPrice());
                    promotionGroupSpecUser.setShareAmount(promotionGroupSpec.getComShareAmount());
                    promotionGroupSpecUser.setCompanyWechatId(adminUser.getCompanyWechatId());
                    promotionGroupSpecUser.setCompanyName(adminUser.getCompanyName());
                    specUsers.add(promotionGroupSpecUser);

                }
            }
            promotionGroupSpecUserService.saveBatch(specUsers);
        }

        //4.设置为团购活动商品
        if(goodsIds.size() > 0) {
            goodsService.lambdaUpdate()
                    .set(Goods::getPromotionGroup, true)
                    .in(Goods::getGoodsId, goodsIds)
                    .update();
        }
    }


    public void addGroupUser(User user){
        //1.remove
        this.deleteGroupUser(user);
        //2.add
        List<PromotionGroupSpec> list = promotionGroupSpecService.list();
        List<PromotionGroupSpecUser> specUsers = new ArrayList<>();
        for (PromotionGroupSpec promotionGroupSpec : list) {
                PromotionGroupSpecUser promotionGroupSpecUser = new PromotionGroupSpecUser();
                BeanUtils.copyProperties(promotionGroupSpec,promotionGroupSpecUser);
                promotionGroupSpecUser.setUserId(user.getUserId());
                promotionGroupSpecUser.setUserName(user.getNickName());
                promotionGroupSpecUser.setUserPhone(user.getMobile());
                promotionGroupSpecUser.setCreateTime(new Date());
                promotionGroupSpecUser.setGroupPrice(promotionGroupSpec.getComGroupPrice());
                promotionGroupSpecUser.setShareAmount(promotionGroupSpec.getComShareAmount());
                promotionGroupSpecUser.setCompanyWechatId(user.getCompanyWechatId());
                promotionGroupSpecUser.setCompanyName(user.getCompanyName());
                specUsers.add(promotionGroupSpecUser);
        }
        promotionGroupSpecUserService.saveBatch(specUsers);
    }

    public void deleteGroupUser(User user){
        promotionGroupSpecUserService.lambdaUpdate()
                .eq(PromotionGroupSpecUser::getUserId,user.getUserId())
                .eq(StringUtils.isNotBlank(user.getCompanyWechatId()),PromotionGroupSpecUser::getCompanyWechatId,user.getCompanyWechatId())
                .remove();
        promotionGroupUserService.lambdaUpdate().eq(PromotionGroupUser::getUserId,user.getUserId()).remove();
    }


    /**
     * 拼团详情
     */
    public IPage<PromotionGroupDetail> ptDetail(String promotionGroupId,String mobile,Integer pageNum,Integer pageSize){
        //查询所有团长
        IPage page = promotionGroupUserService.lambdaQuery()
                .eq(PromotionGroupUser::getPromotionGroupId,promotionGroupId)
                .like(StringUtils.isNotBlank(mobile),PromotionGroupUser::getMobile,mobile)
                .page(new Page<>(pageNum,pageSize));

        List<PromotionGroupDetail> list = new ArrayList<>();
        for(Object o : page.getRecords()){
            PromotionGroupUser user = (PromotionGroupUser)o;
            PromotionGroupDetail promotionGroupDetail = promotionMapper.queryPtDetail(promotionGroupId,user.getUserId());
            promotionGroupDetail.setNickName(user.getNickName());
            promotionGroupDetail.setWebsitName("团长");
            promotionGroupDetail.setPosition("团长");
            promotionGroupDetail.setPhone(user.getMobile());
            promotionGroupDetail.setUserId(user.getUserId());

            //首次访问时间
            IPage<GoodsVisit> page1 = goodsVisitService.lambdaQuery()
                    .eq(GoodsVisit::getShareUserId, user.getUserId())
                    .eq(GoodsVisit::getPromotionGroupId,promotionGroupId)
                    .orderByAsc(GoodsVisit::getCreateTime)
                    .page(new Page<>(1, 1));
            if(page1.getTotal() > 0) {
                promotionGroupDetail.setFirstTime(page1.getRecords().get(0).getCreateTime());
            }
            //总访问次数
            Integer count = goodsVisitService.lambdaQuery()
                    .eq(GoodsVisit::getShareUserId, user.getUserId())
                    .eq(GoodsVisit::getPromotionGroupId,promotionGroupId)
                    .count();
            promotionGroupDetail.setShareNum(count);
            //订单数量
            Integer orderNum = orderInfoService.lambdaQuery()
                    .notIn(OrderInfo::getOrderStatus,Arrays.asList(OrderStatusEnum.CLOSE.toString(),OrderStatusEnum.TIMEOUT.toString()))
                    .eq(OrderInfo::getPromotionGroupId,promotionGroupId)
                    .eq(OrderInfo::getPromotionGroupUserId, user.getUserId()).count();
            promotionGroupDetail.setOrderNum(orderNum);
            //订单台数
            Integer orderDetilNum = promotionMapper.queryTotalGoodsNum(promotionGroupId,user.getUserId());
            promotionGroupDetail.setGoodsNum(orderDetilNum);
            //分佣金额
            promotionGroupDetail.setShareTotalAmount(promotionMapper.queryTotalShareAmount(null,promotionGroupId,user.getUserId()));
            //已结算金额
            promotionGroupDetail.setSettledAmount(promotionMapper.queryTotalShareAmount(OrderShareStatusEnum.OVER.toString(),promotionGroupId,user.getUserId()));
            list.add(promotionGroupDetail);
        }
        page.setRecords(list);
        return page;
    }

    /**
     * 拼团订单明细
     */
    public IPage<OrderInfo> queryOrderList(String promotionGroupId,String userId,Integer pageNo,Integer pageSize){
        IPage<OrderInfo> page = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getPromotionGroupId,promotionGroupId)
                .eq(OrderInfo::getPromotionGroupUserId, userId)
                .orderByDesc(OrderInfo::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
        return page;
    }
    /**
     * 拼团分享明细
     */
    public IPage<GoodsVisit> queryGoodsVisit(String promotionGroupId,String userId,Integer pageNo,Integer pageSize, HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        IPage<GoodsVisit> page = goodsVisitService.lambdaQuery()
                .in(CollectionUtils.isNotEmpty(companyWechatIds), GoodsVisit::getCompanyWechatId, companyWechatIds)
                .eq(GoodsVisit::getPromotionGroupId,promotionGroupId)
                .eq(GoodsVisit::getShareUserId, userId)
                .orderByDesc(GoodsVisit::getCreateTime)
                .page(new Page<>(pageNo, pageSize));
        return page;
    }


    public IPage<PromotionGroupListVO> pageV2(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, PromotionGroupListVO.class);
        IPage<PromotionGroupListVO> orderShareVOIPage = commonPageV2Mapper.pageV2Group(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds);
        //组装数据
        List<PromotionGroupListVO> list = new ArrayList<>();
        for (PromotionGroupListVO promotionGroup : orderShareVOIPage.getRecords()) {

            PromotionGroupListVO promotionGroupList = new PromotionGroupListVO();
            BeanUtils.copyProperties(promotionGroup,promotionGroupList);
            //参与商品数量
            Integer count = promotionGroupSpecService.lambdaQuery().eq(PromotionGroupSpec::getPromotionGroupId, promotionGroup.getPromotionGroupId()).count();
            promotionGroupList.setGoodsNum(count);
            //订单数量
            Integer orderNum = orderInfoService.lambdaQuery()
                    .notIn(OrderInfo::getOrderStatus,Arrays.asList(OrderStatusEnum.CLOSE.toString(),OrderStatusEnum.TIMEOUT.toString()))
                    .eq(OrderInfo::getPromotionGroupId, promotionGroup.getPromotionGroupId()).count();
            promotionGroupList.setOrderNum(orderNum);
            //订单台数
            Integer orderDetilNum = promotionMapper.queryTotalGoodsNum(promotionGroup.getPromotionGroupId(),null);
            promotionGroupList.setOrderDetailNum(orderDetilNum);
            //订单总金额
            BigDecimal totalAmount = promotionMapper.queryOrderTotalAmount(promotionGroup.getPromotionGroupId());
            promotionGroupList.setOrderTotalAmount(totalAmount);
            //团长分佣总额
            BigDecimal totalOrderShareAmount = promotionMapper.queryTotalShareAmount(null,promotionGroup.getPromotionGroupId(),null);
            promotionGroupList.setShareTotalAmount(totalOrderShareAmount);
            list.add(promotionGroupList);
        }
        orderShareVOIPage.setRecords(list);
        return orderShareVOIPage;
    }
}
