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

import java.util.Collection;
import java.util.Date;
import java.util.List;

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.nursing.domain.NursingCertificate;
import com.ruoyi.info.nursing.domain.NursingWorker;
import com.ruoyi.info.nursing.domain.bo.EnableStatusBo;
import com.ruoyi.info.nursing.domain.bo.NursingCertificateBo;
import com.ruoyi.info.nursing.domain.bo.NursingWorkerBo;
import com.ruoyi.info.nursing.domain.vo.NursingCertificateVo;
import com.ruoyi.info.nursing.domain.vo.NursingWorkerVo;
import com.ruoyi.info.nursing.enums.EnableStatusEnum;
import com.ruoyi.info.nursing.exception.NursingWorkerExceptionEnum;
import com.ruoyi.info.nursing.mapper.NursingCertificateMapper;
import com.ruoyi.info.nursing.mapper.NursingWorkerMapper;
import com.ruoyi.info.nursing.service.INursingCertificateService;
import com.ruoyi.info.nursing.service.INursingWorkerService;

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

/**
 * 护工信息Service业务层处理
 *
 * @author baifc
 * @date 2025-09-29
 */
@RequiredArgsConstructor
@Service
public class NursingWorkerServiceImpl implements INursingWorkerService {

    private final NursingWorkerMapper baseMapper;

    private final NursingCertificateMapper nursingCertificateMapper;

    private final INursingCertificateService nursingCertificateService;

    /**
     * 查询护工信息分页
     *
     * @param bo 护工信息
     * @return 护工信息
     */
    @Override
    public TableDataInfo<NursingWorkerVo> queryPageList(NursingWorkerBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NursingWorker> lqw = buildQueryWrapper(bo);
        Page<NursingWorkerVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询护工信息列表
     *
     * @param bo 护工信息
     * @return 护工信息
     */
    @Override
    public List<NursingWorkerVo> queryList(NursingWorkerBo bo) {
        LambdaQueryWrapper<NursingWorker> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NursingWorker> buildQueryWrapper(NursingWorkerBo bo) {

        LambdaQueryWrapper<NursingWorker> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), NursingWorker::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getPhoneNumber()), NursingWorker::getPhoneNumber, bo.getPhoneNumber());
        lqw.eq(StringUtils.isEmpty(bo.getSex()), NursingWorker::getSex, bo.getSex());
        lqw.eq(bo.getHospitalId() != null, NursingWorker::getHospitalId, bo.getHospitalId());
        lqw.eq(bo.getOrderReceivingStatus() != null, NursingWorker::getOrderReceivingStatus, bo.getOrderReceivingStatus());
        lqw.eq(bo.getEnableStatus() != null, NursingWorker::getEnableStatus, bo.getEnableStatus());
        lqw.ge(ObjectUtil.isNotNull(bo.getCreateTimeStart()), NursingWorker::getCreateTime, bo.getCreateTimeStart());
        lqw.le(ObjectUtil.isNotNull(bo.getCreateTimeEnd()), NursingWorker::getCreateTime, bo.getCreateTimeEnd());

        return lqw;
    }

    /**
     * 查询护工信息
     *
     * @param id 护工信息主键
     * @return 护工信息
     */
    @Override
    public NursingWorkerVo queryById(Long id){
        NursingWorkerVo info = baseMapper.selectVoById(id);
        if(ObjectUtil.isEmpty(info)){
            throw new ServiceException(NursingWorkerExceptionEnum.NURSING_WORKER_IS_NOT_EXISTS);
        }

        // 获取从业证书相关信息
        List<NursingCertificate> nursingCertificates = nursingCertificateService.queryListByWorkerId(info.getId());
        List<NursingCertificateVo> nursingCertificateList = BeanCopyUtils.copyList(nursingCertificates, NursingCertificateVo.class);
        info.setNursingCertificateList(nursingCertificateList);
        return info;
    }

    /**
     * 详情护工信息
     *
     * @param id 护工信息主键
     * @return 护工信息
     */
    @Override
    public NursingWorker loadById(Long id, Boolean tw){
        NursingWorker info = this.baseMapper.selectById(id);
        if(ObjectUtil.isEmpty(info) && tw){
            throw new ServiceException(NursingWorkerExceptionEnum.NURSING_WORKER_IS_NOT_EXISTS);
        }
        return info;
    }

    /**
     * 新增护工信息
     *
     * @param bo 护工信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insertByBo(NursingWorkerBo bo) {
        NursingWorker add = BeanUtil.toBean(bo, NursingWorker.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        // 从业证书信息添加
        if (ObjectUtil.isNotEmpty(bo.getNursingCertificateList())) {
            for(NursingCertificateBo nursingCertificateBo : bo.getNursingCertificateList()){
                nursingCertificateBo.setWorkerId(add.getId());
            }
            List<NursingCertificate> nursingCertificateList = BeanCopyUtils.copyList(bo.getNursingCertificateList(), NursingCertificate.class);
            nursingCertificateMapper.insertBatch(nursingCertificateList);
        }
        return flag;
    }

    /**
     * 修改护工信息
     *
     * @param bo 护工信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(NursingWorkerBo bo) {
        NursingWorker nursingWorker = baseMapper.selectById(bo.getId());
        NursingWorker update = BeanCopyUtils.copy(bo, nursingWorker);
        validEntityBeforeSave(update);

        // 修改护工信息
        baseMapper.updateById(update);

        // 删除旧从业证书信息
        nursingCertificateService.deleteByWorkerId(bo.getId());

        // 新增从业证书信息
        if (ObjectUtil.isNotEmpty(bo.getNursingCertificateList())) {
            for (NursingCertificateBo nursingCertificateBo : bo.getNursingCertificateList()) {
                nursingCertificateBo.setWorkerId(bo.getId());
            }
            List<NursingCertificate> nursingCertificateList = BeanCopyUtils.copyList(bo.getNursingCertificateList(), NursingCertificate.class);
            nursingCertificateMapper.insertBatch(nursingCertificateList);
        }
        return true;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(NursingWorker entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除护工信息
     *
     * @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) {
            // 删除从业证书信息
            nursingCertificateService.deleteByWorkerId(id);
        }
        return true;
    }

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

        baseMapper.updateById(nursingWorker);
    }

    @Override
    public NursingWorkerVo getByPhoneNumber(String mobile, boolean isEnable) {
        LambdaQueryWrapper<NursingWorker> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NursingWorker::getPhoneNumber, mobile);
        if (isEnable) {
            wrapper.eq(NursingWorker::getEnableStatus, EnableStatusEnum.ENABLE.getKey());
        }
        wrapper.last("limit 1");
        return baseMapper.selectVoOne(wrapper);
    }

}
