package org.dromara.web.service.impl;

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.dromara.system.mapper.SysUserMapper;
import org.dromara.web.domain.EnteralNutritionTemplate;
import org.dromara.web.domain.bo.EnteralNutritionTemplateBo;
import org.dromara.web.domain.vo.EnteralNutritionTemplateVo;
import org.dromara.web.mapper.EnteralNutritionTemplateMapper;
import org.dromara.web.service.IEnteralNutritionTemplateService;
import org.springframework.stereotype.Service;

import java.util.*;

import static org.dromara.common.core.enums.biz.FeeType.*;

/**
 * 肠内处方模板Service业务层处理
 *
 * @author Huanyi
 * @date 2025-08-04
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EnteralNutritionTemplateServiceImpl implements IEnteralNutritionTemplateService {

    private final EnteralNutritionTemplateMapper baseMapper;
    private final SysDeptMapper deptMapper;
    private final SysUserMapper userMapper;

    /**
     * 查询肠内处方模板
     *
     * @param id 主键
     * @return 肠内处方模板
     */
    @Override
    public EnteralNutritionTemplateVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询肠内处方模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 肠内处方模板分页列表
     */
    @Override
    public TableDataInfo<EnteralNutritionTemplateVo> queryPageList(EnteralNutritionTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EnteralNutritionTemplate> lqw = buildQueryWrapper(bo);
        Page<EnteralNutritionTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<EnteralNutritionTemplateVo> records = result.getRecords();

        Map<Long, String> depts = new HashMap<>();
        deptMapper.selectList().forEach(element -> depts.put(element.getDeptId(), element.getDeptName()));

        for (EnteralNutritionTemplateVo record : records)
            record.setPrescriptionDepartmentName(depts.get(record.getPrescriptionId()));

        records.forEach(e -> {
            switch (e.getPrescriptionType()) {
                case "2" -> e.setPrescriptionType(PRE_PACKAGED_PRESCRIPTION.getRemark());
                case "3" -> e.setPrescriptionType(CONFIGURE_PRESCRIPTION.getRemark());
                case "4" -> e.setPrescriptionType(LONG_TERM_PRESCRIPTION.getRemark());
            }
            e.setCreateBy(userMapper.selectVoById(e.getCreateBy()).getName());
            e.setUpdateBy(userMapper.selectVoById(e.getUpdateBy()).getName());
        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的肠内处方模板列表
     *
     * @param bo 查询条件
     * @return 肠内处方模板列表
     */
    @Override
    public List<EnteralNutritionTemplateVo> queryList(EnteralNutritionTemplateBo bo) {
        LambdaQueryWrapper<EnteralNutritionTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EnteralNutritionTemplate> buildQueryWrapper(EnteralNutritionTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<EnteralNutritionTemplate> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(EnteralNutritionTemplate::getId);
        lqw.like(StringUtils.isNotBlank(bo.getTemplateName()), EnteralNutritionTemplate::getTemplateName, bo.getTemplateName());
        lqw.eq(StringUtils.isNotBlank(bo.getTemplateDescription()), EnteralNutritionTemplate::getTemplateDescription, bo.getTemplateDescription());
        lqw.eq(StringUtils.isNotBlank(bo.getPrescriptionType()), EnteralNutritionTemplate::getPrescriptionType, bo.getPrescriptionType());

        List<Long> deptIds = new ArrayList<>();
        deptMapper.selectList(new LambdaQueryWrapper<SysDept>().like(SysDept::getDeptName, bo.getPrescriptionDepartmentName()))
            .forEach(element -> deptIds.add(element.getDeptId()));
        lqw.in(!deptIds.isEmpty(), EnteralNutritionTemplate::getPrescriptionId, deptIds);

        lqw.eq(bo.getType() != null, EnteralNutritionTemplate::getType, bo.getType());
        lqw.eq(bo.getTemplateType() != null, EnteralNutritionTemplate::getTemplateType, bo.getTemplateType());
        lqw.eq(bo.getPrescriptionId() != null, EnteralNutritionTemplate::getPrescriptionId, bo.getPrescriptionId());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), EnteralNutritionTemplate::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), EnteralNutritionTemplate::getStatus, bo.getStatus());
        lqw.eq(bo.getType() != null, EnteralNutritionTemplate::getType, bo.getType());
        return lqw;
    }

    /**
     * 新增肠内处方模板
     *
     * @param bo 肠内处方模板
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EnteralNutritionTemplateBo bo) {
        EnteralNutritionTemplate add = MapstructUtils.convert(bo, EnteralNutritionTemplate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改肠内处方模板
     *
     * @param bo 肠内处方模板
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EnteralNutritionTemplateBo bo) {
        EnteralNutritionTemplate update = MapstructUtils.convert(bo, EnteralNutritionTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public TableDataInfo<EnteralNutritionTemplateVo> listAll() {
        List<EnteralNutritionTemplateVo> result = baseMapper.selectVoList();
        return TableDataInfo.build(result);
    }
}
