package com.aiotagro.cattletrade.business.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aiotagro.cattletrade.business.entity.SysTenant;
import com.aiotagro.cattletrade.business.entity.IotDeviceData;
import com.aiotagro.cattletrade.business.mapper.SysTenantMapper;
import com.aiotagro.cattletrade.business.mapper.IotDeviceDataMapper;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 租户管理控制器
 *
 * @author System
 * @date 2025-01-16
 */
@RestController
@RequestMapping("/sysTenant")
public class SysTenantController {

    private static final Logger logger = LoggerFactory.getLogger(SysTenantController.class);

    @Resource
    private SysTenantMapper tenantMapper;
    
    @Resource
    private IotDeviceDataMapper iotDeviceDataMapper;

    /**
     * 租户列表查询（分页）
     */
    @SaCheckPermission("system:tenant:list")
    @PostMapping("/queryList")
    public AjaxResult queryList(@RequestBody Map<String, Object> params) {
        Integer pageNum = params.get("pageNum") != null ? (Integer) params.get("pageNum") : 1;
        Integer pageSize = params.get("pageSize") != null ? (Integer) params.get("pageSize") : 10;
        String name = (String) params.get("name");

        Page<SysTenant> result = PageHelper.startPage(pageNum, pageSize);
        
        LambdaQueryWrapper<SysTenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysTenant::getIsDelete, 0);
        
        if (name != null && !name.trim().isEmpty()) {
            wrapper.like(SysTenant::getName, name);
        }
        
        wrapper.orderByDesc(SysTenant::getId);
        List<SysTenant> list = tenantMapper.selectList(wrapper);

        // 为每个租户添加设备数量统计
        List<Map<String, Object>> resultList = list.stream().map(tenant -> {
            Map<String, Object> tenantMap = new HashMap<>();
            tenantMap.put("id", tenant.getId());
            tenantMap.put("name", tenant.getName());
            tenantMap.put("mobile", tenant.getMobile());
            tenantMap.put("createTime", tenant.getCreateTime());
            
            // 查询该租户的设备数量统计
            QueryWrapper<IotDeviceData> deviceWrapper = new QueryWrapper<>();
            deviceWrapper.eq("tenant_id", tenant.getId());
            
            // 耳标数量 (device_type = 2)
            deviceWrapper.clear();
            deviceWrapper.eq("tenant_id", tenant.getId()).eq("device_type", 2);
            Long jbqCount = iotDeviceDataMapper.selectCount(deviceWrapper);
            tenantMap.put("jbqCount", jbqCount);
            
            // 项圈数量 (device_type = 4)
            deviceWrapper.clear();
            deviceWrapper.eq("tenant_id", tenant.getId()).eq("device_type", 4);
            Long xqCount = iotDeviceDataMapper.selectCount(deviceWrapper);
            tenantMap.put("xqCount", xqCount);
            
            // 主机数量 (device_type = 1)
            deviceWrapper.clear();
            deviceWrapper.eq("tenant_id", tenant.getId()).eq("device_type", 1);
            Long serverCount = iotDeviceDataMapper.selectCount(deviceWrapper);
            tenantMap.put("serverCount", serverCount);
            
            return tenantMap;
        }).collect(java.util.stream.Collectors.toList());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("rows", resultList);
        resultMap.put("total", result.getTotal());
        
        return AjaxResult.success("操作成功", resultMap);
    }

    /**
     * 新增租户
     */
    @SaCheckPermission("system:tenant:add")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysTenant tenant) {
        tenant.setCreateTime(new Date());
        tenant.setIsDelete(0);
        int rows = tenantMapper.insert(tenant);
        return rows > 0 ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
    }

    /**
     * 更新租户
     */
    @SaCheckPermission("system:tenant:edit")
    @PostMapping("/update")
    public AjaxResult update(@RequestBody SysTenant tenant) {
        int rows = tenantMapper.updateById(tenant);
        return rows > 0 ? AjaxResult.success("更新成功") : AjaxResult.error("更新失败");
    }

    /**
     * 删除租户（逻辑删除）
     * 同时将该租户绑定的所有设备的tenant_id设置为null
     */
    @SaCheckPermission("system:tenant:delete")
    @PostMapping("/delete")
    public AjaxResult delete(@RequestParam Integer id) {
        try {
            // 1. 先查询该租户绑定的设备数量
            QueryWrapper<IotDeviceData> deviceWrapper = new QueryWrapper<>();
            deviceWrapper.eq("tenant_id", id);
            Long deviceCount = iotDeviceDataMapper.selectCount(deviceWrapper);
            
            // 2. 将该租户绑定的所有设备的tenant_id设置为null
            if (deviceCount > 0) {
                LambdaUpdateWrapper<IotDeviceData> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(IotDeviceData::getTenantId, id)
                           .set(IotDeviceData::getTenantId, null)
                           .set(IotDeviceData::getUpdateTime, new Date());
                
                int updateResult = iotDeviceDataMapper.update(null, updateWrapper);
                logger.info("租户 {} 删除时解绑设备数量: {}", id, updateResult);
            }
            
            // 3. 删除租户（逻辑删除）
            SysTenant tenant = new SysTenant();
            tenant.setId(id);
            tenant.setIsDelete(1);
            int rows = tenantMapper.updateById(tenant);
            
            if (rows > 0) {
                String message = deviceCount > 0 ? 
                    String.format("删除成功，同时解绑了 %d 个设备", deviceCount) : 
                    "删除成功";
                return AjaxResult.success(message);
            } else {
                return AjaxResult.error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除租户失败，租户ID: {}", id, e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取租户详情
     */
    @SaCheckPermission("system:tenant:view")
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Integer id) {
        SysTenant tenant = tenantMapper.selectById(id);
        return AjaxResult.success(tenant);
    }

    /**
     * 获取租户分配列表（用于下拉框等）
     */
    @GetMapping("/allotList")
    public AjaxResult allotList() {
        LambdaQueryWrapper<SysTenant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysTenant::getIsDelete, 0);
        wrapper.orderByDesc(SysTenant::getId);
        List<SysTenant> list = tenantMapper.selectList(wrapper);
        return AjaxResult.success(list);
    }
}

