package com.usky.meeting.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.meeting.domain.MeetingDevice;
import com.usky.meeting.domain.MeetingFloor;
import com.usky.meeting.domain.MeetingRoom;
import com.usky.meeting.mapper.MeetingDeviceMapper;
import com.usky.meeting.mapper.MeetingRoomMapper;
import com.usky.meeting.service.MeetingDeviceService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.meeting.service.MeetingRoomService;
import com.usky.meeting.service.vo.MeetingDeviceRequestVO;
import net.bytebuddy.implementation.bytecode.Throw;
import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.bouncycastle.jcajce.provider.symmetric.AES;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.util.Optionals;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 设备表 服务实现类
 * </p>
 *
 * @author zyj
 * @since 2024-03-08
 */
@Service
public class MeetingDeviceServiceImpl extends AbstractCrudService<MeetingDeviceMapper, MeetingDevice> implements MeetingDeviceService {
    @Autowired
    private MeetingRoomMapper meetingRoomMapper;

    @Override
    public CommonPage<MeetingDevice> meetingDeviceList(MeetingDeviceRequestVO requestVO){
        Integer current = requestVO.getCurrent();
        Integer size = requestVO.getSize();
        IPage<MeetingDevice> page = new Page<>(current,size);
        LambdaQueryWrapper<MeetingDevice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(requestVO.getDeviceName()),MeetingDevice::getDeviceName,requestVO.getDeviceName())
                .like(StringUtils.isNotBlank(requestVO.getNameplate()),MeetingDevice::getNameplate,requestVO.getNameplate())
                .like(StringUtils.isNotBlank(requestVO.getMaintainer()),MeetingDevice::getMaintainer,requestVO.getMaintainer())
                .like(StringUtils.isNotBlank(requestVO.getContacts()),MeetingDevice::getContacts,requestVO.getContacts())
                .like(StringUtils.isNotBlank(requestVO.getRemark()),MeetingDevice::getRemark,requestVO.getRemark())
                .eq(MeetingDevice::getTenantId,SecurityUtils.getTenantId())
                .orderByAsc(MeetingDevice::getDeviceId);
        page = this.page(page,queryWrapper);
        if(page.getRecords().size()>0){
            List<Long> roomIdList = new ArrayList<>();
            for (int i = 0; i < page.getRecords().size(); i++) {
                roomIdList.add(Long.valueOf(page.getRecords().get(i).getRoomId()));
            }
            List<Long> list = roomIdList.stream().distinct().collect(Collectors.toList());

            LambdaQueryWrapper<MeetingRoom> queryWrapper1 = Wrappers.lambdaQuery();
            queryWrapper1.in(MeetingRoom::getRoomId,list).eq(MeetingRoom::getTenantId,SecurityUtils.getTenantId());
            List<MeetingRoom> meetingRoomList = meetingRoomMapper.selectList(queryWrapper1);
            if(CollectionUtils.isNotEmpty(meetingRoomList)){
                for (int i = 0; i < page.getRecords().size(); i++) {
                    Long RId = Long.valueOf(page.getRecords().get(i).getRoomId());
                    for (int j = 0; j < meetingRoomList.size(); j++) {
                        if(RId.equals(meetingRoomList.get(j).getRoomId())){
                            page.getRecords().get(i).setRoomName(meetingRoomList.get(j).getRoomName());
                            break;
                        }
                    }
                }
            }
        }

        return new CommonPage<>(page.getRecords(),page.getTotal(),size,current);
    }

    @Override
    public void add(MeetingDevice meetingDevice){
        if(checkNameUnique(meetingDevice)){
            throw new BusinessException("新增会议室设备失败，"+meetingDevice.getDeviceName()+"已经存在");
        }
//        Snowflake snowflake = IdUtil.createSnowflake(1,1);
//        meetingDevice.setDeviceId(snowflake.nextId());
        meetingDevice.setCreateBy(SecurityUtils.getUsername());
        meetingDevice.setCreateTime(LocalDateTime.now());
        meetingDevice.setTenantId(SecurityUtils.getTenantId());
        this.save(meetingDevice);

    }

    @Override
    public void edit(MeetingDevice meetingDevice){
        if(checkNameUnique(meetingDevice)){
            throw new BusinessException("修改会议室设备失败，"+meetingDevice.getDeviceName()+"已经存在");
        }
        meetingDevice.setUpdateBy(SecurityUtils.getUsername());
        meetingDevice.setUpdateTime(LocalDateTime.now());

        this.updateById(meetingDevice);
    }

    @Override
    public void remove(Long deviceId){
        MeetingDevice meetingDevice = this.getById(deviceId);
        Optional.ofNullable(meetingDevice).orElseThrow(() -> new BusinessException("该会议室设备不存在"));
        this.removeById(deviceId);

    }

    public boolean checkNameUnique(MeetingDevice meetingDevice){
        Long deviceId = null == meetingDevice.getDeviceId()?-1:meetingDevice.getDeviceId();
        LambdaQueryWrapper<MeetingDevice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(MeetingDevice::getDeviceName,meetingDevice.getDeviceName())
                .eq(MeetingDevice::getTenantId,SecurityUtils.getTenantId());
        MeetingDevice one = this.getOne(queryWrapper);
        return null != one && !Objects.equals(one.getDeviceId(),deviceId);
    }
}
