package org.dromara.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.SysUserMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SysDoctorVolunteerBo;
import org.dromara.system.domain.vo.SysDoctorVolunteerVo;
import org.dromara.system.domain.SysDoctorVolunteer;
import org.dromara.system.mapper.SysDoctorVolunteerMapper;
import org.dromara.system.service.ISysDoctorVolunteerService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 医生志愿者关联Service业务层处理
 *
 * @author wuzhigang
 * @date 2023-12-21
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysDoctorVolunteerServiceImpl implements ISysDoctorVolunteerService {

    private final SysDoctorVolunteerMapper baseMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询医生志愿者关联
     */
    @Override
    public SysDoctorVolunteerVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询医生志愿者关联列表
     */
    @Override
    public TableDataInfo<SysDoctorVolunteerVo> queryPageList(SysDoctorVolunteerBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysDoctorVolunteer> lqw = buildQueryWrapper(bo);
        Page<SysDoctorVolunteerVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询医生志愿者关联列表
     */
    @Override
    public List<SysDoctorVolunteerVo> queryList(SysDoctorVolunteerBo bo) {
        LambdaQueryWrapper<SysDoctorVolunteer> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysDoctorVolunteer> buildQueryWrapper(SysDoctorVolunteerBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysDoctorVolunteer> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getDoctorUserId() != null, SysDoctorVolunteer::getDoctorUserId, bo.getDoctorUserId());
        lqw.eq(bo.getVolunteerUserId() != null, SysDoctorVolunteer::getVolunteerUserId, bo.getVolunteerUserId());
        return lqw;
    }

    /**
     * 新增医生志愿者关联
     */
    @Override
    public Boolean insertByBo(SysDoctorVolunteerBo bo) {
        SysDoctorVolunteer add = MapstructUtils.convert(bo, SysDoctorVolunteer.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改医生志愿者关联
     */
    @Override
    public Boolean updateByBo(SysDoctorVolunteerBo bo) {
        SysDoctorVolunteer update = MapstructUtils.convert(bo, SysDoctorVolunteer.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysDoctorVolunteer entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除医生志愿者关联
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 医生绑定志愿者
     *
     * @param bo
     * @return
     */
    @Override
    public SysUser bindVolunteer(SysDoctorVolunteerBo bo) {
        LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SysUser::getPhonenumber, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getName()), SysUser::getNickName, bo.getName());
        // 根据手机号和姓名查询用户
        SysUser user = userMapper.selectOne(lqw);
        if(user == null){
            throw new ServiceException("输⼊信息有误，请重新尝试");
        }
        SysDoctorVolunteer add = new SysDoctorVolunteer();

        if(user.getLoginIdentity().equals(UserConstants.LOGIN_IDENTITY_VOLUNTEER)){
            // 医生ID
            add.setDoctorUserId(LoginHelper.getUserId());
            // 志愿者ID
            add.setVolunteerUserId(user.getUserId());
        }else{
            throw new ServiceException("绑定人身份非志愿者，请重新尝试");
        }

        // 查询是否已绑定
        LambdaQueryWrapper<SysDoctorVolunteer> doctorVolunteerLqw = Wrappers.lambdaQuery();
        doctorVolunteerLqw.eq(SysDoctorVolunteer::getDoctorUserId,add.getDoctorUserId());
        doctorVolunteerLqw.eq(SysDoctorVolunteer::getVolunteerUserId,add.getVolunteerUserId());
        List<SysDoctorVolunteer> list = baseMapper.selectList(doctorVolunteerLqw);
        if(list!=null&&list.size()>0){
            throw new ServiceException("绑定关系已存在，请勿重复绑定");
        }

        baseMapper.insert(add);

        return user;
    }

    /**
     * 根据医生userId获取绑定志愿者列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysDoctorVolunteerVo> volunteerList(Long userId) {

        // 根据医生userId查询
        LambdaQueryWrapper<SysDoctorVolunteer> lqw = Wrappers.lambdaQuery();
        lqw.eq( SysDoctorVolunteer::getDoctorUserId, userId);

        return baseMapper.selectVoList(lqw);
    }

    /**
     * 根据志愿者userId获取绑定医生列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysDoctorVolunteerVo> doctorList(Long userId) {
        // 根据志愿者userId查询
        LambdaQueryWrapper<SysDoctorVolunteer> lqw = Wrappers.lambdaQuery();
        lqw.eq( SysDoctorVolunteer::getVolunteerUserId, userId);

        return baseMapper.selectVoList(lqw);
    }

    /**
     * 志愿者绑定医生
     *
     * @param bo
     * @return
     */
    @Override
    public SysUser bindDoctor(SysDoctorVolunteerBo bo) {
        LambdaQueryWrapper<SysUser> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), SysUser::getPhonenumber, bo.getPhone().trim());
        lqw.eq(StringUtils.isNotBlank(bo.getName()), SysUser::getNickName, bo.getName().trim());
        // 根据手机号和姓名查询用户
        SysUser user = userMapper.selectOne(lqw);
        if(user == null){
            throw new ServiceException("输⼊信息有误，请重新尝试");
        }
        SysDoctorVolunteer add = new SysDoctorVolunteer();

        if(user.getLoginIdentity().equals(UserConstants.LOGIN_IDENTITY_DOCTOR)){
            // 医生ID
            add.setDoctorUserId(user.getUserId());
            // 志愿者ID
            add.setVolunteerUserId(LoginHelper.getUserId());
        }else{
            throw new ServiceException("绑定人身份非医生，请重新尝试");
        }

        // 查询是否已绑定
        LambdaQueryWrapper<SysDoctorVolunteer> doctorVolunteerLqw = Wrappers.lambdaQuery();
        doctorVolunteerLqw.eq(SysDoctorVolunteer::getDoctorUserId,add.getDoctorUserId());
        doctorVolunteerLqw.eq(SysDoctorVolunteer::getVolunteerUserId,add.getVolunteerUserId());
        List<SysDoctorVolunteer> list = baseMapper.selectList(doctorVolunteerLqw);
        if(list!=null&&list.size()>0){
            throw new ServiceException("绑定关系已存在，请勿重复绑定");
        }
        baseMapper.insert(add);
        return user;
    }
}
