package com.liquidnet.service.sweet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.sweet.entity.SweetLostFoundAdmin;
import com.liquidnet.service.sweet.mapper.SweetLostFoundAdminMapper;
import com.liquidnet.service.sweet.param.SweetLostFoundAdminParam;
import com.liquidnet.service.sweet.service.ISweetLostFoundAdminService;
import com.liquidnet.service.sweet.utils.LostFoundRedisUtils;
import com.liquidnet.service.sweet.vo.SweetLostFoundAdminVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 失物招领管理员服务实现类
 *
 * @author liquidnet
 * @since 2025-01-18
 */
@Service
public class SweetLostFoundAdminServiceImpl extends ServiceImpl<SweetLostFoundAdminMapper, SweetLostFoundAdmin> implements ISweetLostFoundAdminService {

    @Autowired
    private LostFoundRedisUtils lostFoundRedisUtils;

    @Override
    public boolean addAdmin(SweetLostFoundAdminParam admin) {
        String phone = admin.getPhone().trim();
        String performanceId = admin.getPerformanceId().trim();
        Integer authScope = admin.getAuthScope();
        
        if (phone == null || phone.trim().isEmpty()) {
            throw new IllegalArgumentException("手机号不能为空");
        }
        
        if (performanceId == null || performanceId.isEmpty()) {
            throw new IllegalArgumentException("演出ID不能为空");
        }
        
        // 规则1: 检查在当前演出下是否已创建过管理员
        QueryWrapper<SweetLostFoundAdmin> existWrapper = new QueryWrapper<>();
        existWrapper.eq("phone", phone)
                   .eq("performance_id", performanceId)
                   .eq("is_deleted", 0);
        
        if (baseMapper.selectCount(existWrapper) > 0) {
            throw new IllegalStateException("该手机号在当前演出下已存在管理员记录");
        }
        
        // 规则2: 如果创建的是全站管理员，检查该手机号是否已在其他演出下创建过全站管理员
        if (authScope != null && authScope == 2) {
            QueryWrapper<SweetLostFoundAdmin> globalWrapper = new QueryWrapper<>();
            globalWrapper.eq("phone", phone)
                        .eq("auth_scope", 2)
                        .ne("performance_id", performanceId)
                        .eq("is_deleted", 0);
            
            if (baseMapper.selectCount(globalWrapper) > 0) {
                throw new IllegalStateException("该手机号已作为全站管理员存在，不能再次创建");
            }
        }
        
        SweetLostFoundAdmin foundAdmin = SweetLostFoundAdmin.getNew();
        foundAdmin.setAdminId(IDGenerator.nextSnowId());
        foundAdmin.setPhone(phone);
        foundAdmin.setName(admin.getName());
        foundAdmin.setPermissionType(admin.getPermissionType());
        foundAdmin.setAuthScope(admin.getAuthScope());
        foundAdmin.setPerformanceId(performanceId);
        return baseMapper.insert(foundAdmin) > 0;
    }

