package org.jeecg.ctop.finance.policy.service.impl;

import cn.com.ctop.common.module.mapper.ProjectMapper;
import cn.com.ctop.common.module.mapper.SysRoleMapper;
import cn.com.ctop.common.module.mapper.SysUserMapper;
import cn.com.ctop.common.module.utils.Check;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.ctop.finance.policy.entity.CwjsSaleAssistantInfo;
import org.jeecg.ctop.finance.policy.mapper.CwjsSaleAssistantInfoMapper;
import org.jeecg.ctop.finance.policy.service.ICwjsSaleAssistantInfoService;
import org.jeecg.modules.ctop.entity.ProjectMember;
import org.jeecg.modules.ctop.service.IProjectMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * aaa
 * @author jeecg-boot
 * 2021-10-18
 * @version V1.0
 */
@Service
@Slf4j
public class CwjsSaleAssistantInfoServiceImpl extends ServiceImpl<CwjsSaleAssistantInfoMapper, CwjsSaleAssistantInfo> implements ICwjsSaleAssistantInfoService {


    @Resource
    private  CwjsSaleAssistantInfoMapper cwjsSaleAssistantInfoMapper;

    @Resource
    private SysRoleMapper roleMapper;

    @Override
    public Result getSaleListByUserDepart(String userId) {
        List <CwjsSaleAssistantInfo> list = cwjsSaleAssistantInfoMapper.getSaleListByUserDepart(userId);
        return Result.successMsg("查询成功。",list);
    }


/*

    public List<CwjsSaleAssistantInfo> getCwSaleAndAssistantList(String userId){
        List<CwjsSaleAssistantInfo> resultList = new ArrayList();
        String roleCode = roleMapper.getRoleCodeByUserId(userId);
        //管理员 查询全部
        if (StringUtils.equals("admin",roleCode)){
            CwjsSaleAssistantInfo info = new CwjsSaleAssistantInfo();
            info.setSaleId(userId);
            info.setSaleName("管理员");
            resultList.add(info);//追加 管理员
            userId = null;
            //查询 销售
            List <CwjsSaleAssistantInfo> saleList = cwjsSaleAssistantInfoMapper.getCwSaleNameList(userId);
            resultList.addAll(saleList);
            //查询助理
            List <CwjsSaleAssistantInfo> assistantList = cwjsSaleAssistantInfoMapper.getCwAssistantNameList(userId);
            resultList.addAll(assistantList);
            resultList = resultList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CwjsSaleAssistantInfo :: getSaleId))),ArrayList :: new));
            log.info("查询成功-管理员。");
            return resultList;
        }
        //查询助理
        List <CwjsSaleAssistantInfo> assistantList = cwjsSaleAssistantInfoMapper.getCwAssistantNameList(userId);
        //如果该用户是 助理角色 则 对应的销售加自己的id list 必然 > 2
        if (assistantList.size() < 2){
            log.info("查询成功-销售。");
            return cwjsSaleAssistantInfoMapper.getCwSaleNameList(userId);
        }
        log.info("查询成功-助理。");
        return assistantList;
    }
*/



    public List<CwjsSaleAssistantInfo> getCwSaleAndAssistantList(String userId){
        List<CwjsSaleAssistantInfo> resultList = new ArrayList();
        String roleCode = roleMapper.getRoleCodeByUserId(userId);
        //管理员 查询全部
        if (StringUtils.equals("admin",roleCode) || "finance".equals(roleCode)){
            userId = null;
        }
        //查询 销售
        List <CwjsSaleAssistantInfo> saleList = null;
        //销售
        saleList = cwjsSaleAssistantInfoMapper.selectCwSaleName(userId);
        if (Check.isNull(saleList)){
            //助理
            saleList = cwjsSaleAssistantInfoMapper.getAssistantList(userId);
        }
        //如果为空 添加自己的id
        if (Check.isNull(saleList)){
            saleList.add(new CwjsSaleAssistantInfo().setSaleId(userId));
        }
        return saleList;
    }


    /**
     * 获取销售和助理的对应关系
     * @param userId
     * @return 人员id
     */
    @Override
    public List<String> getCwSaleAndAssistantListStr(String userId) {
        List<CwjsSaleAssistantInfo> list = getCwSaleAndAssistantList(userId);
        List<String> userIds = list.stream().map(CwjsSaleAssistantInfo::getSaleId).collect(Collectors.toList());
        return userIds;
    }


    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private IProjectMemberService projectMemberService;

    @Override
    public Result cwjsParticipateList(ProjectMember projectMember) {
        String userId = projectMember.getUserId();
        if (Check.isNull(userId)) {
            return Result.error("未获取到关联用户信息");
        }
        String projectName = projectMember.getProjectName();
        Long productId = projectMember.getProductId();

        QueryWrapper<ProjectMember> queryWrapper = new QueryWrapper<>();
        String roleCode = sysRoleMapper.getRoleCodeByUserId(userId);
        if (!"admin".equals(roleCode)) {
            List<String> userIds = getCwSaleAndAssistantListStr(projectMember.getUserId());
            queryWrapper.in("user_id", userIds);
        }
        if (!Check.isNull(projectName)) {
            queryWrapper.like("project_name", projectName);
        }
        if (!Check.isNull(productId)) {
            List<Long> projectIds = projectMapper.getProjectIdsByProductId(productId);
            if (Check.isNull(projectIds)) {
                return Result.error("该产品下暂无关联项目");
            }
            queryWrapper.in("project_id", projectIds);
        }
        queryWrapper.groupBy("project_id");
        queryWrapper.orderByDesc("create_time");
        List<ProjectMember> projectMembers = projectMemberService.list(queryWrapper);
        projectMembers = projectMemberService.getMapsByProjectList(projectMembers);
        List<ProjectMember> resultList = new ArrayList<>();
        if (!Check.isNull(projectMembers)) {
                Map<String, List<ProjectMember>> groupByMedia = projectMembers.stream().filter(p -> (!Check.isNull(p.getMediaId()))).collect(Collectors.groupingBy(ProjectMember::getMediaId));
                resultList = groupByMedia.get(projectMember.getMediaId());
                if (!Check.isNull(resultList)) {
                    resultList.stream().filter(p -> (!Check.isNull(p.getAdvertiserName()))).collect(Collectors.toList());
                    resultList = resultList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(ProjectMember::getAdvertiserId))), ArrayList::new));
                }
            }
        return Result.successMsg("成功。", resultList);
    }


}
