package com.ym.mec.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.TenantProxyDividendDao;
import com.ym.mec.biz.dal.entity.TenantPreJoin;
import com.ym.mec.biz.dal.entity.TenantProxyDividend;
import com.ym.mec.biz.dal.entity.TenantProxyUserRelation;
import com.ym.mec.biz.dal.vo.ProxyDividendInfoVo;
import com.ym.mec.biz.dal.vo.ProxyDividendVo;
import com.ym.mec.biz.service.TenantPreJoinService;
import com.ym.mec.biz.service.TenantProxyDividendService;
import com.ym.mec.biz.service.TenantProxyUserRelationService;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.PageUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

/**
 * 代理商分润表(TenantProxyDividend)表服务实现类
 *
 * @author hgw
 * @since 2022-04-22 14:08:19
 */
@Service("tenantProxyDividendService")
public class TenantProxyDividendServiceImpl extends ServiceImpl<TenantProxyDividendDao, TenantProxyDividend> implements TenantProxyDividendService {

    private final static Logger log = LoggerFactory.getLogger(TenantProxyDividendServiceImpl.class);

    @Autowired
    private TenantPreJoinService tenantPreJoinService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private TenantProxyUserRelationService tenantProxyUserRelationService;

    @Override
    public TenantProxyDividendDao getDao() {
        return this.baseMapper;
    }

    /**
     * 代理商分润汇总查询
     */
    @Override
    public ProxyDividendVo queryProxyDividend() {
        ProxyDividendVo result = new ProxyDividendVo();
        result.setPreTenant(0);
        result.setTenantAgency(0);

        List<TenantPreJoin> preJoinsList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>();

        SysUser user = getUser();
        //当前登录人是代理商账号类型，需要做数据隔离
        if (user.getUserType().equalsIgnoreCase("PROXY")) {
            //查询代理商
            TenantProxyUserRelation proxyUserRelation = tenantProxyUserRelationService.getOne(Wrappers.<TenantProxyUserRelation>lambdaQuery()
                    .eq(TenantProxyUserRelation::getUserId, user.getId()));
            if (Objects.nonNull(proxyUserRelation)) {
                param.put("proxyId", proxyUserRelation.getProxyId());
                //查询该代理商下所有代理人
                List<TenantProxyUserRelation> relationList = tenantProxyUserRelationService.list(Wrappers.<TenantProxyUserRelation>lambdaQuery()
                        .eq(TenantProxyUserRelation::getProxyId, proxyUserRelation.getProxyId()));
                List<Integer> userList = relationList.stream().map(TenantProxyUserRelation::getUserId).collect(Collectors.toList());
                //查询当前代理商入驻信息
                preJoinsList = tenantPreJoinService.list(Wrappers.<TenantPreJoin>lambdaQuery()
                        .in(TenantPreJoin::getRecommender, userList));
            }
        } else {
            //查询入驻信息
            preJoinsList = tenantPreJoinService.list();
        }

        if (CollectionUtils.isNotEmpty(preJoinsList)) {
            result.setTenantAgency(preJoinsList.size());
            long count = preJoinsList.stream()
                    .filter(a -> Objects.nonNull(a.getState()) && a.getState() == 1)
                    .count();
            result.setPreTenant((int) count);
        }

        //团练宝销售数
        int count = baseMapper.queryProxyDividendCount(param);
        result.setMemberCount(count);
        return result;
    }

    /**
     * 代理商分润查询
     *
     * @param param 传入参数
     *              <p> -  proxyId 代理商id
     *              <p> -  recommenderId 推荐人id
     *              <p> -  startData 开始日期 年月日
     *              <p> -  endData 结束日期 年月日
     *              <p> - row 条数
     *              <p> - page 页数
     * @return
     */
    @Override
    public PageInfo<ProxyDividendInfoVo> queryProxyDividendInfo(Map<String, Object> param) {
        Optional.ofNullable(param.get("startData")).orElseThrow(() -> new BizException("查询的开始日期不能为空！"));
        Optional.ofNullable(param.get("endData")).orElseThrow(() -> new BizException("查询的结束日期不能为空！"));
        //拼接时分秒
        BiConsumer<String, String> addTimeCons = (key, time) -> Optional.ofNullable(param.get(key)).map(String::valueOf)
                .ifPresent(date -> param.put(key, date + " " + time));
        addTimeCons.accept("startData", "00:00:00");
        addTimeCons.accept("endData", "23:59:59");

        SysUser user = getUser();
        //当前登录人是代理商账号类型，需要做数据隔离
        if (user.getUserType().equalsIgnoreCase("PROXY")) {
            //查询代理商
            TenantProxyUserRelation proxyUserRelation = tenantProxyUserRelationService.getOne(Wrappers.<TenantProxyUserRelation>lambdaQuery()
                    .eq(TenantProxyUserRelation::getUserId, user.getId()));
            if (Objects.nonNull(proxyUserRelation)) {
                param.put("proxyId", proxyUserRelation.getProxyId());
            }
        }
        //分页查询分润记录
        Page<ProxyDividendInfoVo> pageInfo = PageUtil.getPageInfo(param);
        pageInfo.setAsc("a.active_time_");
        IPage<ProxyDividendInfoVo> tiPage = baseMapper.queryProxyDividendInfo(pageInfo, param);
        return PageUtil.pageInfo(tiPage);
    }

    private SysUser getUser() {
        //修改机构基础信息
        return Optional.ofNullable(sysUserFeignService.queryUserInfo())
                .orElseThrow(() -> new BizException("用户信息获取失败,请刷新页面或者重新登录!"));
    }
}

