package com.ruoyi.info.management.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.hospital.domain.HospitalDepartment;
import com.ruoyi.info.hospital.mapper.HospitalDepartmentMapper;
import com.ruoyi.info.management.domain.ManagementTeacher;
import com.ruoyi.info.management.domain.TeacherDepartmentRel;
import com.ruoyi.info.management.domain.bo.ManagementTeacherBo;
import com.ruoyi.info.management.domain.bo.ManagementTeacherPageReqBo;
import com.ruoyi.info.management.domain.vo.ManagementTeacherVo;
import com.ruoyi.info.management.exception.ManagementTeacherExceptionEnum;
import com.ruoyi.info.management.mapper.ManagementTeacherMapper;
import com.ruoyi.info.management.mapper.TeacherDepartmentRelMapper;
import com.ruoyi.info.management.service.IManagementTeacherService;
import com.ruoyi.info.management.service.ITeacherDepartmentRelService;
import com.ruoyi.info.nursing.domain.bo.EnableStatusBo;
import com.ruoyi.info.nursing.enums.EnableStatusEnum;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;

import static com.ruoyi.common.utils.CollectionUtils.anyMatch;
import static com.ruoyi.common.utils.CollectionUtils.convertList;
import static com.ruoyi.common.utils.CollectionUtils.convertSet;

/**
 * 管理老师信息Service业务层处理
 *
 * @author baifc
 * @date 2025-09-30
 */
@RequiredArgsConstructor
@Service
public class ManagementTeacherServiceImpl implements IManagementTeacherService {

    private final ManagementTeacherMapper baseMapper;

    private final HospitalDepartmentMapper hospitalDepartmentMapper;

    private final TeacherDepartmentRelMapper teacherDepartmentRelMapper;

    private final ITeacherDepartmentRelService teacherDepartmentRelService;
    /**
     * 查询管理老师信息分页
     *
     * @param bo 管理老师信息
     * @return 管理老师信息
     */
    @Override
    public TableDataInfo<ManagementTeacherVo> queryPageList(ManagementTeacherPageReqBo bo, PageQuery pageQuery) {
        Page<ManagementTeacherVo> result = baseMapper.selectVoListPage(bo, pageQuery.build());
        return TableDataInfo.build(result);
    }

