package com.ruoyi.frequency.customer.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.block.entity.Block;
import com.ruoyi.frequency.block.service.BlockService;
import com.ruoyi.frequency.customer.mapper.UserMapper;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author a
 * @date 2023/9/25 14:55
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessUtil businessUtil;


    @Override
    public Map<UserVo, UserInfo> selectUserInfoMap(Set<UserVo> userVoSet, UserVo userVo) {

        Map<UserVo, UserInfo> userInfoMap = new HashMap<>();

        if (userVoSet == null || userVoSet.isEmpty()) {
            return userInfoMap;
        }

        //设计师
        List<Long> customerIds = CollectionUtil.toList();

        //表现师
        List<Long> storeIds = CollectionUtil.toList();

        //销售
        List<Long> saleIds = CollectionUtil.toList();

        //企业
        List<Long> enterpriseIds = CollectionUtil.toList();

        userVoSet.stream().forEach(user -> {
            if (user == null || user.getUserId() == null) {
                return;
            }
            if (user.getUserType() == 1) {
                customerIds.add(user.getUserId());
            } else if (user.getUserType() == 2) {
                storeIds.add(user.getUserId());
            } else if (user.getUserType() == 3) {
                saleIds.add(user.getUserId());
            } else {
                enterpriseIds.add(user.getUserId());
            }
        });

        List<UserInfo> userInfos = userMapper.selectUserInfoList(customerIds, storeIds, saleIds, enterpriseIds, userVo);

        //累计服务金额基数
        BigDecimal orderAmount = new BigDecimal(businessUtil.getDict(DictConstant.OrderDict.累计服务金额基数).getDictValue());

        //当月服务单数基数
        Integer orderMonthNum = Integer.valueOf(businessUtil.getDict(DictConstant.OrderDict.当月服务单数基数).getDictValue());

        //累计服务单数基数
        Integer orderNum = Integer.valueOf(businessUtil.getDict(DictConstant.OrderDict.累计服务单数基数).getDictValue());

        userInfos.stream().forEach(userInfo -> {

            Integer userType = userInfo.getUserType();
            //上次调用此接口的时间
            String last_time_map_key = "last_time_" + userType;

            //获取在线状态
            userInfo.setOnlineStatus(getOnlineStatus(userInfo.getUserId(), last_time_map_key));

            if (ObjectUtil.equal(UserEnums.store.getCode(), userInfo.getUserType())) {
                //累计服务金额基数
                userInfo.setOrderAmount(orderAmount.add(userInfo.getOrderAmount()));

                //当月服务单数基数
                userInfo.setOrderMonthNum(orderMonthNum + userInfo.getOrderMonthNum());

                //累计服务单数基数
                userInfo.setOrderNum(orderNum + userInfo.getOrderNum());
            }

            userInfoMap.put(new UserVo(userInfo.getUserType(), userInfo.getUserId()), userInfo);
        });

        return userInfoMap;
    }

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取在线状态
     *
     * @param id
     * @param lastTimeMapKey
     * @return
     */
    private Integer getOnlineStatus(Long id, String lastTimeMapKey) {

        //在线状态;1:在线,2离线
        Integer onlineStatus = 2;

        if (redisTemplate.opsForHash().hasKey(lastTimeMapKey, id.toString())) {
            long lastTimes = Long.valueOf(redisTemplate.opsForHash().get(lastTimeMapKey, id.toString()).toString());

            //判断当前时间和上次时间是否超过6分钟(考虑到网络延时和程序卡顿,多1分钟)
            if (System.currentTimeMillis() - lastTimes < (6 * 60 * 1000)) {
                onlineStatus = 1;
            }
        }

        return onlineStatus;
    }

    @Override
    public List<UserVo> blockUserList(UserVo userVo) {
        return userMapper.blockUserList(userVo);
    }

    @Override
    public List<UserVo> shieldUserList(UserVo userVo) {
        return userMapper.shieldUserList(userVo);
    }


    @Autowired
    private StoreService storeService;

    @Override
    public void storeByEnterprise(UserVo userVo) {
        if (UserEnums.enterprise.getCode().equals(userVo.getUserType())) {
            Store one = storeService.getOne(new QueryWrapper<Store>().lambda().eq(Store::getBindEnterpriseId, userVo.getUserId()));
            if (one == null) {
                throw new CustomException(700, "token过期");
            } else {
                userVo.setUserType(UserEnums.store.getCode());
                userVo.setUserId(one.getId());
            }
        }
    }

    @Autowired
    private BlockService blockService;

    @Override
    public ResponseData userRelationship(UserVo otherUserVo, UserVo userVo) {

        List<Block> userVos = blockService.list(new QueryWrapper<Block>().lambda().eq(Block::getUserId, userVo.getUserId())
                .eq(Block::getUserType, userVo.getUserType()).eq(Block::getDelFlag, PublicCommon.启用));

        for (Block cur : userVos) {
            if (cur.getBlockUserId().equals(otherUserVo.getUserId()) && cur.getBlockUserType().equals(otherUserVo.getUserType())) {
                return ResponseData.error("你已将对方拉黑");
            }
        }
        userVos = blockService.list(new QueryWrapper<Block>().lambda().eq(Block::getUserId, otherUserVo.getUserId())
                .eq(Block::getUserType, otherUserVo.getUserType()).eq(Block::getDelFlag, PublicCommon.启用));
        for (Block cur : userVos) {
            if (cur.getBlockUserId().equals(userVo.getUserId()) && cur.getBlockUserType().equals(userVo.getUserType())) {
                return ResponseData.error("对方已将你拉黑");
            }
        }
        return ResponseData.success();
    }
}
