package com.zg.project.wisdom.controller;

import com.zg.common.exception.ServiceException;
import com.zg.common.utils.StringUtils;
import com.zg.framework.web.controller.BaseController;
import com.zg.framework.web.domain.AjaxResult;
import com.zg.framework.web.page.TableDataInfo;
import com.zg.project.wisdom.domain.AgvTaskResult;
import com.zg.project.wisdom.domain.WcsTaskResult;
import com.zg.project.wisdom.domain.dto.AgvDTO;
import com.zg.project.wisdom.domain.dto.OutGoodsDTO;
import com.zg.project.wisdom.service.IAgvTaskResultService;
import com.zg.project.wisdom.service.IWcsTaskResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/wisdom")
public class AgvTaskResultController extends BaseController {

    @Autowired
    private IAgvTaskResultService agvTaskResultService;


    @Autowired
    private IWcsTaskResultService wcsTaskResultService;


    /**
     * AGV任务执行结果回调
     */
    @PostMapping("/agv/callback")
    public AjaxResult receiveCallback(@RequestBody AgvDTO dto) {
        agvTaskResultService.handleAgvCallback(dto);
        return AjaxResult.success("AGV回调接收成功");
    }

    /**
     * WCS 回调接口
     */
    @PostMapping("/wcs/callback")
    public AjaxResult receiveWcsCallback(@RequestBody WcsTaskResult dto) {
        wcsTaskResultService.handleWcsCallback(dto);
        return AjaxResult.success("WCS 回调接收成功");
    }

    /**
     * 查询 AGV 状态
     */
    @PostMapping("/agv/query")
    public AjaxResult queryAgvStatus(@RequestBody AgvDTO dto) {
        String requestId = dto.getRequestId();
        String status = dto.getStatus();

        boolean exists = agvTaskResultService.existsByRequestIdAndStatus(requestId, status);
        int resultCode = exists ? 200 : 201;

        return AjaxResult.success(resultCode);
    }

    /**
     * 检查任务状态（TaskStatus = 1 是否存在）
     *
     * @param taskId 任务ID
     */
    @GetMapping("/wcs/query")
    public AjaxResult checkTaskStatus(@RequestParam("TaskID") String taskId) {
        boolean exists = wcsTaskResultService.checkTaskStatusExists(taskId);
        return AjaxResult.success(exists ? "200" : "201");
    }

    /**
     * 上架
     * @param dto
     * @return
     */
    @PostMapping("/upGoods")
    public AjaxResult upGoods(@RequestBody OutGoodsDTO dto) {
        if (StringUtils.isBlank(dto.getTaskNo())) {
            throw new ServiceException("taskNo 不能为空");
        }
        // 返回 taskId
        String taskId = agvTaskResultService.handleUpGoods(dto.getTaskNo(), dto.getMaterialStatus());
        return AjaxResult.success("上架任务已提交至WCS").put("taskId", taskId);
    }

    /**
     * 下架
     * @param dto
     * @return
     */
    @PostMapping("/outGoods")
    public AjaxResult outGoods(@RequestBody OutGoodsDTO dto) {
        try {
            agvTaskResultService.handleOutGoods(dto);
            return AjaxResult.success("下架任务已提交成功");
        } catch (Exception e) {
            return AjaxResult.error("下架失败：" + e.getMessage());
        }
    }

    /**
     * 查询AGV任务结果列表（分页）
     */
    @GetMapping("/list")
    public TableDataInfo list(AgvTaskResult agvTaskResult) {
        startPage();
        List<AgvTaskResult> list = agvTaskResultService.selectAgvTaskResultList(agvTaskResult);
        return getDataTable(list);
    }

    /**
     * 根据ID查询单个AGV任务结果
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(agvTaskResultService.selectAgvTaskResultById(id));
    }

    /**
     * 新增AGV任务执行结果
     */
    @PostMapping
    public AjaxResult add(@RequestBody AgvTaskResult agvTaskResult) {
        return toAjax(agvTaskResultService.insertAgvTaskResult(agvTaskResult));
    }

    /**
     * 修改AGV任务执行结果
     */
    @PutMapping
    public AjaxResult edit(@RequestBody AgvTaskResult agvTaskResult) {
        return toAjax(agvTaskResultService.updateAgvTaskResult(agvTaskResult));
    }

    /**
     * 批量删除AGV任务执行结果
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(agvTaskResultService.deleteAgvTaskResultByIds(ids));
    }
}
