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.domain.SysUser;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.web.domain.ConsultantResultTemplate;
import org.dromara.web.domain.SuppliesManage;
import org.dromara.web.domain.bo.ConsultantResultTemplateBo;
import org.dromara.web.domain.vo.ConsultantResultTemplateVo;
import org.dromara.web.mapper.ConsultantResultTemplateMapper;
import org.dromara.web.service.IConsultantResultTemplateService;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 会诊结果模板Service业务层处理
 *
 * @author Lion Li
 * @date 2025-07-08
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ConsultantResultTemplateServiceImpl implements IConsultantResultTemplateService {

    private final ConsultantResultTemplateMapper baseMapper;

    private final SysDeptMapper deptMapper;

    private final SysUserMapper userMapper;


    /**
     * 查询会诊结果模板
     *
     * @param id 主键
     * @return 会诊结果模板
     */
    @Override
    public ConsultantResultTemplateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询会诊结果模板列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 会诊结果模板分页列表
     */
    @Override
    public TableDataInfo<ConsultantResultTemplateVo> queryPageList(ConsultantResultTemplateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ConsultantResultTemplate> lqw = buildQueryWrapper(bo);
        Page<ConsultantResultTemplateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<ConsultantResultTemplateVo> templateVoList = result.getRecords();
        List<SysDept> deptlList = deptMapper.selectList(Wrappers.lambdaQuery(SysDept.class).select(SysDept::getDeptId, SysDept::getDeptName));
        Map<Long, String> deptMap = deptlList.stream().collect(Collectors.toMap(k1 -> k1.getDeptId(), k2 -> String.valueOf(k2.getDeptName()), (k1, k2) -> k1));

        List<SysUser> userList = userMapper.selectList(Wrappers.lambdaQuery(SysUser.class).select(SysUser::getUserId, SysUser::getUserName));
        Map<String, String> userMap = userList.stream().collect(Collectors.toMap(k1 -> String.valueOf(k1.getUserId()), k2 -> k2.getUserName(), (k1, k2) -> k1));

        if (null != templateVoList) {
            for (ConsultantResultTemplateVo templateVo : templateVoList) {
                if (null != templateVo.getCreateBy()) {
                    templateVo.setCreateByUser(userMap.get(templateVo.getCreateBy().toString()));
                }
                if (null != templateVo.getUpdateBy()) {
                    templateVo.setUpdateByUser(userMap.get(templateVo.getUpdateBy().toString()));
                }
                if (null != templateVo.getCreateDept()) {
                    templateVo.setCreateDeptName(deptMap.get(templateVo.getCreateDept()));
                }
                if (null != templateVo.getUpdateDept()) {
                    templateVo.setUpdateDeptName(deptMap.get(templateVo.getUpdateDept()));
                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的会诊结果模板列表
     *
     * @param bo 查询条件
     * @return 会诊结果模板列表
     */
    @Override
    public List<ConsultantResultTemplateVo> queryList(ConsultantResultTemplateBo bo) {
        LambdaQueryWrapper<ConsultantResultTemplate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ConsultantResultTemplate> buildQueryWrapper(ConsultantResultTemplateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ConsultantResultTemplate> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(ConsultantResultTemplate::getId);
        lqw.eq(bo.getTemplateTypeId() != null, ConsultantResultTemplate::getTemplateTypeId, bo.getTemplateTypeId());
        lqw.eq(bo.getCreateBy() != null, ConsultantResultTemplate::getCreateBy, bo.getCreateBy());
        if (StringUtils.isNotBlank(bo.getSearchValue())) {
            lqw.and(wrapper -> wrapper.like(ConsultantResultTemplate::getTemplateName, bo.getSearchValue())
                .or().like(ConsultantResultTemplate::getDescription, bo.getSearchValue())
                .or().like(ConsultantResultTemplate::getCreateBy, bo.getSearchValue())
                .or().like(ConsultantResultTemplate::getUpdateBy, bo.getSearchValue()).or());
        }
        return lqw;
    }

    /**
     * 新增会诊结果模板
     *
     * @param bo 会诊结果模板
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ConsultantResultTemplateBo bo) {
        bo.setContent(URLDecoder.decode(new String(Base64.getDecoder().decode(bo.getContentStr()), StandardCharsets.UTF_8)));
        ConsultantResultTemplate add = MapstructUtils.convert(bo, ConsultantResultTemplate.class);
        validEntityBeforeSave(add);
        add.setUpdateDept(bo.getCreateDept());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改会诊结果模板
     *
     * @param bo 会诊结果模板
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ConsultantResultTemplateBo bo) {
        bo.setContent(URLDecoder.decode(new String(Base64.getDecoder().decode(bo.getContentStr()), StandardCharsets.UTF_8)));
        ConsultantResultTemplate update = MapstructUtils.convert(bo, ConsultantResultTemplate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    }

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