package com.dayou.service.impl;

import com.dayou.common.BaseEntity;
import com.dayou.entity.Team;
import com.dayou.entity.TeamMember;
import com.dayou.entity.UserTarget;
import com.dayou.exception.ErrorCode;
import com.dayou.mapper.UserTargetMapper;
import com.dayou.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayou.utils.LoginContext;
import com.dayou.vo.UserTargetVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 员工目标 服务实现类
 * </p>
 *
 * @author wucl
 * @since 2023-02-14
 */
@Slf4j
@Service
public class UserTargetServiceImpl extends ServiceImpl<UserTargetMapper, UserTarget> implements IUserTargetService {


    @Autowired
    private UserTargetMapper userTargetMapper;

    @Autowired
    private IItemBrokerageGeneralService iItemBrokerageGeneralService;

    @Autowired
    private ITeamMemberService teamMemberService;

    @Autowired
    private ITeamService teamService;

    @Autowired
    private IUserService userService;

    @Override
    public UserTarget detail(Long id){
        return this.getById(id);
    }

    @Override
    public Boolean add(UserTarget userTarget){
        if (userTarget.getPaymentTarget()!=null && userTarget.getPaymentTarget() <= 0){
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"目标金额不能小于或等于0");
        }
        if (userTarget.getSaleTarget() !=null && userTarget.getSaleTarget() <= 0){
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"目标金额不能小于或等于0");
        }
        Long userId = LoginContext.getUserId();
        UserTarget ut = this.getOne(new LambdaQueryWrapper<UserTarget>().eq(UserTarget::getUserId, userId));
        if (ut==null){
            userTarget.setUserId(userId);
           return this.save(userTarget);
        }
        ut.setSaleTarget(userTarget.getSaleTarget());
        ut.setPaymentTarget(userTarget.getPaymentTarget());
        this.updateById(ut);
        iItemBrokerageGeneralService.updateAheadStatus(userId);
        return  Boolean.TRUE;
    }

    @Override
    public Boolean update(UserTarget userTarget){
        return  this.updateById(userTarget);
    }

    @Override
    public List<UserTargetVO> getList(UserTargetVO userTargetVO) {
        List<UserTargetVO> list = userTargetMapper.getList(userTargetVO);
        return list;
    }

    @Override
    public UserTarget getUserTarget(Long userId) {
        UserTarget userTarget = this.getOne(new LambdaQueryWrapper<UserTarget>().eq(UserTarget::getUserId, userId));
        if (userTarget==null || userTarget.getPaymentTarget()==null){
            userTarget = new UserTarget();
            userTarget.setSaleTarget(0d);
            userTarget.setPaymentTarget(0d);
            log.info("客户经理id[{}]未设置年回款目标。", userId);
        }
        return userTarget;
    }

    @Override
    public UserTarget getTeamTarget(Long userId) {
        Set<Long> juniorUserId = new HashSet<>();
        Team team = teamService.getOne(new LambdaQueryWrapper<Team>().eq(Team::getSupervisorId, userId).eq(BaseEntity::getDeleted, Boolean.FALSE));
        //当team为空时，则userId代表营销经理
        if (team!=null){
            juniorUserId = teamMemberService.list(new LambdaQueryWrapper<TeamMember>()
                    .eq(TeamMember::getTeamId,team.getId()).eq(BaseEntity::getDeleted,Boolean.FALSE)).stream().map(TeamMember::getMemberId).collect(Collectors.toSet());
        }else {
            juniorUserId = userService.getJuniorUserId(userId);
            juniorUserId.add(userId);
        }

        UserTarget userTarget = new UserTarget();
        userTarget.setUserId(userId);
        if (!CollectionUtils.isEmpty(juniorUserId)){
            List<UserTarget> list = this.list(new LambdaQueryWrapper<UserTarget>().in(UserTarget::getUserId, juniorUserId));
            double paymentSum = list.stream().filter(x -> x.getPaymentTarget() != null).collect(Collectors.summarizingDouble(UserTarget::getPaymentTarget)).getSum();
            double saleSum = list.stream().filter(x -> x.getSaleTarget() != null).collect(Collectors.summarizingDouble(UserTarget::getSaleTarget)).getSum();
            userTarget.setPaymentTarget(paymentSum);
            userTarget.setSaleTarget(saleSum);
            return userTarget;
        }
        log.info("员工id[{}]非部门领导。", userId);
        userTarget.setPaymentTarget(0d);
        userTarget.setSaleTarget(0d);
        return userTarget;
    }

}
