package com.rj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rj.entity.Tenant;
import com.rj.mapper.TenantMapper;
import com.rj.service.ITenantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 租户表 服务实现类
 * </p>
 *
 * @author 系统生成
 * @since 2025-01-XX
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public Map<String, Object> getTenantList(Integer current, Integer size, String tenantCode, 
                                             String tenantName, Integer status, String contactName, 
                                             String contactPhone, String expireStartTime, String expireEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Tenant> page = new Page<>(current, size);
            LambdaQueryWrapper<Tenant> queryWrapper = buildQueryWrapper(tenantCode, tenantName, status, 
                                                                        contactName, contactPhone, 
                                                                        expireStartTime, expireEndTime);
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(Tenant::getCreateTime);
            
            Page<Tenant> tenantPage = this.page(page, queryWrapper);

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

    @Override
    public Map<String, Object> getTenantListWithoutPage(String tenantCode, String tenantName, 
                                                        Integer status, String contactName, 
                                                        String contactPhone, String expireStartTime, 
                                                        String expireEndTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            LambdaQueryWrapper<Tenant> queryWrapper = buildQueryWrapper(tenantCode, tenantName, status, 
                                                                          contactName, contactPhone, 
                                                                          expireStartTime, expireEndTime);
            
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(Tenant::getCreateTime);
            
            List<Tenant> tenantList = this.list(queryWrapper);

            result.put("success", true);
            result.put("message", "查询成功");
            result.put("data", tenantList);
            result.put("total", tenantList.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询异常：" + e.getMessage());
        }
        return result;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<Tenant> buildQueryWrapper(String tenantCode, String tenantName, 
                                                         Integer status, String contactName, 
                                                         String contactPhone, String expireStartTime, 
                                                         String expireEndTime) {
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
        
        // 租户编码（精确查询）
        if (tenantCode != null && !tenantCode.trim().isEmpty()) {
            queryWrapper.eq(Tenant::getTenantCode, tenantCode);
        }
        
        // 租户名称（模糊查询）
        if (tenantName != null && !tenantName.trim().isEmpty()) {
            queryWrapper.like(Tenant::getTenantName, tenantName);
        }
        
        // 状态
        if (status != null) {
            queryWrapper.eq(Tenant::getStatus, status);
        }
        
        // 联系人姓名（模糊查询）
        if (contactName != null && !contactName.trim().isEmpty()) {
            queryWrapper.like(Tenant::getContactName, contactName);
        }
        
        // 联系人电话
        if (contactPhone != null && !contactPhone.trim().isEmpty()) {
            queryWrapper.like(Tenant::getContactPhone, contactPhone);
        }
        
        // 过期时间范围查询
        if (expireStartTime != null && !expireStartTime.trim().isEmpty()) {
            try {
                LocalDateTime startTime = LocalDateTime.parse(expireStartTime, DATE_TIME_FORMATTER);
                queryWrapper.ge(Tenant::getExpireTime, startTime);
            } catch (Exception e) {
                // 如果时间格式解析失败，忽略该条件
            }
        }
        
        if (expireEndTime != null && !expireEndTime.trim().isEmpty()) {
            try {
                LocalDateTime endTime = LocalDateTime.parse(expireEndTime, DATE_TIME_FORMATTER);
                queryWrapper.le(Tenant::getExpireTime, endTime);
            } catch (Exception e) {
                // 如果时间格式解析失败，忽略该条件
            }
        }
        
        return queryWrapper;
    }

    @Override
    public Map<String, Object> addTenant(Tenant tenant) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 验证必填字段
            if (tenant.getTenantCode() == null || tenant.getTenantCode().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "租户编码不能为空");
                return result;
            }
            if (tenant.getTenantName() == null || tenant.getTenantName().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "租户名称不能为空");
                return result;
            }

            // 检查租户编码是否已存在
            LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Tenant::getTenantCode, tenant.getTenantCode());
            long count = this.count(queryWrapper);
            if (count > 0) {
                result.put("success", false);
                result.put("message", "租户编码已存在");
                return result;
            }

            // 生成UUID作为主键
            tenant.setId(tenant.getTenantCode());
            tenant.setUpdateTime(LocalDateTime.now());

            // 设置默认状态为启用
            if (tenant.getStatus() == null) {
                tenant.setStatus(1);
            }

            boolean success = this.save(tenant);
            if (success) {
                result.put("success", true);
                result.put("message", "租户添加成功");
                result.put("data", tenant);
            } else {
                result.put("success", false);
                result.put("message", "租户添加失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "租户添加异常：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> updateTenant(Tenant tenant) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (tenant.getId() == null || tenant.getId().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "租户ID不能为空");
                return result;
            }

            // 检查租户是否存在
            Tenant existingTenant = this.getById(tenant.getId());
            if (existingTenant == null) {
                result.put("success", false);
                result.put("message", "租户不存在");
                return result;
            }

            // 如果修改了租户编码，检查新编码是否已存在
            if (tenant.getTenantCode() != null && !tenant.getTenantCode().equals(existingTenant.getTenantCode())) {
                LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Tenant::getTenantCode, tenant.getTenantCode());
                long count = this.count(queryWrapper);
                if (count > 0) {
                    result.put("success", false);
                    result.put("message", "租户编码已存在");
                    return result;
                }
            }

            // 设置更新时间
            tenant.setUpdateTime(LocalDateTime.now());
            // 不更新创建时间
            tenant.setCreateTime(existingTenant.getCreateTime());

            boolean success = this.updateById(tenant);
            if (success) {
                result.put("success", true);
                result.put("message", "租户信息更新成功");
                result.put("data", tenant);
            } else {
                result.put("success", false);
                result.put("message", "租户信息更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新异常：" + e.getMessage());
        }
        return result;
    }

    @Override
    public Map<String, Object> deleteTenant(String id) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (id == null || id.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "租户ID不能为空");
                return result;
            }

            // 检查租户是否存在
            Tenant tenant = this.getById(id);
            if (tenant == null) {
                result.put("success", false);
                result.put("message", "租户不存在");
                return result;
            }

            boolean success = this.removeById(id);
            if (success) {
                result.put("success", true);
                result.put("message", "租户删除成功");
            } else {
                result.put("success", false);
                result.put("message", "租户删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除异常：" + e.getMessage());
        }
        return result;
    }
}

