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

import com.ruoyi.common.core.domain.BaseValidator;
import com.ruoyi.common.core.domain.ValidateResult;
import com.ruoyi.common.core.domain.entity.SmUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ss.device.domain.DeviceQuery;
import com.ruoyi.ss.device.service.DeviceService;
import com.ruoyi.ss.user.domain.SmUserQuery;
import com.ruoyi.ss.user.domain.SmUserVO;
import com.ruoyi.ss.user.service.ISmUserService;
import com.ruoyi.ss.user.service.UserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;

/**
 * @author wjh
 * 2024/4/29
 */
@Service
public class UserValidatorImpl extends BaseValidator implements UserValidator {

    @Autowired
    private ISmUserService userService;

    @Autowired
    private DeviceService deviceService;

    /**
     * 判断用户是否存在
     *
     * @param userIds 用户id列表
     */
    @Override
    public boolean isExist(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return true;
        }
        SmUserQuery query = new SmUserQuery();
        query.setUserIds(userIds);
        int userCount = userService.selectCount(query);
        return userCount == new HashSet<Long>(userIds).size();
    }

    /**
     * 判断用户是否是商家
     *
     * @param userId
     * @return
     */
    @Override
    public boolean isMch(Long userId) {
        if (userId == null) {
            return false;
        }
        SmUserQuery query = new SmUserQuery();
        query.setUserId(userId);
        query.setIsMch(true);
        return userService.selectCount(query) > 0;
    }

    /**
     * 判断用户是否可用
     *
     * @param userId
     */
    @Override
    public boolean isUsage(Long userId) {
        if (userId == null) {
            return false;
        }
        SmUserVO user = userService.selectSmUserByUserId(userId);
        if (user == null || UserStatus.DELETED.getCode().equals(user.getDelFlag()) || UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            return false;
        }
        return true;
    }

    /**
     * 逻辑删除前校验
     */
    @Override
    public ValidateResult preLogicDel(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return error("用户id不能为空");
        }
        if (!isExist(userIds)) {
            return error("用户不存在");
        }
        return success();
    }

    @Override
    public void checkMobile(Long userId, String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return;
        }
        SmUserQuery query = new SmUserQuery();
        query.setEqPhonenumber(mobile);
        query.setExcludeUserId(userId);
        int repeatCount = userService.selectCount(query);
        ServiceUtil.assertion(repeatCount > 0, "当前手机号已被绑定");
    }

    @Override
    public void afterCheck(SmUserVO vo) {
        if (vo == null) {
            return;
        }

        // 校验手机号
        this.checkMobile(vo.getUserId(), vo.getPhonenumber());

        // 校验openId
        this.checkOpenId(vo.getUserId(), vo.getWxOpenId());

        // 校验代理商服务费
        this.checkAgentServiceRate(vo);

    }

    @Override
    public void checkBeforeInsert(SmUser data) {
        ServiceUtil.assertion(data == null, "新增用户数据不允许为空");
        // 手机号校验
        this.checkMobile(data.getUserId(), data.getPhonenumber());
        // 微信openId校验
        this.checkOpenId(data.getUserId(), data.getWxOpenId());
    }

    @Override
    public boolean isAgent(Long userId) {
        if (userId == null) {
            return false;
        }
        SmUserVO user = userService.selectSimpleById(userId);
        return user != null && UserType.AGENT.getType().equals(user.getType());
    }

    private void checkAgentServiceRate(SmUserVO vo) {
        if (vo == null) {
            return;
        }
        // 代理服务费不允许大于代理商默认设备服务费
        BigDecimal agentRate = vo.getAgentServiceRate();
        BigDecimal deviceRate = vo.getAgentDeviceService();
        ServiceUtil.assertion(agentRate != null && deviceRate != null && agentRate.compareTo(deviceRate) > 0,
                String.format("代理服务费(%s%%)不允许大于默认设备服务费(%s%%)", agentRate, deviceRate));

        // 代理服务费不允许大于目前最大的设备服务费
        DeviceQuery query = new DeviceQuery();
        query.setAgentId(vo.getUserId());
        BigDecimal maxDeviceRate = deviceService.selectMaxAgentServiceRate(query);
        ServiceUtil.assertion(maxDeviceRate != null && maxDeviceRate.compareTo(agentRate) < 0,
                "代理服务费不允许大于目前最大的设备服务费：" + maxDeviceRate + "%");

    }

    // 判断微信openId是否重复
    private void checkOpenId(Long userId, String wxOpenId) {
        if (StringUtils.isBlank(wxOpenId)) {
            return ;
        }
        SmUserQuery query = new SmUserQuery();
        query.setWxOpenId(wxOpenId);
        query.setExcludeUserId(userId);
        int repeatCount = userService.selectCount(query);
        ServiceUtil.assertion(repeatCount > 0, "用户微信OpenId重复");
    }
}