    @Override
    public boolean editAdmin(SweetLostFoundAdminParam admin) {
        Long id = admin.getId();
        String phone = admin.getPhone().trim();
        String performanceId = admin.getPerformanceId().trim();
        Integer authScope = admin.getAuthScope();
        
        if (id == null) {
            throw new IllegalArgumentException("管理员ID不能为空");
        }
        
        if (phone == null || phone.isEmpty()) {
            throw new IllegalArgumentException("手机号不能为空");
        }
        
        if (performanceId == null || performanceId.isEmpty()) {
            throw new IllegalArgumentException("演出ID不能为空");
        }
        
        // 检查要修改的管理员是否存在
        SweetLostFoundAdmin existingAdmin = baseMapper.selectById(id);
        if (existingAdmin == null || existingAdmin.getIsDeleted() == 1) {
            throw new IllegalStateException("管理员记录不存在或已删除");
        }
        
        // 规则1: 检查修改后的手机号在当前演出下是否已存在（排除自身）
        QueryWrapper<SweetLostFoundAdmin> existWrapper = new QueryWrapper<>();
        existWrapper.eq("phone", phone)
                   .eq("performance_id", performanceId)
                   .ne("id", id)
                   .eq("is_deleted", 0);
        
        if (baseMapper.selectCount(existWrapper) > 0) {
            throw new IllegalStateException("该手机号在当前演出下已存在管理员记录");
        }
        
        // 规则2: 如果修改为全站管理员，检查该手机号是否已在其他演出下创建过全站管理员（排除自身）
        if (authScope != null && authScope == 2) {
            QueryWrapper<SweetLostFoundAdmin> globalWrapper = new QueryWrapper<>();
            globalWrapper.eq("phone", phone)
                        .eq("auth_scope", 2)
                        .ne("id", id)
                        .ne("performance_id", performanceId)
                        .eq("is_deleted", 0);
            
            if (baseMapper.selectCount(globalWrapper) > 0) {
                throw new IllegalStateException("该手机号已作为全站管理员存在，不能再次创建");
            }
        }
        
        SweetLostFoundAdmin foundAdmin = SweetLostFoundAdmin.getNew();
        foundAdmin.setId(id);
        foundAdmin.setPhone(phone);
        foundAdmin.setName(admin.getName());
        foundAdmin.setPermissionType(admin.getPermissionType());
        foundAdmin.setAuthScope(admin.getAuthScope());
        foundAdmin.setPerformanceId(performanceId);

        // 更新缓存
        lostFoundRedisUtils.deleteAdminCache(phone, performanceId);
        if (!phone.trim().equals(existingAdmin.getPhone())) {
            lostFoundRedisUtils.deleteAdminCache(existingAdmin.getPhone(), performanceId);
        }

        return baseMapper.updateById(foundAdmin) > 0;
    }

    @Override
    public boolean deleteAdmin(Long id) {
        // 检查管理员是否存在
        SweetLostFoundAdmin admin = baseMapper.selectById(id);
        if (admin == null) {
            return false;
        }

        // 逻辑删除：更新is_deleted字段为1
        admin.setIsDeleted(1);

        lostFoundRedisUtils.deleteAdminCache(admin.getPhone(), admin.getPerformanceId());

        return baseMapper.updateById(admin) > 0;
    }

    @Override
    public SweetLostFoundAdminVo getAdminDetail(Long id) {
        SweetLostFoundAdmin admin = baseMapper.selectById(id);
        if (admin == null || admin.getIsDeleted() == 1) {
            return null;
        }

        SweetLostFoundAdminVo vo = new SweetLostFoundAdminVo();
        BeanUtils.copyProperties(admin, vo);
        return vo;
    }

    @Override
    public List<SweetLostFoundAdminVo> getAdminList(String performanceId) {
        // 构建查询条件
        QueryWrapper<SweetLostFoundAdmin> queryWrapper = new QueryWrapper<>();

        // 过滤逻辑删除的记录
        queryWrapper.eq("is_deleted", 0);

        // 查询条件：performanceId = 指定演出ID OR authScope = 2(全站)
        queryWrapper.and(wrapper ->
                wrapper.eq("performance_id", performanceId.trim())
                        .or()
                        .eq("auth_scope", 2)
        );

        // 默认按创建时间降序
        queryWrapper.orderByDesc("create_time");

        // 执行查询
        List<SweetLostFoundAdmin> adminList = baseMapper.selectList(queryWrapper);

        // 转换为VO对象
        List<SweetLostFoundAdminVo> voList = adminList.stream()
                .map(admin -> {
                    SweetLostFoundAdminVo vo = new SweetLostFoundAdminVo();
                    BeanUtils.copyProperties(admin, vo);
                    return vo;
                })
                .collect(Collectors.toList());

        return voList;
    }

    @Override
    public SweetLostFoundAdminVo hasPermission(String phone, String performanceId) {
        SweetLostFoundAdminVo adminCache = lostFoundRedisUtils.getAdminCache(phone, performanceId);
        if (adminCache == null) {
            QueryWrapper<SweetLostFoundAdmin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone.trim())
                    .eq("is_deleted", 0);
            queryWrapper.and(wrapper ->
                    wrapper.eq("performance_id", performanceId.trim())
                            .or()
                            .eq("auth_scope", 2)
            );
            SweetLostFoundAdmin admin = baseMapper.selectOne(queryWrapper);
            if (admin == null) {
                return null;
            }
            SweetLostFoundAdminVo vo = new SweetLostFoundAdminVo();
            BeanUtils.copyProperties(admin, vo);
            lostFoundRedisUtils.setAdminCache(phone, performanceId, vo);
            return vo;
        }
        return adminCache;
    }
}