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.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.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

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

    @Autowired
    private 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", "inventory_tally".equals(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("没有需要同步的记录");
            }

            List<CheckinRecord> records = new java.util.ArrayList<>();
            for (Map<String, Object> data : recordsData) {
                CheckinRecord record = new CheckinRecord();
                record.setCheckinType((String) data.get("type"));
                record.setUserId(StpUtil.getLoginIdAsLong());
                record.setUserName((String) data.get("userName"));
                record.setUserNo((String) data.get("userNo"));
                record.setShopId(data.get("shopId") != null ? Long.valueOf(data.get("shopId").toString()) : null);
                record.setDeviceId((String) data.get("deviceId"));

                @SuppressWarnings("unchecked")
                Map<String, Object> location = (Map<String, Object>) data.get("location");
                if (location != null) {
                    record.setLatitude(new java.math.BigDecimal(location.get("latitude").toString()));
                    record.setLongitude(new java.math.BigDecimal(location.get("longitude").toString()));
                    record.setAddress((String) location.get("address"));
                    record.setAccuracy(location.get("accuracy") != null ? Integer.valueOf(location.get("accuracy").toString()) : null);
                }

                @SuppressWarnings("unchecked")
                List<Map<String, Object>> photos = (List<Map<String, Object>>) data.get("photos");
                if (photos != null) {
                    record.setPhotos(com.alibaba.fastjson2.JSON.toJSONString(photos));
                }

                record.setRemark((String) data.get("remark"));
                record.setOfflineId((String) data.get("offlineId"));
                record.setStatus("pending");

                String createdAt = (String) data.get("createdAt");
                if (createdAt != null) {
                    try {
                        record.setCheckinTime(java.time.LocalDateTime.parse(createdAt.replace(" ", "T")));
                        record.setCreateTime(record.getCheckinTime());
                    } catch (Exception e) {
                        record.setCheckinTime(java.time.LocalDateTime.now());
                        record.setCreateTime(java.time.LocalDateTime.now());
                    }
                } else {
                    record.setCheckinTime(java.time.LocalDateTime.now());
                    record.setCreateTime(java.time.LocalDateTime.now());
                }

                records.add(record);
            }

            Map<String, Object> result = checkinRecordService.syncOfflineCheckins(records);
            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());
        }
    }
}
