package com.ruoyi.bst.device.service.impl;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.bst.device.domain.DeviceQuery;
import com.ruoyi.bst.device.domain.DeviceVO;
import com.ruoyi.bst.device.mapper.DeviceMapper;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.device.service.DeviceValidator;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;

@Service
public class DeviceValidatorImpl implements DeviceValidator {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceService deviceService;

    @Override
    public boolean canEdit(Long id) {
        return canOperate(Collections.singletonList(id));
    }

    @Override
    public boolean canDeleteAll(List<Long> ids) {
        return canOperate(ids);
    }

    private boolean canOperate(List<Long> ids) {
        return canView(ids);
    }

    private boolean canView(List<Long> ids) {
        if (CollectionUtils.isEmptyElement(ids)) {
            return false;
        }
        DeviceQuery query = new DeviceQuery();
        query.setIds(ids);
        List<Long> idList = deviceMapper.selectIdList(query);
        return new HashSet<>(idList).containsAll(ids);
    }

    @Override
    public boolean canLink(String mac, Long userId) {
        if (StringUtils.isBlank(mac) || userId == null) {
            return false;
        }
        DeviceVO device = deviceService.selectByMac(mac);
        return canView(device, userId);
    }

    // 是否可以查看设备
    private boolean canView(DeviceVO device, Long userId) {
        return isMch(device, userId) || isAreaUser(device, userId) || isOrderUser(device, userId) || isAreaAgent(device, userId);
    }

    // 是否是商户
    private boolean isMch(DeviceVO device, Long userId) {
        return device != null && device.getMchId() != null && device.getMchId().equals(userId);
    }

    // 是否是运营区管理员
    private boolean isAreaUser(DeviceVO device, Long userId) {
        return device.getAreaUserId() != null && device.getAreaUserId().equals(userId);
    }

    // 是否是订单用户
    private boolean isOrderUser(DeviceVO device, Long userId) {
        return device.getOrderUserId() != null && device.getOrderUserId().equals(userId);
    }

    // 是否是运营区代理
    private boolean isAreaAgent(DeviceVO device, Long userId) {
        return device.getAreaAgentId() != null && device.getAreaAgentId().equals(userId);
    }

}
