package com.bc.exam.modules.dict.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bc.exam.core.api.dto.PagingReqDTO;
import com.bc.exam.core.exception.ServiceException;
import com.bc.exam.modules.dict.entity.SysDictData;
import com.bc.exam.modules.dict.entity.SysDictType;
import com.bc.exam.modules.dict.mapper.SysDictTypeMapper;
import com.bc.exam.modules.dict.service.SysDictDataService;
import com.bc.exam.modules.dict.service.SysDictTypeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

/**
 * @Description 描述:码值大类表 服务实现类
 * @Author A贾宇婷034244310
 * @Date 20260615
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {

    @Resource
    private SysDictDataService dictDataService;

    @Override
    public IPage<SysDictType> paging(PagingReqDTO<SysDictType> reqDTO) {
        //创建分页对象
        Page<SysDictType> query = new Page<>(reqDTO.getCurrent(), reqDTO.getSize());
        QueryWrapper<SysDictType> wrapper = new QueryWrapper<>();
        this.page(query, wrapper);
        return query;
    }

    @Override
    public List<SysDictData> getDicDataByCode(String code, Function<String, List<SysDictData>> func){
        QueryWrapper<SysDictType> wrapper = new QueryWrapper<>();
        wrapper.eq("CODE", code);
        SysDictType sysDictType = this.baseMapper.selectOne(wrapper);
        if(sysDictType == null || StrUtil.isBlank(sysDictType.getId())){
            return Collections.emptyList();
        }
        if(sysDictType.getSourceType().equals("1")) {
            return func.apply(code);
        }
        if(StrUtil.isBlank(sysDictType.getSourceSql())){
            return Collections.emptyList();
        }
        return dictDataService.getListBySourceSql(sysDictType.getSourceSql());
    }

    @Override
    public void saveData(SysDictType reqDTO) {
        if (StringUtils.isBlank(reqDTO.getId())) {
            reqDTO.setId(IdWorker.getIdStr());
        }
        if(StrUtil.isBlank(reqDTO.getCode())){
            throw new ServiceException("码值必输!");
        }
        if(StrUtil.isBlank(reqDTO.getSourceType())){
            throw new ServiceException("码值类型必输!");
        }
        if(reqDTO.getSourceType().equals("2") && StrUtil.isBlank(reqDTO.getSourceSql())){
            throw new ServiceException("码值类型为sql时, 码值sql必输!");
        }
        this.saveOrUpdate(reqDTO);
    }
}
