package org.dromara.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import org.dromara.common.core.domain.R;
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 lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysDept;
import org.dromara.system.mapper.SysDeptMapper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SysWardBo;
import org.dromara.system.domain.vo.SysWardVo;
import org.dromara.system.domain.SysWard;
import org.dromara.system.mapper.SysWardMapper;
import org.dromara.system.service.ISysWardService;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 病区管理Service业务层处理
 *
 * @author Lion Li
 * @date 2025-06-26
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysWardServiceImpl implements ISysWardService {

    private final SysWardMapper baseMapper;
    private final SysDeptMapper deptMapper;

    /**
     * 查询病区管理
     *
     * @param wardId 主键
     * @return 病区管理
     */
    @Override
    public SysWardVo queryById(Long wardId) {
        return baseMapper.selectVoById(wardId);
    }


    @Override
    public R<JSONObject> listUsed() {
        JSONObject deptUsedMap = new JSONObject();
        List<SysWard> sysWardList = baseMapper.selectList(Wrappers.lambdaQuery(SysWard.class)
            .select(SysWard::getDeptId));
        sysWardList.forEach(v -> {
            Arrays.stream(v.getDeptId().split(",")).forEach(deptId -> {
                deptUsedMap.put(deptId, Boolean.TRUE);
            });
        });

        return R.ok(deptUsedMap);
    }

    /**
     * 分页查询病区管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 病区管理分页列表
     */
    @Override
    public TableDataInfo<SysWardVo> queryPageList(SysWardBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysWard> lqw = buildQueryWrapper(bo);
        Page<SysWardVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollUtil.isNotEmpty(result.getRecords())) {
            Set<Long> deptIds = CollUtil.newHashSet();
            result.getRecords().forEach(v -> {
                deptIds.addAll(Arrays.stream(v.getDeptId().split(",")).map(Long::valueOf).collect(Collectors.toSet()));
            });
            Map<String, String> deptMap = deptMapper.selectList(Wrappers.lambdaQuery(SysDept.class)
                .select(SysDept::getDeptId, SysDept::getDeptName)
                .in(SysDept::getDeptId, deptIds)).stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getDeptId()), k2 -> k2.getDeptName(), (k1, k2) -> k1));

            result.getRecords().forEach(v -> {
                v.setDeptName(Arrays.stream(v.getDeptId().split(",")).map(id -> {
                    return deptMap.get(id);
                }).filter(StringUtils::isNotBlank).collect(Collectors.joining(",")));
            });
        }

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的病区管理列表
     *
     * @param bo 查询条件
     * @return 病区管理列表
     */
    @Override
    public List<SysWardVo> queryList(SysWardBo bo) {
        LambdaQueryWrapper<SysWard> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysWard> buildQueryWrapper(SysWardBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysWard> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysWard::getWardId);
        lqw.like(StringUtils.isNotBlank(bo.getWardName()), SysWard::getWardName, bo.getWardName());
        lqw.eq(StringUtils.isNotBlank(bo.getDeptId()), SysWard::getDeptId, bo.getDeptId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysWard::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增病区管理
     *
     * @param bo 病区管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysWardBo bo) {
        SysWard add = MapstructUtils.convert(bo, SysWard.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setWardId(add.getWardId());
        }
        return flag;
    }

    /**
     * 修改病区管理
     *
     * @param bo 病区管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysWardBo bo) {
        SysWard update = MapstructUtils.convert(bo, SysWard.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 校验并批量删除病区管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
