package com.rj.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.rj.common.DictItemConstants;
import com.rj.common.PasswordUtil;
import com.rj.entity.DictItem;
import com.rj.mapper.DictItemMapper;
import com.rj.service.IDictItemService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 字典项/配置项服务实现
 */
@Service
public class DictItemServiceImpl extends ServiceImpl<DictItemMapper, DictItem> implements IDictItemService {

    @Override
    public Map<String, Object> add(DictItem entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getTenantId() == null || entity.getTenantId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "tenantId不能为空");
                return result;
            }
            if (entity.getName() == null || entity.getName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "name不能为空");
                return result;
            }

                String tenantId = entity.getTenantId().trim();
            String name = entity.getName().trim();
            LambdaQueryWrapper<DictItem> dupQ = new LambdaQueryWrapper<DictItem>()
                    .eq(DictItem::getName, name);
            if (this.count(dupQ) > 0) {
                result.put("success", false);
                result.put("message", "该租户下name已存在，不能重复添加");
                return result;
            }
            if (DictItemConstants.QIWEI_CONFIG.equals(name)){
                String rawValue = entity.getValue();
                if (rawValue == null) {
                    rawValue = "";
                }
                entity.setValue(PasswordUtil.encryptReversibleWithDefaultSalt(rawValue));
            }

            entity.setTenantId(tenantId);
            entity.setName(name);
            entity.setId(UUID.randomUUID().toString().replace("-", ""));
            LocalDateTime now = LocalDateTime.now();
            entity.setCreatedTime(now);
            entity.setUpdatedTime(now);
            boolean ok = this.save(entity);
            result.put("success", ok);
            result.put("message", ok ? "添加成功" : "添加失败");
            if (ok) {
                result.put("data", entity);
            }
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "添加异常：" + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> update(DictItem entity) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (entity.getId() == null || entity.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "ID不能为空");
                return result;
            }
            if (DictItemConstants.QIWEI_CONFIG.equals(entity.getName())) {
                String rawValue = entity.getValue();
                if (rawValue == null) {
                    rawValue = "";
                }
                entity.setValue(PasswordUtil.encryptReversibleWithDefaultSalt(rawValue));
            }
            entity.setUpdatedTime(LocalDateTime.now());
            boolean ok = this.updateById(entity);
            result.put("success", ok);
            result.put("message", ok ? "更新成功" : "更新失败");
            if (ok) {
                result.put("data", this.getById(entity.getId()));
            }
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> deleteById(String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean ok = this.removeById(id);
            result.put("success", ok);
            result.put("message", ok ? "删除成功" : "删除失败");
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
            return result;
        }
    }

    @Override
    public Map<String, Object> pageQuery(Integer current,
                                         Integer size,
                                         String tenantId,
                                         String name,
                                         String type,
                                         String microService,
                                         String valueRange) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (current == null || current < 1) {
                current = 1;
            }
            if (size == null || size < 1) {
                size = 10;
            }

            Page<DictItem> page = new Page<>(current, size);
            LambdaQueryWrapper<DictItem> q = new LambdaQueryWrapper<>();
            if (tenantId != null && !tenantId.trim().isEmpty()) {
                q.eq(DictItem::getTenantId, tenantId.trim());
            }
            if (name != null && !name.trim().isEmpty()) {
                q.like(DictItem::getName, name.trim());
            }
            if (type != null && !type.trim().isEmpty()) {
                q.eq(DictItem::getType, type.trim());
            }
            if (microService != null && !microService.trim().isEmpty()) {
                q.eq(DictItem::getMicroService, microService.trim());
            }
            if (valueRange != null && !valueRange.trim().isEmpty()) {
                q.eq(DictItem::getValueRange, valueRange.trim());
            }
            q.orderByDesc(DictItem::getUpdatedTime).orderByDesc(DictItem::getCreatedTime);

            Page<DictItem> data = this.page(page, q);
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", data.getRecords());
            result.put("total", data.getTotal());
            result.put("current", data.getCurrent());
            result.put("size", data.getSize());
            result.put("pages", data.getPages());
            return result;
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
            return result;
        }
    }
}

