package com.emotion.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emotion.entity.Dictionary;
import com.emotion.mapper.DictionaryMapper;
import com.emotion.service.DictionaryService;
import com.emotion.dto.request.dictionary.DictionaryCreateRequest;
import com.emotion.dto.request.dictionary.DictionaryPageRequest;
import com.emotion.dto.request.dictionary.DictionaryUpdateRequest;
import com.emotion.dto.response.dictionary.DictionaryResponse;
import com.emotion.common.PageResult;
import com.emotion.common.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

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

/**
 * 字典Service实现类
 * 
 * @author huazhongmin
 * @date 2025-12-22
 */
@Service
public class DictionaryServiceImpl extends ServiceImpl<DictionaryMapper, Dictionary> implements DictionaryService {

    /**
     * 创建字典
     * 
     * @param request 创建请求
     * @return 创建结果
     */
    @Override
    public Result<DictionaryResponse> createDictionary(DictionaryCreateRequest request) {
        // 检查字典类型+字典编码是否已存在
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getDictType, request.getDictType())
                .eq(Dictionary::getDictCode, request.getDictCode())
                .eq(Dictionary::getIsDeleted, 0);
        if (this.count(queryWrapper) > 0) {
            return Result.error(400, "同一字典类型下字典编码已存在");
        }

        // 创建字典实体
        Dictionary dictionary = new Dictionary();
        BeanUtils.copyProperties(request, dictionary);
        dictionary.setSortOrder(request.getSortOrder() != null ? request.getSortOrder() : 0);

