package com.dji.sample.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dji.sample.manage.dao.IFleetUserMapper;
import com.dji.sample.manage.model.dto.FleetUserDTO;
import com.dji.sample.manage.model.entity.FleetUserEntity;
import com.dji.sample.manage.model.entity.UserEntity;
import com.dji.sample.manage.model.enums.UserTypeEnum;
import com.dji.sample.manage.service.IFleetUserService;
import com.dji.sample.manage.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author guan
 */
@Service
@Transactional
public class FleetUserServiceImpl extends ServiceImpl<IFleetUserMapper, FleetUserEntity> implements IFleetUserService {

    @Autowired
    private IFleetUserMapper mapper;

    @Autowired
    private IUserService userService;

    @Override
    public void addFleetUser(List<FleetUserEntity> userList) {

        for (FleetUserEntity addUser : userList) {
            this.mapper.insert(addUser);
        }

    }

    @Override
    public List<FleetUserDTO> searchUserDTOListByFleetId(String fleetId) {

        LambdaQueryWrapper<FleetUserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FleetUserEntity::getFleetId, fleetId);

        List<FleetUserEntity> fleetUserEntities = this.mapper.selectList(queryWrapper);

        List<FleetUserDTO> userDTOList = new ArrayList<>();
        for (FleetUserEntity fleetUserEntity : fleetUserEntities) {
            userDTOList.add(fleetUserEntityToDTO(fleetUserEntity));
        }
        return userDTOList;
    }

    public FleetUserDTO fleetUserEntityToDTO(FleetUserEntity entity) {

        FleetUserDTO fleetUserDTO = new FleetUserDTO();

        fleetUserDTO.setId(entity.getId());
        fleetUserDTO.setFleetId(entity.getFleetId());
        fleetUserDTO.setUserId(entity.getUserId());

        // 查询 user
        LambdaQueryWrapper<UserEntity> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(UserEntity::getId, fleetUserDTO.getUserId());
        UserEntity user = userService.getOne(userQueryWrapper);

        if (!ObjectUtils.isEmpty(user)) {
            fleetUserDTO.setUsername(user.getUsername());
            fleetUserDTO.setUserTypeName(UserTypeEnum.find(user.getUserType()).name());
        }

        return fleetUserDTO;
    }
}
