package com.haha.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.annotation.Log;
import com.haha.common.constant.SyncConstants;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.Result;
import com.haha.entity.SyncRecord;
import com.haha.service.DataSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 数据同步控制器
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/sync")
public class DataSyncController {

    private final DataSyncService dataSyncService;

    /**
     * 同步设备数据
     * 从哈哈平台拉取设备列表并存储到本地数据库
     */
    @RequirePermission("sync:execute")
    @Log(module = "数据同步", operation = OperationType.SYNC, summary = "同步设备数据")
    @PostMapping("/devices")
    public Result<SyncRecord> syncDevices() {
        try {
            // 获取当前登录用户信息
            Long operatorId = StpUtil.getLoginIdAsLong();
            String operatorName = StpUtil.getLoginIdAsString();
            
            // 尝试从Session中获取用户名
            try {
                Object nickname = StpUtil.getSession().get("nickname");
                if (nickname != null) {
                    operatorName = nickname.toString();
                }
            } catch (Exception e) {
                log.debug("获取用户昵称失败，使用默认值");
            }

            SyncRecord record = dataSyncService.syncDevices(operatorId, operatorName);
            
            if (record.getStatus() == SyncConstants.STATUS_SYNC_FAILED) {
                return Result.error("同步失败: " + record.getErrorMessage());
            }
            return Result.success(record);
        } catch (Exception e) {
            log.error("同步设备数据失败", e);
            return Result.error("同步失败: " + e.getMessage());
        }
    }

    /**
     * 同步商品数据
     * 从哈哈平台商家商品库拉取商品列表并存储到本地数据库
     */
    @RequirePermission("sync:execute")
    @Log(module = "数据同步", operation = OperationType.SYNC, summary = "同步商品数据")
    @PostMapping("/products")
    public Result<SyncRecord> syncProducts() {
        try {
            // 获取当前登录用户信息
            Long operatorId = StpUtil.getLoginIdAsLong();
            String operatorName = StpUtil.getLoginIdAsString();
            
            // 尝试从Session中获取用户名
            try {
                Object nickname = StpUtil.getSession().get("nickname");
                if (nickname != null) {
                    operatorName = nickname.toString();
                }
            } catch (Exception e) {
                log.debug("获取用户昵称失败，使用默认值");
            }

            SyncRecord record = dataSyncService.syncProducts(operatorId, operatorName);
            
            if (record.getStatus() == SyncConstants.STATUS_SYNC_FAILED) {
                return Result.error("同步失败: " + record.getErrorMessage());
            }
            return Result.success(record);
        } catch (Exception e) {
            log.error("同步商品数据失败", e);
            return Result.error("同步失败: " + e.getMessage());
        }
    }

    /**
     * 获取同步记录列表
     */
    @RequirePermission("sync:read")
    @GetMapping("/records")
    public Result<Map<String, Object>> getSyncRecords(
            @RequestParam(required = false) String syncType,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = dataSyncService.getSyncRecordList(syncType, status, page, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取同步记录列表失败", e);
            return Result.error("获取同步记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取同步日志列表
     */
    @RequirePermission("sync:read")
    @GetMapping("/logs/{recordId}")
    public Result<Map<String, Object>> getSyncLogs(
            @PathVariable Long recordId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Map<String, Object> result = dataSyncService.getSyncLogList(recordId, page, pageSize);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取同步日志列表失败", e);
            return Result.error("获取同步日志失败: " + e.getMessage());
        }
    }

    /**
     * 获取同步统计信息
     */
    @RequirePermission("sync:read")
    @GetMapping("/statistics")
    public Result<Map<String, Object>> getSyncStatistics() {
        try {
            Map<String, Object> stats = dataSyncService.getSyncStatistics();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取同步统计信息失败", e);
            return Result.error("获取统计信息失败: " + e.getMessage());
        }
    }
}
