package co.yixiang.yshop.module.distributor.service.distributoruser;

import cn.hutool.core.collection.CollUtil;
import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.common.util.collection.CollectionUtils;
import co.yixiang.yshop.module.distributor.controller.admin.distributororder.vo.DistributorOrderExportReqVO;
import co.yixiang.yshop.module.distributor.controller.admin.distributoruser.vo.DistributorUserExportReqVO;
import co.yixiang.yshop.module.distributor.controller.admin.distributoruser.vo.DistributorUserPageReqVO;
import co.yixiang.yshop.module.distributor.controller.app.distributoruser.vo.AppDistributorUserCountRespVO;
import co.yixiang.yshop.module.distributor.controller.app.distributoruser.vo.AppDistributorUserPageReqVO;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributor.DistributorDO;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributororder.DistributorOrderDO;
import co.yixiang.yshop.module.distributor.dal.dataobject.distributoruser.DistributorUserDO;
import co.yixiang.yshop.module.distributor.enums.DistributorLevelTypeEnum;
import co.yixiang.yshop.module.distributor.enums.DistributorOrderStatusEnum;
import co.yixiang.yshop.module.distributor.service.distributor.DistributorService;
import co.yixiang.yshop.module.distributor.service.distributororder.DistributorOrderService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static co.yixiang.yshop.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Service
@Validated
public class DistributorUserFacadeImpl implements DistributorUserFacade {

    @Resource
    private DistributorService distributorService;

    @Resource
    private DistributorUserService distributorUserService;

    @Resource
    private DistributorOrderService distributorOrderService;


    /**
     * 获取今日用户数量
     *
     * @param type 一级 二级
     * @return 数量
     */
    @Override
    public Integer getTodayCount(Integer type) {
        Long userId = getLoginUserId();
        DistributorDO distributorDO = distributorService.getDistributorByUserId(userId);

        DistributorUserExportReqVO distributorUserExportReqVO = new DistributorUserExportReqVO();
        if (DistributorLevelTypeEnum.P1.getType().equals(type)) {
            distributorUserExportReqVO.setSuperiorIdP1(distributorDO.getId());
        } else if (DistributorLevelTypeEnum.P2.getType().equals(type)) {
            distributorUserExportReqVO.setSuperiorIdP2(distributorDO.getId());
        }

        LocalDateTime[] expireTime = new LocalDateTime[2];
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime startTime = now.withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endTime = now.withHour(23).withMinute(59).withSecond(59);
        expireTime[0] = startTime;
        expireTime[1] = endTime;

        distributorUserExportReqVO.setCreateTime(expireTime);
        List<DistributorUserDO> userList = distributorUserService.getUserList(distributorUserExportReqVO);
        return userList.size();
    }

    /**
     * 获取一级 二级用户总数
     *
     * @return 用户总数
     */
    @Override
    public AppDistributorUserCountRespVO getCount() {
        Long userId = getLoginUserId();
        DistributorDO distributorDO = distributorService.getDistributorByUserId(userId);

        AppDistributorUserCountRespVO respVO = new AppDistributorUserCountRespVO();

        List<DistributorUserDO> p1List = distributorUserService.getUserList(new DistributorUserExportReqVO().setSuperiorIdP1(distributorDO.getId()));

        List<DistributorUserDO> p2List = distributorUserService.getUserList(new DistributorUserExportReqVO().setSuperiorIdP2(distributorDO.getId()));

        respVO.setP1Count(p1List.size());
        respVO.setP2Count(p2List.size());
        return respVO;
    }

    @Override
    public PageResult<DistributorUserDO> getAppPage(AppDistributorUserPageReqVO reqVO) {
        Long userId = getLoginUserId();
        DistributorDO distributorDO = distributorService.getDistributorByUserId(userId);

        DistributorUserPageReqVO distributorUserPageReqVO = new DistributorUserPageReqVO();

        // 订单查询条件
        DistributorOrderExportReqVO orderExportReqVO = new DistributorOrderExportReqVO();

        // 判断一级用户还是二级用户
        if (DistributorLevelTypeEnum.P1.getType().equals(reqVO.getType())) {
            distributorUserPageReqVO.setSuperiorIdP1(distributorDO.getId());
            orderExportReqVO.setSuperiorIdP1(distributorDO.getId());
        } else if (DistributorLevelTypeEnum.P2.getType().equals(reqVO.getType())) {
            distributorUserPageReqVO.setSuperiorIdP2(distributorDO.getId());
            orderExportReqVO.setSuperiorIdP2(distributorDO.getId());
        } else {
            return new PageResult<>(0L);
        }

        // 查询所有分销商下用户
        PageResult<DistributorUserDO> userPage = distributorUserService.getUserPage(distributorUserPageReqVO);
        List<DistributorUserDO> list = userPage.getList();
        // 获取用户
        List<Long> userIds = CollectionUtils.convertList(list, DistributorUserDO::getUserId);
        // 查询用户所有此分销商的分销订单
        orderExportReqVO.setUserIds(userIds);
        List<DistributorOrderDO> orderList = distributorOrderService.getOrderList(orderExportReqVO);

        Map<Long, List<DistributorOrderDO>> map = orderList.stream().collect(Collectors.groupingBy(DistributorOrderDO::getUserId));
        list.forEach(distributorUserDO -> {
            List<DistributorOrderDO> orderDOList = map.get(distributorUserDO.getUserId());
            if (CollUtil.isNotEmpty(orderDOList)) {
                BigDecimal productAmount = BigDecimal.ZERO;
                BigDecimal wages = BigDecimal.ZERO;
                for (DistributorOrderDO orderDO : orderDOList) {
                    productAmount = productAmount.add(orderDO.getProductPrice());
                    if (orderDO.getStatus().equals(DistributorOrderStatusEnum.COMPLETE.getStatus())) {
                        if (DistributorLevelTypeEnum.P1.getType().equals(reqVO.getType())) {
                            wages = wages.add(orderDO.getFirstAmount());
                        } else if (DistributorLevelTypeEnum.P2.getType().equals(reqVO.getType())) {
                            wages = wages.add(orderDO.getSecondAmount());
                        }
                    }
                }
                distributorUserDO.setProductAmount(productAmount);
                distributorUserDO.setWages(wages);
                distributorUserDO.setOrderCount(orderDOList.size());
            } else {
                distributorUserDO.setProductAmount(BigDecimal.ZERO);
                distributorUserDO.setWages(BigDecimal.ZERO);
                distributorUserDO.setOrderCount(0);
            }
        });

        return userPage;
    }
}
