package com.lesingle.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.common.enums.ErrorCode;
import com.lesingle.common.exception.BusinessException;
import com.lesingle.common.result.PageResult;
import com.lesingle.modules.sys.dto.CreateDictDto;
import com.lesingle.modules.sys.entity.SysDict;
import com.lesingle.modules.sys.entity.SysDictItem;
import com.lesingle.modules.sys.mapper.SysDictItemMapper;
import com.lesingle.modules.sys.mapper.SysDictMapper;
import com.lesingle.modules.sys.service.ISysDictService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysDictServiceImpl extends ServiceImpl<SysDictMapper, SysDict> implements ISysDictService {

    private final SysDictItemMapper dictItemMapper;

    @Override
    @Transactional
    public SysDict createDict(CreateDictDto dto, Long tenantId) {
        log.info("开始创建字典，编码：{}，租户：{}", dto.getCode(), tenantId);
        SysDict dict = new SysDict();
        dict.setTenantId(tenantId);
        dict.setName(dto.getName());
        dict.setCode(dto.getCode());
        dict.setDescription(dto.getDescription());
        save(dict);

        // 创建字典项
        if (dto.getItems() != null) {
            for (CreateDictDto.DictItemDto itemDto : dto.getItems()) {
                SysDictItem item = new SysDictItem();
                item.setDictId(dict.getId());
                item.setLabel(itemDto.getLabel());
                item.setValue(itemDto.getValue());
                item.setSort(itemDto.getSort() != null ? itemDto.getSort() : 0);
                dictItemMapper.insert(item);
            }
        }

        return findDetail(dict.getId(), tenantId);
    }

    @Override
    public PageResult<SysDict> findAll(Long page, Long pageSize, Long tenantId) {
        IPage<SysDict> result = baseMapper.selectPage(
                new Page<>(page, pageSize),
                new LambdaQueryWrapper<SysDict>()
                        .eq(tenantId != null, SysDict::getTenantId, tenantId)
                        .eq(SysDict::getValidState, 1)
                        .orderByDesc(SysDict::getCreateTime));

        // 为每个字典加载字典项
        for (SysDict dict : result.getRecords()) {
            loadItems(dict);
        }

        return PageResult.from(result);
    }

    @Override
    public SysDict findByCode(String code, Long tenantId) {
        SysDict dict = getOne(new LambdaQueryWrapper<SysDict>()
                .eq(SysDict::getCode, code)
                .eq(SysDict::getTenantId, tenantId)
                .eq(SysDict::getValidState, 1), false);
        if (dict == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "字典不存在");
        }
        loadItems(dict);
        return dict;
    }

    @Override
    public SysDict findDetail(Long id, Long tenantId) {
        SysDict dict = getById(id);
        if (dict == null) {
            throw BusinessException.of(ErrorCode.NOT_FOUND, "字典不存在");
        }
        loadItems(dict);
        return dict;
    }

    @Override
    @Transactional
    public SysDict updateDict(Long id, CreateDictDto dto, Long tenantId) {
        log.info("开始更新字典，ID：{}", id);
        SysDict dict = new SysDict();
        dict.setId(id);
        if (dto.getName() != null) dict.setName(dto.getName());
        if (dto.getCode() != null) dict.setCode(dto.getCode());
        if (dto.getDescription() != null) dict.setDescription(dto.getDescription());
        updateById(dict);

        // 更新字典项（如果提供）
        if (dto.getItems() != null) {
            dictItemMapper.delete(new LambdaQueryWrapper<SysDictItem>().eq(SysDictItem::getDictId, id));
            for (CreateDictDto.DictItemDto itemDto : dto.getItems()) {
                SysDictItem item = new SysDictItem();
                item.setDictId(id);
                item.setLabel(itemDto.getLabel());
                item.setValue(itemDto.getValue());
                item.setSort(itemDto.getSort() != null ? itemDto.getSort() : 0);
                dictItemMapper.insert(item);
            }
        }

        return findDetail(id, tenantId);
    }

    @Override
    public void removeDict(Long id, Long tenantId) {
        log.info("删除字典，ID：{}", id);
        removeById(id);
    }

    private void loadItems(SysDict dict) {
        List<SysDictItem> items = dictItemMapper.selectList(
                new LambdaQueryWrapper<SysDictItem>()
                        .eq(SysDictItem::getDictId, dict.getId())
                        .eq(SysDictItem::getValidState, 1)
                        .orderByAsc(SysDictItem::getSort));
        dict.setItems(items);
    }
}
