package easydo.technology.controller;

import easydo.technology.enums.MESEnum;
import easydo.technology.model.PurchaseOrder;
import easydo.technology.service.PurchaseOrderService;
import easydo.technology.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/purchaseOrder")
public class PurchaseOrderController {

    @Resource
    private PurchaseOrderService purchaseOrderService;

    @RequestMapping(value = "/getPage")
    public Object getPage(@RequestBody Map<String, Object> map) throws Exception {
        Map<String, Object> result = purchaseOrderService.getPage(map);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @RequestMapping(value = "/save")
    public Object save(@RequestBody PurchaseOrder model) throws Exception {
        // 校验用户登录状态
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return new ResponseEntity<>("用户请先登录", HttpStatus.UNAUTHORIZED);
        }
        
        model.setCreateId(userId);
        model.setStatus(MESEnum.PURCHASE_ORDER_OF_STATUS_PENDING.getValue());  // 设置初始状态为待处理
        return new ResponseEntity<>(purchaseOrderService.save(model), HttpStatus.OK);
    }

    @RequestMapping(value = "/update")
    public Object update(@RequestBody PurchaseOrder model) throws Exception {
        // 校验用户登录状态
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return new ResponseEntity<>("用户请先登录", HttpStatus.UNAUTHORIZED);
        }
        
        model.setUpdateId(userId);
        return new ResponseEntity<>(purchaseOrderService.update(model), HttpStatus.OK);
    }

    @RequestMapping(value = "/remove")
    public Object remove(@RequestBody PurchaseOrder model) throws Exception {
        return new ResponseEntity<>(purchaseOrderService.remove(model), HttpStatus.OK);
    }
}
