package com.njzscloud.supervisory.sys.dict.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.supervisory.sys.dict.mapper.DictMapper;
import com.njzscloud.supervisory.sys.dict.pojo.DictEntity;
import com.njzscloud.supervisory.sys.dict.pojo.DictItemEntity;
import com.njzscloud.supervisory.sys.dict.pojo.ObtainDictDataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 字典表
 */
@Slf4j
@Service
public class DictService extends ServiceImpl<DictMapper, DictEntity> implements IService<DictEntity> {
    @Autowired
    private DictItemService dictItemService;

    /**
     * 新增
     */
    public void add(DictEntity dictEntity) {
        String dictKey = dictEntity.getDictKey();
        boolean exists = this.exists(Wrappers.<DictEntity>lambdaQuery().eq(DictEntity::getDictKey, dictKey));
        Assert.isFalse(exists, () -> Exceptions.clierr("字典标识重复：{}", dictKey));
        this.save(dictEntity);
    }

    /**
     * 修改
     */
    public void modify(DictEntity dictEntity) {
        this.updateById(dictEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
        dictItemService.remove(Wrappers.<DictItemEntity>lambdaQuery().in(DictItemEntity::getDictId, ids));
    }

    /**
     * 详情
     */
    public DictEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     */
    public PageResult<DictEntity> paging(PageParam pageParam, DictEntity dictEntity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.<DictEntity>lambdaQuery()
                .like(StrUtil.isNotBlank(dictEntity.getDictName()), DictEntity::getDictName, dictEntity.getDictName())));
    }


    public List<ObtainDictDataResult> obtainDictData(String dictKey) {
        return dictItemService.list(Wrappers.<DictItemEntity>lambdaQuery().eq(DictItemEntity::getDictKey, dictKey))
                .stream().map(it -> BeanUtil.copyProperties(it, ObtainDictDataResult.class))
                .collect(Collectors.toList());
    }

}
