package com.friday.custody.service.basicService.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.friday.custody.enums.RetCodeEnum;
import com.friday.custody.req.PublicDataDirectoryReq;
import com.friday.custody.service.basicService.PublicDataDirectoryService;
import com.friday.custody.utils.PageUtils;
import com.friday.custody.utils.Query;
import com.friday.custody.utils.R;
import com.friday.custody.vo.PublicDataDirectoryVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;


import com.friday.custody.dao.PublicDataDirectoryDao;
import com.friday.custody.entity.PublicDataDirectoryEntity;
import org.springframework.util.CollectionUtils;


@Service("publicDataDirectoryService")
public class PublicDataDirectoryServiceImpl extends ServiceImpl<PublicDataDirectoryDao, PublicDataDirectoryEntity> implements PublicDataDirectoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PublicDataDirectoryEntity> page = this.page(
                new Query<PublicDataDirectoryEntity>().getPage(params),
                new QueryWrapper<PublicDataDirectoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R queryList(String params) {
        try {
            PublicDataDirectoryReq queryDictionaryDirectoryReq = JSON.parseObject(params, PublicDataDirectoryReq.class);
            QueryWrapper<PublicDataDirectoryEntity> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(queryDictionaryDirectoryReq.getPublicDataName())){
                queryWrapper.like("public_data_name",queryDictionaryDirectoryReq.getPublicDataName());
            }
            List<PublicDataDirectoryEntity> entities = baseMapper.selectList(queryWrapper);
            List<PublicDataDirectoryVO> vos =entities.stream().map(entity-> PublicDataDirectoryVO.builder()
                    .type(entity.getType())
                    .publicDataName(entity.getPublicDataName())
                    .build()).collect(Collectors.toList());
            return R.ok("查询公用数据目录成功！").put("data", vos);
        } catch (Exception e) {
            log.error("查询公用数据目录失败", e);
            return R.error(RetCodeEnum.SYS_ERROR.getCode(), "查询公用数据目录失败！");
        }
    }

    @Override
    public String queryByType(String type) {
        List<PublicDataDirectoryEntity> entities = baseMapper.selectList(new QueryWrapper<PublicDataDirectoryEntity>().eq("type", type));
        if (!CollectionUtils.isEmpty(entities)) {
            return entities.get(0).getServiceName();
        }
        return null;
    }

}