    /**
     * 查询管理老师信息列表
     *
     * @param bo 管理老师信息
     * @return 管理老师信息
     */
    @Override
    public List<ManagementTeacherVo> queryList(ManagementTeacherBo bo) {
        LambdaQueryWrapper<ManagementTeacher> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ManagementTeacher> buildQueryWrapper(ManagementTeacherBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ManagementTeacher> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), ManagementTeacher::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getPhoneNumber()), ManagementTeacher::getPhoneNumber, bo.getPhoneNumber());
        lqw.eq(StringUtils.isNotBlank(bo.getSex()), ManagementTeacher::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getEnableStatus()), ManagementTeacher::getEnableStatus, bo.getEnableStatus());
        return lqw;
    }

    /**
     * 查询管理老师信息
     *
     * @param id 管理老师信息主键
     * @return 管理老师信息
     */
    @Override
    public ManagementTeacherVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 详情管理老师信息
     *
     * @param id 管理老师信息主键
     * @return 管理老师信息
     */
    @Override
    public ManagementTeacher loadById(Long id, Boolean tw){
        ManagementTeacher info = this.baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(info) && tw){
            throw new ServiceException(ManagementTeacherExceptionEnum.MANAGEMENT_TEACHER_IS_NOT_EXISTS);
        }
        return info;
    }

    /**
     * 新增管理老师信息
     *
     * @param bo 管理老师信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(ManagementTeacherBo bo) {
        // 参数校验
        validEntityBeforeSave(bo);
        ManagementTeacher add = BeanUtil.toBean(bo, ManagementTeacher.class);

        // 插入管理老师信息
        baseMapper.insert(add);

        if (bo.getDepartmentIds() != null) {
            // 插入管理老师科室关联信息
            List<HospitalDepartment> hospitalDepartments = hospitalDepartmentMapper.selectBatchIds(bo.getDepartmentIds());
            List<TeacherDepartmentRel> teacherDepartmentRelList = new ArrayList<>();
            for (HospitalDepartment hospitalDepartment : hospitalDepartments) {
                TeacherDepartmentRel teacherDepartmentRel = new TeacherDepartmentRel();
                teacherDepartmentRel.setTeacherId(add.getId());
                teacherDepartmentRel.setHospitalId(hospitalDepartment.getHospitalId());
                teacherDepartmentRel.setDepartmentId(hospitalDepartment.getId());
                teacherDepartmentRelList.add(teacherDepartmentRel);
            }
            teacherDepartmentRelMapper.insertBatch(teacherDepartmentRelList);
        }

        return true;
    }

    /**
     * 修改管理老师信息
     *
     * @param bo 管理老师信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(ManagementTeacherBo bo) {
        // 校验参数
        validEntityBeforeSave(bo);

        ManagementTeacher managementTeacher = baseMapper.selectById(bo.getId());
        if (ObjectUtil.isEmpty(managementTeacher)) {
            throw new ServiceException(ManagementTeacherExceptionEnum.MANAGEMENT_TEACHER_IS_NOT_EXISTS);
        }

        ManagementTeacher update = BeanCopyUtils.copy(bo, managementTeacher);
        baseMapper.updateById(update);

        // 删除旧的科室关联信息
        List<TeacherDepartmentRel> teacherDepartmentRelDBList = teacherDepartmentRelService.queryByTeacherId(bo.getId());
        teacherDepartmentRelMapper.deleteBatchIds(convertSet(teacherDepartmentRelDBList, TeacherDepartmentRel::getId));

        // 获取需要插入的科室关联信息
        if (CollUtil.isNotEmpty(bo.getDepartmentIds())) {
            List<HospitalDepartment> hospitalDepartmentList = hospitalDepartmentMapper.selectBatchIds(bo.getDepartmentIds());
            List<TeacherDepartmentRel> teacherDepartmentRelSaveList = convertList(hospitalDepartmentList,
                h -> new TeacherDepartmentRel(bo.getId(), h.getHospitalId(), h.getId())) ;
            teacherDepartmentRelMapper.insertBatch(teacherDepartmentRelSaveList);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     *
     * @param bo 请求参数
     */
    private void validEntityBeforeSave(ManagementTeacherBo bo) {

        //  校验管理老师科室是否重复
        if (CollUtil.isNotEmpty(bo.getDepartmentIds())) {
            List<TeacherDepartmentRel> teacherDepartmentRelList = teacherDepartmentRelService.queryByDepartmentIds(bo.getDepartmentIds());
            if (ObjectUtil.isEmpty(bo.getId())) {
                // 新增
                if (CollUtil.isNotEmpty(teacherDepartmentRelList)) {
                    throw new ServiceException(ManagementTeacherExceptionEnum.MANAGEMENT_TEACHER_DEPARTMENT_CANT_RELATED);
                }
            } else {
                // 修改
                if (anyMatch(teacherDepartmentRelList,
                    t -> !t.getTeacherId().equals(bo.getId()))) {
                    throw new ServiceException(ManagementTeacherExceptionEnum.MANAGEMENT_TEACHER_DEPARTMENT_CANT_RELATED);
                }
            }
        }
    }

    /**
     * 批量删除管理老师信息
     *
     * @param ids 需要删除的管理老师信息主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        baseMapper.deleteBatchIds(ids);

        for (Long id : ids) {
            // 删除旧的科室关联信息
            List<TeacherDepartmentRel> teacherDepartmentRelDBList = teacherDepartmentRelService.queryByTeacherId(id);
            teacherDepartmentRelMapper.deleteBatchIds(convertSet(teacherDepartmentRelDBList, TeacherDepartmentRel::getId));
        }
        return true;
    }

    @Override
    public List<ManagementTeacher> queryByIds(Collection<Long> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    public void updateStatus(EnableStatusBo bo) {
        ManagementTeacher managementTeacher = baseMapper.selectById(bo.getId());
        managementTeacher.setEnableStatus(bo.getEnableStatus());
        managementTeacher.setUpdateTime(new Date());

        baseMapper.updateById(managementTeacher);
    }

    @Override
    public ManagementTeacherVo queryDelById(Long id) {
        return baseMapper.queryDelById(id);
    }

    @Override
    public ManagementTeacherVo getByPhoneNumber(String mobile, boolean isEnable) {
        LambdaQueryWrapper<ManagementTeacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManagementTeacher::getPhoneNumber, mobile);
        if (isEnable) {
            // 只查状态为启用的
            wrapper.eq(ManagementTeacher::getEnableStatus, EnableStatusEnum.ENABLE);
        }
        wrapper.last("limit 1");
        return baseMapper.selectVoOne(wrapper);
    }

}
