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

import cn.hutool.core.collection.CollUtil;
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.dispose.sys.dict.mapper.DictItemMapper;
import com.njzscloud.dispose.sys.dict.pojo.entity.DictItemEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 字典条目表
 */
@Slf4j
@Service
public class DictItemService extends ServiceImpl<DictItemMapper, DictItemEntity> implements IService<DictItemEntity> {

    /**
     * 新增
     */
    @Transactional(rollbackFor = Exception.class)
    public void add(DictItemEntity dictItemEntity) {
        Long dictId = dictItemEntity.getDictId();
        String val = dictItemEntity.getVal();
        boolean exists = this.exists(Wrappers.<DictItemEntity>lambdaQuery().eq(DictItemEntity::getDictId, dictId).eq(DictItemEntity::getVal, val));
        Assert.isFalse(exists, () -> Exceptions.clierr("字典项已存在：{}", val));
        Integer sort = dictItemEntity.getSort();
        if (sort == null || sort == 0) {
            Integer maxSort = this.getOne(Wrappers.<DictItemEntity>query().eq("dict_id", dictId).orderByDesc("sort").select("IFNULL(MAX(sort),0) sort")).getSort();
            dictItemEntity.setSort(maxSort + 1);
        } else {
            this.update(Wrappers.<DictItemEntity>lambdaUpdate().eq(DictItemEntity::getDictId, dictId).ge(DictItemEntity::getSort, sort).setIncrBy(DictItemEntity::getSort, 1));
        }

        this.save(dictItemEntity);
    }

    /**
     * 修改
     */
    @Transactional(rollbackFor = Exception.class)
    public void modify(DictItemEntity dictItemEntity) {
        Long id = dictItemEntity.getId();
        DictItemEntity oldData = this.getById(id);
        Assert.notNull(oldData, () -> Exceptions.clierr("为查询到要修改的数据"));

        Long dictId = oldData.getDictId();
        String val = dictItemEntity.getVal();
        if (StrUtil.isNotBlank(val)) {
            boolean exists = this.exists(Wrappers.<DictItemEntity>lambdaQuery().eq(DictItemEntity::getDictId, dictId).eq(DictItemEntity::getVal, val).ne(DictItemEntity::getId, id));
            Assert.isFalse(exists, () -> Exceptions.clierr("字典项已存在：{}", val));
        }

        Integer sort = dictItemEntity.getSort();
        if (sort != null && sort != 0) {
            List<DictItemEntity> list = this.list(Wrappers.<DictItemEntity>lambdaQuery()
                .eq(DictItemEntity::getDictId, dictId)
                .ge(DictItemEntity::getSort, sort)
                .ne(DictItemEntity::getId, id)
                .select(DictItemEntity::getSort, DictItemEntity::getId)
            );
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(item -> item.setSort(sort + 1));
                this.updateBatchById(list);
            }
        }

        this.updateById(dictItemEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public List<String> del(List<Long> ids) {
        List<DictItemEntity> dictItemEntities = listByIds(ids);
        List<String> list = dictItemEntities.stream().map(DictItemEntity::getDictKey).distinct().toList();
        this.removeBatchByIds(ids);
        return list;
    }

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

    /**
     * 分页查询
     */
    public PageResult<DictItemEntity> paging(PageParam pageParam, DictItemEntity dictItemEntity) {
        Long dictId = dictItemEntity.getDictId();
        String val = dictItemEntity.getVal();
        String txt = dictItemEntity.getTxt();
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.<DictItemEntity>lambdaQuery()
            .eq(DictItemEntity::getDictId, dictId)
            .like(StrUtil.isNotBlank(val), DictItemEntity::getVal, val)
            .like(StrUtil.isNotBlank(txt), DictItemEntity::getTxt, txt)
            .orderByAsc(DictItemEntity::getSort)
        ));
    }

}
