package com.gxwebsoft.app.controller;

import com.gxwebsoft.app.entity.AppTicket;
import com.gxwebsoft.app.entity.AppTicketReply;
import com.gxwebsoft.app.param.AppTicketParam;
import com.gxwebsoft.app.service.AppTicketService;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

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

/**
 * 应用工单控制器
 *
 * @author 科技小王子
 * @since 2026-03-30
 */
@Slf4j
@Tag(name = "应用工单管理")
@RestController
@RequestMapping("/api/app/ticket")
public class AppTicketController extends BaseController {

    @Resource
    private AppTicketService appTicketService;

    // ─── 客户端接口 ────────────────────────────────────────────────

    @Operation(summary = "查询我的工单（分页）")
    @GetMapping("/my")
    public ApiResult<PageResult<AppTicket>> myTickets(AppTicketParam param) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录",null);
        return success(appTicketService.myPage(param, loginUser.getUserId()));
    }

    @Operation(summary = "提交工单")
    @PostMapping("/submit")
    public ApiResult<AppTicket> submit(@RequestBody AppTicket ticket) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录",null);
        try {
            AppTicket result = appTicketService.submit(ticket, loginUser.getUserId());
            return success("工单提交成功", result);
        } catch (Exception e) {
            return fail(e.getMessage(),null);
        }
    }

    @Operation(summary = "关闭工单（提交人）")
    @PutMapping("/{ticketId}/close")
    public ApiResult<?> close(@PathVariable Long ticketId) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录");
        try {
            appTicketService.closeByUser(ticketId, loginUser.getUserId());
            return success("工单已关闭");
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    // ─── 技术端接口 ────────────────────────────────────────────────

    @Operation(summary = "查询所有工单（技术人员）")
    @GetMapping("/list")
    public ApiResult<PageResult<AppTicket>> allTickets(AppTicketParam param) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录",null);
        return success(appTicketService.allPage(param));
    }

    @Operation(summary = "获取工单详情")
    @GetMapping("/{ticketId}")
    public ApiResult<AppTicket> detail(@PathVariable Long ticketId) {
        return success(appTicketService.getById(ticketId));
    }

    @Operation(summary = "更新工单状态（技术人员）")
    @PutMapping("/status")
    public ApiResult<?> updateStatus(@RequestBody Map<String, Object> body) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录");
        Long ticketId = Long.valueOf(body.get("ticketId").toString());
        String status = body.get("status").toString();
        appTicketService.updateStatus(ticketId, status, loginUser.getUserId());
        return success("状态已更新");
    }

    @Operation(summary = "分配处理人（管理员）")
    @PutMapping("/assign")
    public ApiResult<?> assign(@RequestBody Map<String, Object> body) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录");
        Long ticketId = Long.valueOf(body.get("ticketId").toString());
        Integer assigneeId = Integer.valueOf(body.get("assigneeId").toString());
        appTicketService.assign(ticketId, assigneeId);
        return success("分配成功");
    }

    // ─── 回复接口 ─────────────────────────────────────────────────

    @Operation(summary = "获取工单回复列表")
    @GetMapping("/{ticketId}/replies")
    public ApiResult<List<AppTicketReply>> replies(@PathVariable Long ticketId) {
        return success(appTicketService.getReplies(ticketId));
    }

    @Operation(summary = "提交工单回复")
    @PostMapping("/reply")
    public ApiResult<AppTicketReply> reply(@RequestBody AppTicketReply reply) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录",null);
        if (reply.getContent() == null || reply.getContent().trim().isEmpty()) {
            return fail("回复内容不能为空",null);
        }
        try {
            AppTicketReply result = appTicketService.addReply(reply, loginUser.getUserId());
            return success("回复成功", result);
        } catch (Exception e) {
            return fail(e.getMessage(),null);
        }
    }

    // ─── 统计 & 辅助 ─────────────────────────────────────────────

    @Operation(summary = "工单统计数据")
    @GetMapping("/stats")
    public ApiResult<Map<String, Long>> stats(
            @RequestParam(required = false) Long websiteId) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录",null);
        // 技术端不限制用户维度；客户端通过路由区分
        return success(appTicketService.stats(websiteId, null));
    }

    @Operation(summary = "获取技术人员列表（用于分配）")
    @GetMapping("/staff-list")
    public ApiResult<List<Map<String, Object>>> staffList() {
        return success(appTicketService.getTechStaffList());
    }
}