        // 保存字典
        if (this.save(dictionary)) {
            DictionaryResponse response = convertToResponse(dictionary);
            return Result.success(response);
        }
        return Result.error(500, "创建字典失败");
    }

    /**
     * 更新字典
     * 
     * @param request 更新请求
     * @return 更新结果
     */
    @Override
    public Result<DictionaryResponse> updateDictionary(DictionaryUpdateRequest request) {
        // 检查字典是否存在
        Dictionary dictionary = this.getById(request.getId());
        if (dictionary == null || dictionary.getIsDeleted() == 1) {
            return Result.error(400, "字典不存在");
        }

        // 检查字典类型+字典编码是否已存在（排除当前字典）
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getDictType, request.getDictType())
                .eq(Dictionary::getDictCode, request.getDictCode())
                .ne(Dictionary::getId, request.getId())
                .eq(Dictionary::getIsDeleted, 0);
        if (this.count(queryWrapper) > 0) {
            return Result.error(400, "同一字典类型下字典编码已存在");
        }

        // 更新字典实体
        BeanUtils.copyProperties(request, dictionary);

        // 保存更新
        if (this.updateById(dictionary)) {
            DictionaryResponse response = convertToResponse(dictionary);
            return Result.success(response);
        }
        return Result.error(500, "更新字典失败");
    }

    /**
     * 删除字典
     * 
     * @param id 字典ID
     * @return 删除结果
     */
    @Override
    public Result<Void> deleteDictionary(String id) {
        // 检查字典是否存在
        Dictionary dictionary = this.getById(id);
        if (dictionary == null || dictionary.getIsDeleted() == 1) {
            return Result.error(400, "字典不存在");
        }

        // 删除字典（逻辑删除）
        if (this.removeById(id)) {
            return Result.success();
        }
        return Result.error(500, "删除字典失败");
    }

    /**
     * 获取字典详情
     * 
     * @param id 字典ID
     * @return 字典详情
     */
    @Override
    public Result<DictionaryResponse> getDictionary(String id) {
        // 获取字典
        Dictionary dictionary = this.getById(id);
        if (dictionary == null || dictionary.getIsDeleted() == 1) {
            return Result.error(400, "字典不存在");
        }

        // 转换为响应对象
        DictionaryResponse response = convertToResponse(dictionary);
        return Result.success(response);
    }

    /**
     * 分页查询字典
     * 
     * @param request 分页请求
     * @return 分页结果
     */
    @Override
    public Result<PageResult<DictionaryResponse>> listDictionaries(DictionaryPageRequest request) {
        // 构建查询条件
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getIsDeleted, 0);

        // 添加查询条件
        if (request.getDictType() != null && !request.getDictType().isEmpty()) {
            queryWrapper.eq(Dictionary::getDictType, request.getDictType());
        }
        if (request.getDictCode() != null && !request.getDictCode().isEmpty()) {
            queryWrapper.like(Dictionary::getDictCode, request.getDictCode());
        }
        if (request.getDictName() != null && !request.getDictName().isEmpty()) {
            queryWrapper.like(Dictionary::getDictName, request.getDictName());
        }
        if (request.getStatus() != null) {
            queryWrapper.eq(Dictionary::getStatus, request.getStatus());
        }

        // 排序
        queryWrapper.orderByAsc(Dictionary::getDictType).orderByAsc(Dictionary::getSortOrder).orderByAsc(Dictionary::getCreateTime);

        // 分页查询
        Page<Dictionary> page = this.page(new Page<>(request.getCurrent(), request.getSize()), queryWrapper);

        // 转换为响应对象
        List<DictionaryResponse> responseList = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        // 构建分页结果
        PageResult<DictionaryResponse> pageResult = new PageResult<>();
        pageResult.setRecords(responseList);
        pageResult.setCurrent(page.getCurrent());
        pageResult.setSize(page.getSize());
        pageResult.setTotal(page.getTotal());
        pageResult.setPages(page.getPages());

        return Result.success(pageResult);
    }

    /**
     * 根据字典类型查询字典集合
     * 
     * @param dictType 字典类型
     * @return 字典集合
     */
    @Override
    public Result<List<DictionaryResponse>> getDictionariesByType(String dictType) {
        // 构建查询条件
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getDictType, dictType)
                .eq(Dictionary::getIsDeleted, 0)
                .orderByAsc(Dictionary::getSortOrder)
                .orderByAsc(Dictionary::getCreateTime);

        // 查询字典集合
        List<Dictionary> dictionaryList = this.list(queryWrapper);

        // 转换为响应对象
        List<DictionaryResponse> responseList = dictionaryList.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        return Result.success(responseList);
    }

    /**
     * 根据字典类型查询启用的字典集合
     * 
     * @param dictType 字典类型
     * @return 启用的字典集合
     */
    @Override
    public Result<List<DictionaryResponse>> getEnabledDictionariesByType(String dictType) {
        // 构建查询条件
        LambdaQueryWrapper<Dictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dictionary::getDictType, dictType)
                .eq(Dictionary::getStatus, 1)
                .eq(Dictionary::getIsDeleted, 0)
                .orderByAsc(Dictionary::getSortOrder)
                .orderByAsc(Dictionary::getCreateTime);

        // 查询字典集合
        List<Dictionary> dictionaryList = this.list(queryWrapper);

        // 转换为响应对象
        List<DictionaryResponse> responseList = dictionaryList.stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        return Result.success(responseList);
    }

    /**
     * 实体转换为响应对象
     * 
     * @param dictionary 字典实体
     * @return 字典响应对象
     */
    private DictionaryResponse convertToResponse(Dictionary dictionary) {
        DictionaryResponse response = new DictionaryResponse();
        // 基础字段映射
        response.setId(dictionary.getId());
        response.setDictType(dictionary.getDictType());
        response.setDictCode(dictionary.getDictCode());
        response.setDictName(dictionary.getDictName());
        response.setDictValue(dictionary.getDictValue());
        response.setSortOrder(dictionary.getSortOrder());
        response.setStatus(dictionary.getStatus());
        response.setCreateBy(dictionary.getCreateBy());
        response.setUpdateBy(dictionary.getUpdateBy());
        response.setRemarks(dictionary.getRemarks());
        
        // 转换时间类型
        if (dictionary.getCreateTime() != null) {
            response.setCreateTime(dictionary.getCreateTime().toString());
        }
        if (dictionary.getUpdateTime() != null) {
            response.setUpdateTime(dictionary.getUpdateTime().toString());
        }
        
        return response;
    }
}