package com.cmeeting.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmeeting.ad.entity.RobotSecurityUser;
import com.cmeeting.ad.util.SecurityUtil;
import com.cmeeting.constant.PermissionPruposeType;
import com.cmeeting.constant.RecordTemplateConstant;
import com.cmeeting.dto.MeetTypeDto;
import com.cmeeting.exception.RobotBaseException;
import com.cmeeting.mapper.primary.MeetTemplateEnableMapper;
import com.cmeeting.mapper.primary.MeetingRecordTemplateMapper;
import com.cmeeting.pojo.*;
import com.cmeeting.service.MeetTypeService;
import com.cmeeting.mapper.primary.MeetTypeMapper;
import com.cmeeting.service.MeetingRecordTemplateService;
import com.cmeeting.service.ModulePermissionService;
import com.cmeeting.service.SysUserSyncService;
import com.cmeeting.vo.AuthVO;
import com.cmeeting.vo.MeetingTypeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【meet_type(会议类型)】的数据库操作Service实现
* @createDate 2025-07-17 10:55:32
*/
@Slf4j
@Service
public class MeetTypeServiceImpl extends ServiceImpl<MeetTypeMapper, MeetType>
    implements MeetTypeService{

    @Autowired
    private MeetTypeMapper meetTypeMapper;
    @Autowired
    private MeetingRecordTemplateMapper meetingRecordTemplateMapper;
    @Autowired
    private MeetTemplateEnableMapper meetTemplateEnableMapper;
    @Resource
    private ModulePermissionService modulePermissionService;
    @Autowired
    private MeetingRecordTemplateService meetingRecordTemplateService;
    @Resource
    private SysUserSyncService sysUserSyncService;

    /**
     * 添加会议类型
     *
     * @param meetingTypeVo 请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(MeetingTypeVo meetingTypeVo) {
        Date now = new Date();

        RobotSecurityUser loginUser = SecurityUtil.getUser();
        // 校验管理员身份
        String role = loginUser.getRole();
        if (!RecordTemplateConstant.TEMPLATE_TYPE_SYSTEM.equals(role)) {
            throw new RobotBaseException("非管理员用户不允许创建会议类型");
        }
        // 校验会议类型名称
        Integer count = meetTypeMapper.selectCount(new LambdaQueryWrapper<MeetType>().eq(MeetType::getName, meetingTypeVo.getName()));
        if (count > 0) {
            throw new RobotBaseException("添加失败。当前会议类型名称已存在。");
        }

        MeetType meetType = new MeetType();
        meetType.setName(meetingTypeVo.getName());
        meetType.setPersonalPermission(meetingTypeVo.getPersonalPermission());
        meetType.setAuthType(meetingTypeVo.getAuthType());
        meetType.setRelId(meetingTypeVo.getRelId());
        meetType.setContent(meetingTypeVo.getContent());
        meetType.setRegex(meetingTypeVo.getRegex());
        meetType.setCreateTime(now);
        meetType.setUpdateTime(now);
        meetType.setCreateUser(String.format("%08d", loginUser.getUserId()));
        meetType.setUpdateUser(String.format("%08d", loginUser.getUserId()));
        meetType.setCreateUserName(loginUser.getUsername());
        meetType.setUpdateUserName(loginUser.getUsername());
        if (meetTypeMapper.insert(meetType) != 0) {
            List<AuthVO.Add> authData = meetingTypeVo.getAuthData();
            if (CollUtil.isNotEmpty(authData)) {
                Long targetId = meetType.getId();
                authData.forEach(e->e.setTargetId(targetId));
                modulePermissionService.auth(authData);
            }
        }

    }

    /**
     * 更新会议类型
     *
     * @param meetingTypeVo 请求参数
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(MeetingTypeVo meetingTypeVo) {
        Date now = new Date();
        RobotSecurityUser loginUser = SecurityUtil.getUser();
        // 校验会议类型名称
        Integer count = meetTypeMapper.selectCount(new LambdaQueryWrapper<MeetType>().eq(MeetType::getName, meetingTypeVo.getName()).ne(MeetType::getId, meetingTypeVo.getId()));
        if (count > 0) {
            throw new RobotBaseException("编辑失败。当前会议类型名称已存在。");
        }

        MeetType meetType = new MeetType();
        meetType.setId(meetingTypeVo.getId());
        meetType.setName(meetingTypeVo.getName());
        meetType.setPersonalPermission(meetingTypeVo.getPersonalPermission());
        meetType.setAuthType(meetingTypeVo.getAuthType());
        meetType.setRelId(meetingTypeVo.getRelId());
        meetType.setContent(meetingTypeVo.getContent());
        meetType.setRegex(meetingTypeVo.getRegex());
        meetType.setUpdateTime(now);
        meetType.setUpdateUser(String.format("%08d", loginUser.getUserId()));
        meetType.setUpdateUserName(loginUser.getUsername());
        if (meetTypeMapper.updateById(meetType) != 0) {
            modulePermissionService.remove(new LambdaQueryWrapper<ModulePermission>()
                    .eq(ModulePermission::getTargetId, meetingTypeVo.getId())
                    .eq(ModulePermission::getPurpose, PermissionPruposeType.TEMPLATE_TYPE_PERMISSION)
            );
            List<AuthVO.Add> authData = meetingTypeVo.getAuthData();
            if (CollUtil.isNotEmpty(authData)) {
                Long targetId = meetType.getId();
                authData.forEach(e->e.setTargetId(targetId));
                modulePermissionService.auth(authData);
            }
        }
    }

    /**
     * 根据id删除会议类型
     *
     * @param id 会议类型id
     */
    @Transactional
    @Override
    public void delete(Long id) {
        // 删除类型
        meetTypeMapper.deleteById(id);
        // 删除模板
        meetingRecordTemplateMapper.delete(new LambdaQueryWrapper<MeetingRecordTemplate>().eq(MeetingRecordTemplate::getMeetingType, id));
        // 删除模板的启用数据
        meetTemplateEnableMapper.delete(new LambdaQueryWrapper<MeetTemplateEnable>().eq(MeetTemplateEnable::getMeetTypeId, id));
        // 重置参考该类型的其他会议类型的rel_id为null
        LambdaUpdateWrapper<MeetType> lambdaUpdate = Wrappers.lambdaUpdate();
        update(lambdaUpdate.eq(MeetType::getRelId, id).eq(MeetType::getIsDel, false).set(MeetType::getRelId, null));
    }

    /**
     * 获取会议类型
     *
     * @return
     */
    @Override
    public List<MeetTypeDto> getMeetTypeList() {
        // 获取当前用户向上的的部门集合
        RobotSecurityUser loginUser = SecurityUtil.getUser();
        List<SysUserSyncCategory> categoryList = sysUserSyncService.getCategoryListByUserId(String.format("%08d", loginUser.getUserId()));
        List<String> parentDeptIdList = categoryList.stream().map(SysUserSyncCategory::getDeptId).collect(Collectors.toList());
        return meetingRecordTemplateService.getMeetTypeList(String.format("%08d", loginUser.getUserId()), parentDeptIdList, loginUser.getRole());
    }


    /**
     * 获取会议类型下拉列表
     *
     * @return
     */
    @Override
    public List<MeetTypeDto> getMeetTypeSelect() {
        return meetTypeMapper.selectMeetTypeSelect();
    }


}




