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.enums.OperationType;
import com.haha.common.vo.Result;
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<Void> syncDevices() {
        Long operatorId = StpUtil.getLoginIdAsLong();
        String operatorName = getOperatorName();
        dataSyncService.syncDevices(operatorId, operatorName);
        return Result.success("同步任务已启动，正在后台执行，请稍后刷新查看结果");
    }

    /**
     * 同步商品数据（异步后台执行）
     */
    @RequirePermission("sync:execute")
    @Log(module = "数据同步", operation = OperationType.SYNC, summary = "同步商品数据")
    @PostMapping("/products")
    public Result<Void> syncProducts() {
        Long operatorId = StpUtil.getLoginIdAsLong();
        String operatorName = getOperatorName();
        dataSyncService.syncProducts(operatorId, operatorName);
        return Result.success("同步任务已启动，正在后台执行，请稍后刷新查看结果");
    }

    private String getOperatorName() {
        try {
            Object nickname = StpUtil.getSession().get("nickname");
            if (nickname != null) {
                return nickname.toString();
            }
        } catch (Exception e) {
            log.debug("获取用户昵称失败");
        }
        return StpUtil.getLoginIdAsString();
    }

    /**
     * 获取同步记录列表
     */
    @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());
        }
    }
}
