package com.shinsoft.sto.controller.main;

import com.alibaba.fastjson.JSON;
import com.shinsoft.sto.model.main.Material;
import com.shinsoft.sto.service.main.MaterialService;
import com.shinsoft.sto.model.system.ResultJSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/Material")
public class MaterialController {

    @Autowired
    private MaterialService materialService;

    @GetMapping("/query")
    public ResultJSON query(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "50") int rows,
                           @RequestParam(required = false) String material,
                           @RequestParam(required = false) String standard,
                           HttpServletRequest request) {
        try {
            String userId = (String) request.getHeader("userId");
            String belongId = (String) request.getHeader("belongId");
            
            return materialService.query(page, rows, material, standard, userId, belongId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("查询失败：" + ex.getMessage());
        }
    }

    @PostMapping("/save")
    public ResultJSON save(@RequestParam String json,
                          HttpServletRequest request) {
        try {
            String userId = (String) request.getHeader("userId");
            String belongId = (String) request.getHeader("belongId");
            
            Material material = JSON.parseObject(json, Material.class);
            return materialService.save(material, userId, belongId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("保存失败：" + ex.getMessage());
        }
    }

    @PostMapping("/remove")
    public ResultJSON remove(@RequestParam String id,
                            HttpServletRequest request) {
        try {
            String userId = (String) request.getHeader("userId");
            return materialService.remove(id, userId);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("删除失败：" + ex.getMessage());
        }
    }

    @GetMapping("/options")
    public ResultJSON getOptions(HttpServletRequest request) {
        try {
            String belongId = (String) request.getHeader("belongId");
            return ResultJSON.success(materialService.getMaterialOptions(belongId));
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultJSON.error("获取选项失败：" + ex.getMessage());
        }
    }
}