package com.cim.idm.controller;

import com.cim.idm.exception.GlobalException;
import com.cim.idm.model.dto.PageDto;
import com.cim.idm.model.dto.WareHouseEditDto;
import com.cim.idm.model.dto.storage.StorageAddDto;
import com.cim.idm.model.dto.storage.StorageDelDto;
import com.cim.idm.model.dto.storage.StorageEditDto;
import com.cim.idm.model.dto.storage.StorageSearchDto;
import com.cim.idm.model.po.storage.StorageSpec;
import com.cim.idm.service.IWareHouseService;
import com.cim.idm.utils.AjaxResult;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

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


@RestController
@RequestMapping("/api/wareHouse")
@EnableAutoConfiguration
public class WareHouseController {

	@Resource
	private IWareHouseService wareHouseService;

	/**
	 * 编辑
	 */
	@PostMapping(value = "/edit")
	public AjaxResult edit(@RequestBody WareHouseEditDto wareHouseEditDto) {
		if (wareHouseService.edit(wareHouseEditDto) > 0) {
			return AjaxResult.me().setSuccess(true).setMessage("编辑成功");
		} else {
			return AjaxResult.me().setErrorCode(-1).setMessage("编辑失败");
		}
	}

	@PostMapping(value = "/page")
	public AjaxResult page(@RequestBody PageDto in) {
		return AjaxResult.me().setSuccess(true).setResultObj(wareHouseService.page(in));
	}

	@PostMapping(value = "/addStorage")
	public AjaxResult addStorage(@RequestBody StorageAddDto storageAddDto) {
		// 校验
		if (Objects.nonNull(wareHouseService.get(storageAddDto.getSiteName(), storageAddDto.getStorageName()))) {
			throw new GlobalException("已存在该货位！");
		}
		// 新增
		if (wareHouseService.add(storageAddDto) > 0) {
			return AjaxResult.me().setSuccess(true).setMessage("新增成功");
		} else {
			return AjaxResult.me().setErrorCode(-1).setMessage("新增失败");
		}
	}

	@PostMapping(value = "/editStorage")
	public AjaxResult editStorage(@RequestBody StorageEditDto storageEditDto) {
		if (wareHouseService.editStorage(storageEditDto) > 0) {
			return AjaxResult.me().setSuccess(true).setMessage("编辑成功");
		} else {
			return AjaxResult.me().setErrorCode(-1).setMessage("编辑失败");
		}
	}

	@PostMapping(value = "/delStorage")
	public AjaxResult delStorage(@RequestBody StorageDelDto storageDelDto) {
		if (wareHouseService.delStorage(storageDelDto) > 0) {
			return AjaxResult.me().setSuccess(true).setMessage("删除成功");
		} else {
			return AjaxResult.me().setErrorCode(-1).setMessage("删除失败");
		}
	}

	@PostMapping(value = "/search")
	public AjaxResult search(@RequestBody StorageSearchDto storageSearchDto) {
		return AjaxResult.me().setSuccess(true).setResultObj(wareHouseService.search(storageSearchDto));
	}

	@PostMapping(value = "/getLocation")
	public AjaxResult getLocation(@RequestBody StorageSpec storageSpec) {
		return AjaxResult.me().setSuccess(true).setResultObj(wareHouseService.getLocation(storageSpec.getErpLocation()));
	}
}
