package com.skr.mdm.authentication.user.imei;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.skr.mdm.bean.dto.UserLoginCallbackDTO;
import com.skr.mdm.dao.DeviceEquipmentDao;
import com.skr.mdm.dto.LoginUserDTO;
import com.skr.mdm.entity.DeviceEquipmentDO;
import com.skr.mdm.enums.DeleteStateEnum;
import com.skr.mdm.enums.EquipmentStateEnum;
import com.skr.mdm.rabbitmq.RabbitMQProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author nfq
 * @date 2020/7/15 10:58
 */
@Service
public class ImeiUserDetailsServiceImpl implements UserDetailsService {

    private static final String SPLIT = "-";

    private Integer companyId;

    @Autowired
    private DeviceEquipmentDao equipmentDao;
    @Autowired
    private RabbitMQProvider rabbitMQProvider;

    @Override
    public UserDetails loadUserByUsername(String imei) throws UsernameNotFoundException {
        if (StringUtils.isBlank(imei) || companyId == null) {
            throw new ImeiAuthenticationException("imei为空:" + imei + "companyId:" + companyId);
        }
        String firstImei = imei;
        String endImei = null;
        if (imei.contains(SPLIT)) {
            String[] split = StringUtils.split(firstImei, SPLIT);
            firstImei = split[0];
            endImei = split[1];
        }
        DeviceEquipmentDO deviceEquipmentDO = new LambdaQueryChainWrapper<>(equipmentDao)
                .eq(DeviceEquipmentDO::getCompanyId, companyId)
                .eq(DeviceEquipmentDO::getImei, firstImei)
                .eq(DeviceEquipmentDO::getIsDelete, DeleteStateEnum.NON_DELETE.getState())
                .one();
        if (deviceEquipmentDO == null && StringUtils.isNotBlank(endImei)) {
            deviceEquipmentDO = new LambdaQueryChainWrapper<>(equipmentDao)
                    .eq(DeviceEquipmentDO::getCompanyId, companyId)
                    .eq(DeviceEquipmentDO::getImei, endImei)
                    .eq(DeviceEquipmentDO::getIsDelete, DeleteStateEnum.NON_DELETE.getState())
                    .one();
        }
        if (deviceEquipmentDO == null) {
            throw new ImeiAuthenticationException("imei不存在:" + imei + "companyId:" + companyId);
        }
        // 激活时间
        if (EquipmentStateEnum.INACTIVATED.getState().equals(deviceEquipmentDO.getEquipmentState())) {
            LambdaUpdateChainWrapper<DeviceEquipmentDO> updateChainWrapper = new LambdaUpdateChainWrapper<>(equipmentDao);
            updateChainWrapper.set(DeviceEquipmentDO::getActivationTime, new Date())
                    .eq(DeviceEquipmentDO::getId, deviceEquipmentDO.getId())
                    .update();
            // 异步拉取全局指令
            UserLoginCallbackDTO userLoginCallbackDTO = UserLoginCallbackDTO.builder()
                    .deviceIdList(ListUtil.toList(deviceEquipmentDO.getId()))
                    .departmentId(deviceEquipmentDO.getDepartmentId())
                    .companyId(deviceEquipmentDO.getCompanyId())
                    .build();
            rabbitMQProvider.publishRegisterEventWithDelayed(userLoginCallbackDTO);
        }
        LoginUserDTO loginUserDTO = new LoginUserDTO();
        BeanUtils.copyProperties(deviceEquipmentDO, loginUserDTO);
        return loginUserDTO;
    }

    public void setCompanyId(Integer companyId) {
        this.companyId = companyId;
    }
}
