package com.usky.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.MeetingTemplate;
import com.usky.meeting.mapper.MeetingDeviceMapper;
import com.usky.meeting.mapper.MeetingTemplateMapper;
import com.usky.meeting.service.MeetingTemplateService;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.meeting.service.vo.MeetingTemplateRequestVO;
import com.usky.system.domain.SysUserVO;
import com.usky.system.model.LoginUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.security.Security;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 会议屏模板表 服务实现类
 * </p>
 *
 * @author fu
 * @since 2025-11-18
 */
@Service
public class MeetingTemplateServiceImpl extends AbstractCrudService<MeetingTemplateMapper, MeetingTemplate> implements MeetingTemplateService {

    @Autowired
    private MeetingDeviceMapper meetingDeviceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addAndUpdate(MeetingTemplate dto) {

        SysUserVO sysUser = SecurityUtils.getLoginUser().getSysUser();
        if (sysUser == null || sysUser.getTenantId() == null) {
            throw new BusinessException("未获取到登录用户!");
        }
        String username = sysUser.getUserName();
        Integer tenantId = sysUser.getTenantId();
        LocalDateTime now = LocalDateTime.now();

        if (dto.getId() != null) {
            dto.setUpdateTime(now);
            dto.setUpdateBy(username);
            this.updateById(dto);
        } else {
            dto.setCreateTime(now);
            dto.setCreateBy(username);
            dto.setTenantId(tenantId);
            this.save(dto);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long templateId) {
        if (templateId == null) {
            throw new BusinessException("会议模板ID不能为空！");
        }
        Integer tenantId = SecurityUtils.getTenantId();

        LambdaQueryWrapper<MeetingTemplate> tplWrap = new LambdaQueryWrapper<>();
        tplWrap.eq(MeetingTemplate::getId, templateId)
                .eq(MeetingTemplate::getTenantId, tenantId);
        boolean deleted = remove(tplWrap);
        if (!deleted) {
            throw new BusinessException("会议模板不存在！");
        }

        LambdaUpdateWrapper<MeetingDevice> deviceWrap = new LambdaUpdateWrapper<>();
        deviceWrap.set(MeetingDevice::getTemplateId, null)
                .eq(MeetingDevice::getTemplateId, templateId)
                .eq(MeetingDevice::getTenantId, tenantId);
        meetingDeviceMapper.update(null, deviceWrap);
    }

    @Override
    public CommonPage<MeetingTemplate> templateList(Integer pageNum, Integer pageSize, String name, Integer type,
                                                    String layout) {
        Page<MeetingTemplate> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<MeetingTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingTemplate::getTenantId, SecurityUtils.getTenantId())
                .like(StringUtils.isNotBlank(name), MeetingTemplate::getName, name)
                .eq(type != null, MeetingTemplate::getType, type)
                .eq(StringUtils.isNotBlank(layout) && !"all".equals(layout),
                        MeetingTemplate::getLayout, layout);

        Page<MeetingTemplate> mpPage = baseMapper.selectPage(page, wrapper);
        return new CommonPage<>(mpPage.getRecords(), mpPage.getTotal(), pageSize, pageNum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchPublishing(MeetingTemplateRequestVO requestVO) {
        Integer templateId = requestVO.getTemplateId();
        List<String> deviceCodes = requestVO.getDeviceCodes();
        if (templateId == null) {
            throw new BusinessException("模板ID不能为空！");
        }
        Integer tenantId = SecurityUtils.getTenantId();

        LambdaQueryWrapper<MeetingTemplate> lambdaQuery = new LambdaQueryWrapper<>();
        lambdaQuery.eq(MeetingTemplate::getId, templateId)
                .eq(MeetingTemplate::getTenantId, tenantId);
        MeetingTemplate template = baseMapper.selectOne(lambdaQuery);
        if (template == null) {
            throw new BusinessException("模板不存在！");
        }

        LambdaUpdateWrapper<MeetingDevice> unwrap = new LambdaUpdateWrapper<>();
        unwrap.eq(MeetingDevice::getTenantId, tenantId);
        if (deviceCodes != null && !deviceCodes.isEmpty()) {
            unwrap.in(MeetingDevice::getDeviceCode, deviceCodes);
        }
        MeetingDevice updater = new MeetingDevice();
        updater.setTemplateId(templateId);
        meetingDeviceMapper.update(updater, unwrap);
    }
}
