package com.ruoyi.ss.user.service.impl;

import com.ruoyi.common.core.domain.vo.LongCountVO;
import com.ruoyi.common.domain.vo.LongDecimalVO;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.ss.bonus.domain.BonusQuery;
import com.ruoyi.ss.bonus.domain.enums.BonusArrivalType;
import com.ruoyi.ss.bonus.domain.enums.BonusStatus;
import com.ruoyi.ss.bonus.service.BonusService;
import com.ruoyi.ss.device.domain.DeviceCountVO;
import com.ruoyi.ss.device.domain.DeviceQuery;
import com.ruoyi.ss.device.domain.enums.DeviceGroupBy;
import com.ruoyi.ss.device.domain.enums.DeviceGroupByTable;
import com.ruoyi.ss.device.service.DeviceService;
import com.ruoyi.ss.store.service.StoreService;
import com.ruoyi.ss.storeStaff.domain.StoreStaffQuery;
import com.ruoyi.ss.storeStaff.service.StoreStaffService;
import com.ruoyi.ss.user.domain.SmUserVO;
import com.ruoyi.ss.user.service.UserAssembler;
import com.ruoyi.system.domain.enums.config.ConfigKey;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author wjh
 * 2024/5/6
 */
@Service
public class UserAssemblerImpl implements UserAssembler {

    @Autowired
    private StoreService storeService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private BonusService bonusService;

    @Autowired
    private StoreStaffService storeStaffService;

    /**
     * 拼接用户店铺数量
     *
     * @param list
     */
    @Override
    public void assembleStoreCount(List<SmUserVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }

        Map<Long, Integer> map = storeService.selectCountMapByUserIds(list.stream().map(SmUserVO::getUserId).collect(Collectors.toList()));

        for (SmUserVO user : list) {
            Integer count = map.get(user.getUserId());
            user.setStoreCount(count == null ? 0 : count);
        }
    }

    /**
     * 拼接用户设备数量
     *
     * @param list
     */
    @Override
    public void assembleDeviceCount(List<SmUserVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }

        DeviceQuery query = new DeviceQuery();
        query.setUserIds(list.stream().map(SmUserVO::getUserId).collect(Collectors.toList()));
        query.setGroupBy(DeviceGroupBy.user_id.name());
        query.setGroupByTable(DeviceGroupByTable.su.name());
        Map<Long, Integer> map = deviceService.selectCommonCountMap(query, DeviceCountVO::getUserId);

        for (SmUserVO user : list) {
            Integer count = map.get(user.getUserId());
            user.setDeviceCount(count == null ? 0 : count);
        }
    }

    @Override
    public void assembleRealArrivalDelay(List<SmUserVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }

        // 获取全局配置，默认延迟到账时间
        int defaultDelay = sysConfigService.getInt(ConfigKey.ARRIVAL_DELAY);

        for (SmUserVO user : list) {
            if (user == null) {
                continue;
            }
            // 优先获取用户的延迟到账时间
            if (user.getArrivalDelay() != null) {
                user.setRealArrivalDelay(user.getArrivalDelay());
            } else {
                user.setRealArrivalDelay(defaultDelay);
            }
        }

    }

    @Override
    public void assembleRealServiceRate(List<SmUserVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }
        BigDecimal sysServiceRate = sysConfigService.getBigDecimal(ConfigKey.SERVICE_FEE_RATE);

        for (SmUserVO user : list) {
            if (user == null) {
                continue;
            }
            if (user.getServiceRate() != null) {
                user.setRealServiceRate(user.getServiceRate());
            } else {
                ServiceUtil.assertion(sysServiceRate == null, "系统服务费率未配置，请联系管理员");
                user.setRealServiceRate(sysServiceRate);
            }
        }
    }

    @Override
    public void assembleWaitBonusAmount(List<SmUserVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return ;
        }

        BonusQuery query = new BonusQuery();
        query.setArrivalIds(CollectionUtils.map(list, SmUserVO::getUserId));
        query.setArrivalTypes(BonusArrivalType.userList());
        query.setStatus(BonusStatus.WAIT_DIVIDE.getStatus());
        List<LongDecimalVO> amountList = bonusService.selectWaitAmountGroupByArrival(query);

        for (SmUserVO user : list) {
            LongDecimalVO sum = amountList.stream()
                    .filter(item -> Objects.equals(item.getKey(), user.getUserId()))
                    .findFirst().orElse(null);
            if (sum != null) {
                user.setWaitBonusAmount(sum.getValue());
            } else {
                user.setWaitBonusAmount(BigDecimal.ZERO);
            }
        }
    }

    @Override
    public void assembleIsStaff(List<SmUserVO> list) {
        if (CollectionUtils.isEmptyElement(list)) {
            return;
        }

        StoreStaffQuery query = new StoreStaffQuery();
        query.setUserIds(CollectionUtils.map(list, SmUserVO::getUserId));
        query.setEnabled(true);
        List<LongCountVO> counts = storeStaffService.selectCountGroupByUserId(query);

        for (SmUserVO user : list) {
            LongCountVO count = counts.stream().filter(item -> Objects.equals(item.getKey(), user.getUserId())).findFirst().orElse(null);
            if (count == null || count.getValue() == null || count.getValue() < 1) {
                user.setIsStaff(false);
            } else {
                user.setIsStaff(true);
            }
        }
    }
}
