package com.zksy.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zksy.base.domain.EquipmentMaintain;
import com.zksy.base.domain.EquipmentStatus;
import com.zksy.base.mapper.EquipmentMaintainMapper;
import com.zksy.base.mapper.EquipmentStatusMapper;
import com.zksy.common.core.domain.entity.SysUser;
import com.zksy.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class DevicePhoneFetchUtil {

    @Autowired
    private EquipmentMaintainMapper equipmentMaintainMapper;

    @Autowired
    private EquipmentStatusMapper equipmentStatusMapper;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 根据设备ID获取所有关联手机号
     * @param deviceId 设备ID
     * @return 去重后的有效手机号列表
     */
    public List<String> getPhoneListByDeviceId(String deviceId) {
        Set<String> phoneSet = new HashSet<>();
        addAllMaintainPersonPhones(phoneSet, deviceId);
        addUserPhoneByStatus(phoneSet, deviceId);
        return phoneSet.stream()
                .filter(this::isValidPhone)
                .collect(Collectors.toList());
    }

    private void addAllMaintainPersonPhones(Set<String> phoneSet, String deviceId) {
        LambdaQueryWrapper<EquipmentMaintain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EquipmentMaintain::getEquipmentId, deviceId);

        List<EquipmentMaintain> maintainList = equipmentMaintainMapper.selectList(queryWrapper);
        if (maintainList == null || maintainList.isEmpty()) {
            return;
        }
        maintainList.forEach(maintain -> {
            String phone = String.valueOf(maintain.getMaintainPersonPhone());
            phoneSet.add(phone);
        });
    }

    private void addUserPhoneByStatus(Set<String> phoneSet, String deviceId) {
        LambdaQueryWrapper<EquipmentStatus> statusWrapper = new LambdaQueryWrapper<>();
        statusWrapper.eq(EquipmentStatus::getEquipmentId, deviceId);
        EquipmentStatus equipmentStatus = equipmentStatusMapper.selectOne(statusWrapper);

        if (equipmentStatus == null || equipmentStatus.getUserId() == null) {
            return;
        }
        SysUser sysUser = sysUserService.selectUserById(equipmentStatus.getUserId());

        if (sysUser != null && sysUser.getPhonenumber() != null && "0".equals(sysUser.getDelFlag())) {
            phoneSet.add(sysUser.getPhonenumber());
        }
    }

    private boolean isValidPhone(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");
    }
}
