package com.fuzamei.web;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fuzamei.constant.HintMSG;
import com.fuzamei.constant.Role;
import com.fuzamei.constant.Status;
import com.fuzamei.entity.Box;
import com.fuzamei.entity.Orders;
import com.fuzamei.entity.Param;
import com.fuzamei.entity.UserDetail;
import com.fuzamei.service.BoxService;
import com.fuzamei.service.OrderService;
import com.fuzamei.service.OrdersIssueService;
import com.fuzamei.service.UserAuthoricationService;
import com.fuzamei.util.JSONUtil;
import com.fuzamei.util.PageDTO;
import com.fuzamei.util.ReadConfUtil;
import com.fuzamei.util.ValidationUtil;

@RestController
@RequestMapping("/ordersIssue")
public class OrdersIssueAction {

	@Autowired
	private OrdersIssueService ordersIssueService;
	
	@Autowired
	private UserAuthoricationService userAuthoricationService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private BoxService boxService;
	
	private static final Integer ROWNUM=Integer.parseInt(ReadConfUtil.getProperty("rowNum"));
	
	/**
	 * 
	* @Title: queryOrdersByPlanner
	* @Description: TODO(由计划员查询订单信息)
	{
		"userId":"xxx",
		"page":"1",
		"supplierName":"",
		"boxNo":"",
		"startTime":"",
		"endTime":""
	}
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月24日 下午8:58:24
	* @throws
	 */
	@RequestMapping(value="/queryOrdersByPlanner",method=RequestMethod.POST)
	public Map<String, Object> queryOrdersByPlanner(@RequestBody Param param){
		try {
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(param.getUserId()), Role.PLANNER);
			int page = ValidationUtil.checkMinAndAssignInt(param.getPage(), 1);
			Long startTime=ValidationUtil.checkAndAssignDefaultLong(param.getStartTime(), 0L);
			Long endTime=ValidationUtil.checkAndAssignDefaultLong(param.getEndTime(), Long.MAX_VALUE);
			param.setStartTime(startTime);
			if(startTime<=endTime) param.setEndTime(endTime);
			else param.setEndTime(Long.MAX_VALUE);
			param.setStartPage((page - 1) * ROWNUM);
			param.setRowNum(ROWNUM);
			PageDTO pageDto = ordersIssueService.queryOrdersByPlanner(param);
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, pageDto);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	/**
	 * 
	* @Title: queryOrdersBySupplier
	* @Description: TODO(供应商查询订单信息)
	{
		"userId":"",
		"page":"1",
		"orderId":"",
		"boxNo":"",
		"statusId":"",
		"startTime":"",
		"endTime":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月26日 上午10:34:41
	* @throws
	 */
	@RequestMapping(value="/queryOrdersBySupplier",method=RequestMethod.POST)
	public Map<String, Object> queryOrdersBySupplier(@RequestBody Param param){
		try {
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(param.getUserId()), Role.SUPPLIER);
			int page = ValidationUtil.checkMinAndAssignInt(param.getPage(), 1);
			Long startTime=ValidationUtil.checkAndAssignDefaultLong(param.getStartTime(), 0L);
			Long endTime=ValidationUtil.checkAndAssignDefaultLong(param.getEndTime(), Long.MAX_VALUE);
			param.setStartTime(startTime);
			if(startTime<=endTime) param.setEndTime(endTime);
			else param.setEndTime(Long.MAX_VALUE);
			param.setStartPage((page - 1) * ROWNUM);
			param.setRowNum(ROWNUM);
			PageDTO pageDto = ordersIssueService.queryOrdersBySupplier(param);
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, pageDto);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	/**
	 * 
	* @Title: Consignment
	* @Description: TODO(供应商点击发货这个动作)
	{
		"userId":"xxx",
		"orderId":"",
		"carrierId":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月26日 上午11:07:58
	* @throws
	 */
	@RequestMapping(value="/consignment",method=RequestMethod.POST)
	public Map<String, Object> consignment(@RequestBody Param param){
		try {
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(param.getUserId()), Role.SUPPLIER);
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(param.getCarrierId()), Role.CARRIER);
			Orders order = orderService.queryFullOrderByOrderId(ValidationUtil.checkAndAssignInt(param.getOrderId()));
			if(order==null) throw new RuntimeException("订单不存在");
			if(!Status.UNSEND.equals(order.getStatusId())) throw new RuntimeException(HintMSG.ILLEGAL);
			if(!param.getUserId().equals(order.getSupplierId())) throw new RuntimeException(HintMSG.NO_AUTH);
			ordersIssueService.consignment(param);
			return JSONUtil.getJsonMap(200, true, HintMSG.OPERATION_SUCCESS, null);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.OPERATION_FAIL+":"+e.getMessage(), null);
		}
	}
	
	/**
	 * 
	* @Title: addOrder
	* @Description: TODO(由计划员增加新订单)
	{
		"userId":"xxx",
		"orderId":"",
		"supplierId":"",
		"partNo":"",
		"boxNo":"",
		"inboxQty":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月25日 下午1:58:45
	* @throws
	 */
	@RequestMapping(value="/addOrder",method=RequestMethod.POST)
	public Map<String, Object> addOrder(@RequestBody Param param){
		try {
			orderService.checkIfHasTheSameId(ValidationUtil.checkAndAssignInt(param.getOrderId()));
			UserDetail userDetail = userAuthoricationService.queryUserDetail(ValidationUtil.checkAndAssignInt(param.getUserId()), Role.PLANNER);//检测当前操作用户权限
			List<UserDetail> users = userDetail.getUsers();
			int supplierId = ValidationUtil.checkAndAssignInt(param.getSupplierId());
			boolean flag=false;
			for (UserDetail user : users) {
				if(user.getUserId().equals(supplierId)){
					flag=true;
					break;
				}
			}
			if(!flag) throw new RuntimeException("查无此供应商");
			boxService.checkIfHasTheBoxNo(ValidationUtil.checkBlankAndAssignString(param.getBoxNo()));//检测箱号是否存在
			ValidationUtil.checkAndAssignInt(param.getInboxQty());
			ordersIssueService.addOrder(param);//生成新订单
			return JSONUtil.getJsonMap(200, true, HintMSG.OPERATION_SUCCESS, null);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.OPERATION_FAIL+":"+e.getMessage(), null);
		}
	}
	
	/**
	 * 
	* @Title: showSuppliersUnderPlanner
	* @Description: TODO(当用户添加订单时点击供应商列表时显示该计划员下的所有供应商)
	{
		"userId":"xxx"
	}
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月25日 下午3:24:56
	* @throws
	 */
	@RequestMapping(value="/showSuppliersUnderPlanner",method=RequestMethod.POST)
	public Map<String, Object> showSuppliersUnderPlanner(@RequestBody Param param){
		try {
			UserDetail userDetail = userAuthoricationService.queryUserDetail(ValidationUtil.checkAndAssignInt(param.getUserId()), Role.PLANNER);//检测当前操作用户权限
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, userDetail.getUsers());
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	
	/**
	 * 
	* @Title: showAllBoxNo
	* @Description: TODO(当计划员点击箱号，显示所有箱号)
	{
		"userId":"xxx"
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月25日 下午3:57:17
	* @throws
	 */
	@RequestMapping(value="/showAllBoxNo",method=RequestMethod.POST)
	public Map<String, Object> showAllBoxNo(@RequestBody Param param){
		try {
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(param.getUserId()), Role.PLANNER);//检测当前操作用户权限
			List<Box> boxList = boxService.queryAllBoxInformation();
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, boxList);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	/**
	 * 
	* @Title: orderTracking
	* @Description: TODO(查询订单的跟踪情况)
	{
		"userId":"xxx",
		"orderId":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月25日 下午7:41:16
	* @throws
	 */
	@RequestMapping(value="/orderTracking",method=RequestMethod.POST)
	public Map<String, Object> orderTracking(@RequestBody Param param){
		try {
			UserDetail userDetail = userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(param.getUserId()),Role.PLANNER,Role.SUPPLIER);//检测当前操作用户权限
			Orders order = orderService.queryFullOrderByOrderId(ValidationUtil.checkAndAssignInt(param.getOrderId()));
			if(Role.PLANNER.equals(userDetail.getRoleName())){
				if(!param.getUserId().equals(order.getPlannerId())) throw new RuntimeException(HintMSG.NO_AUTH);
			}
			if(Role.SUPPLIER.equals(userDetail.getRoleName())){
				if(!param.getUserId().equals(order.getSupplierId())) throw new RuntimeException(HintMSG.NO_AUTH);
			}
			param.setOrder(order);
			Map<String, Object> map = ordersIssueService.orderTracking(param);
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, map);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	
}
