package com.zksy.web.controller.dispatch;

import com.zksy.common.annotation.Anonymous;
import com.zksy.common.annotation.Log;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.enums.BusinessType;
import com.zksy.common.utils.SecurityUtils;
import com.zksy.dispatch.domain.DisPlanMatchRecord;
import com.zksy.dispatch.dto.PlanMatchDTO;
import com.zksy.dispatch.dto.PlanMatchResultVO;
import com.zksy.dispatch.service.DisPlanLibraryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/dispatch/plan-library")
@Api(tags = "数字预案库匹配")
public class DisPlanLibraryController {

    @Autowired
    private DisPlanLibraryService service;

    @GetMapping("/list")
    @ApiOperation("查询数字预案库全部预案")
    @Anonymous
    public AjaxResult list() {
        return AjaxResult.success(service.listAll());
    }

    @PostMapping("/match")
    @ApiOperation("按事件条件加权匹配预案")
    @Log(title = "匹配应急预案", businessType = BusinessType.OTHER)
    public AjaxResult match(@RequestBody PlanMatchDTO dto) {
        List<PlanMatchResultVO> results = service.match(dto, currentUser());
        return AjaxResult.success(results);
    }

    @PostMapping("/matchByTopic")
    @ApiOperation("按专题匹配预案")
    @Log(title = "专题匹配应急预案", businessType = BusinessType.OTHER)
    public AjaxResult matchByTopic(@RequestBody PlanMatchDTO dto) {
        List<PlanMatchResultVO> results = service.matchByTopic(dto.getTopic(), currentUser());
        return AjaxResult.success(results);
    }

    @GetMapping("/history")
    @ApiOperation("查询最近匹配记录")
    @Anonymous
    public AjaxResult history(@RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        return AjaxResult.success(service.getHistory(limit));
    }

    @PostMapping("/apply")
    @ApiOperation("应用预案")
    @Log(title = "应用应急预案", businessType = BusinessType.OTHER)
    public AjaxResult apply(@RequestBody PlanMatchDTO dto) {
        if (dto.getPlanId() == null) {
            return AjaxResult.error("预案ID不能为空");
        }
        return AjaxResult.success("预案应用成功");
    }

    /**
     * 获取当前登录用户名，未登录时返回null
     */
    private String currentUser() {
        try {
            return SecurityUtils.getUsername();
        } catch (Exception e) {
            return null;
        }
    }
}
