package com.haha.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.haha.admin.annotation.RequirePermission;
import com.haha.common.constant.CheckinConstants;
import com.haha.entity.dto.CheckinQueryDTO;
import com.haha.entity.dto.CheckinSubmitDTO;
import com.haha.common.annotation.Log;
import com.haha.common.enums.OperationType;
import com.haha.common.vo.Result;
import com.haha.entity.CheckinRecord;
import com.haha.service.CheckinRecordService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 签到管理控制器
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/checkin")
public class CheckinController {

    private final CheckinRecordService checkinRecordService;

    /**
     * 提交签到
     */
    @RequirePermission("checkin:create")
    @Log(module = "签到管理", operation = OperationType.INSERT, summary = "提交签到")
    @PostMapping
    public Result<Map<String, Object>> submitCheckin(@Valid @RequestBody CheckinSubmitDTO dto) {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            String userName = StpUtil.getSession().getString("userName");
            String userNo = StpUtil.getSession().getString("userNo");

            if (userName == null) {
                userName = StpUtil.getLoginIdAsString();
            }
            if (userNo == null) {
                userNo = "N/A";
            }

            CheckinRecord record = checkinRecordService.submitCheckin(dto, userId, userName, userNo);

            Map<String, Object> result = new HashMap<>();
            result.put("id", record.getId());
            result.put("type", record.getCheckinType());
            result.put("typeName", CheckinConstants.getTypeName(record.getCheckinType()));
            result.put("status", record.getStatus());
            result.put("checkinTime", record.getCheckinTime());

            return Result.success("签到成功", result);
        } catch (Exception e) {
            log.error("提交签到失败", e);
            return Result.error("签到失败: " + e.getMessage());
        }
    }

    /**
     * 分页查询签到记录
     */
    @RequirePermission("checkin:read")
    @GetMapping
    public Result<Map<String, Object>> getCheckinList(CheckinQueryDTO query) {
        try {
            IPage<Map<String, Object>> pageResult = checkinRecordService.getCheckinPage(query);

            Map<String, Object> result = new HashMap<>();
            result.put("list", pageResult.getRecords());
            result.put("total", pageResult.getTotal());
            result.put("page", query.getPage());
            result.put("pageSize", query.getPageSize());

            return Result.success(result);
        } catch (Exception e) {
            log.error("查询签到记录失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取签到详情
     */
    @RequirePermission("checkin:read")
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getCheckinDetail(@PathVariable Long id) {
        try {
            Map<String, Object> detail = checkinRecordService.getCheckinDetail(id);
            if (detail == null) {
                return Result.error("签到记录不存在");
            }
            return Result.success(detail);
        } catch (Exception e) {
            log.error("获取签到详情失败", e);
            return Result.error("获取详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取签到统计数据
     */
    @RequirePermission("checkin:read")
    @GetMapping("/stats")
    public Result<Map<String, Object>> getCheckinStats() {
        try {
            Map<String, Object> stats = checkinRecordService.getCheckinStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取签到统计失败", e);
            return Result.error("获取统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取今日签到状态
     */
    @RequirePermission("checkin:read")
    @GetMapping("/today")
    public Result<Map<String, Object>> getTodayCheckin() {
        try {
            Long userId = StpUtil.getLoginIdAsLong();
            Map<String, Object> todayCheckin = checkinRecordService.getTodayCheckin(userId);
            return Result.success(todayCheckin);
        } catch (Exception e) {
            log.error("获取今日签到状态失败", e);
            return Result.error("获取签到状态失败: " + e.getMessage());
        }
    }

    /**
     * 同步离线签到记录
     */
    @RequirePermission("checkin:create")
    @Log(module = "签到管理", operation = OperationType.INSERT, summary = "同步离线签到")
    @PostMapping("/sync")
    public Result<Map<String, Object>> syncOfflineCheckins(@RequestBody Map<String, Object> params) {
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> recordsData = (List<Map<String, Object>>) params.get("records");

            if (recordsData == null || recordsData.isEmpty()) {
                return Result.error("没有需要同步的记录");
            }

            Long userId = StpUtil.getLoginIdAsLong();
            Map<String, Object> result = checkinRecordService.syncOfflineCheckinsFromData(recordsData, userId);
            return Result.success("同步完成", result);
        } catch (Exception e) {
            log.error("同步离线签到失败", e);
            return Result.error("同步失败: " + e.getMessage());
        }
    }

    /**
     * 导出签到记录
     */
    @RequirePermission("checkin:read")
    @GetMapping("/export")
    public Result<String> exportCheckinRecords(CheckinQueryDTO query) {
        try {
            String fileUrl = checkinRecordService.exportCheckinRecords(query);
            return Result.success("导出成功", fileUrl);
        } catch (Exception e) {
            log.error("导出签到记录失败", e);
            return Result.error("导出失败: " + e.getMessage());
        }
    }
}
