package com.fuzamei.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.RegexConstant;
import com.fuzamei.constant.Role;
import com.fuzamei.constant.Statuses;
import com.fuzamei.entity.Box;
import com.fuzamei.entity.Orders;
import com.fuzamei.entity.Params;
import com.fuzamei.entity.Part;
import com.fuzamei.entity.Status;
import com.fuzamei.entity.UserDetail;
import com.fuzamei.service.BoxService;
import com.fuzamei.service.OrderService;
import com.fuzamei.service.OrdersIssueService;
import com.fuzamei.service.PartService;
import com.fuzamei.service.StatusService;
import com.fuzamei.service.UserAuthoricationService;
import com.fuzamei.util.JSONUtil;
import com.fuzamei.util.PageDTO;
import com.fuzamei.util.RandomUtil;
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;
	
	@Autowired
	private PartService partService;
	

	
	private static final String ORDER_ID_PATTERN=RegexConstant.ORDER_ID;
	
	@Autowired
	private HttpServletRequest req;

	/**
	 * 
	* @Title: queryOrdersByPlanner
	* @Description: TODO(由计划员查询订单信息)
	{
		"tokenId":"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 Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.PLANNER);
			params.setUserId(Integer.parseInt(userId));
			int page = ValidationUtil.checkMinAndAssignInt(params.getPage(), 1);
			int rowNum = ValidationUtil.checkMinAndAssignInt(params.getRowNum(), 1);
			Long startTime=ValidationUtil.checkAndAssignDefaultLong(params.getStartTime(), 0L);
			Long endTime=ValidationUtil.checkAndAssignDefaultLong(params.getEndTime(), Long.MAX_VALUE);
			params.setStartTime(startTime);
			if(startTime<=endTime) params.setEndTime(endTime);
			else params.setEndTime(Long.MAX_VALUE);
			params.setStartPage((page - 1) * rowNum);
			params.setRowNum(rowNum);
			PageDTO pageDto = ordersIssueService.queryOrdersByPlanner(params);
			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(供应商查询订单信息)
	{
		"tokenId":"",
		"page":"1",
		"orderId":"",
		"boxNo":"",
		"statusId":"",
		"startTime":"",
		"endTime":""
	}
	* @params @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 Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.SUPPLIER);
			params.setUserId(Integer.parseInt(userId));
			int page = ValidationUtil.checkMinAndAssignInt(params.getPage(), 1);
			int rowNum = ValidationUtil.checkMinAndAssignInt(params.getRowNum(), 1);
			Long startTime=ValidationUtil.checkAndAssignDefaultLong(params.getStartTime(), 0L);
			Long endTime=ValidationUtil.checkAndAssignDefaultLong(params.getEndTime(), Long.MAX_VALUE);
			params.setStartTime(startTime);
			if(startTime<=endTime) params.setEndTime(endTime);
			else params.setEndTime(Long.MAX_VALUE);
			params.setStartPage((page - 1) * rowNum);
			params.setRowNum(rowNum);
			PageDTO pageDto = ordersIssueService.queryOrdersBySupplier(params);
			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(供应商点击发货这个动作)
	{
		"tokenId":"xxx",
		"orderId":"",
		"carrierId":""
	}
	* @params @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 Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			ValidationUtil.checkBlankAndAssignString(params.getSign());//前端签名非空校验
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.SUPPLIER);
			params.setUserId(Integer.parseInt(userId));
			ValidationUtil.checkAndAssignLong(params.getSendTime());
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(params.getCarrierId()), Role.CARRIER);
			Orders order = orderService.queryFullOrderByOrderId(ValidationUtil.checkAndAssignInt(params.getOrderId()));
			if(order==null) throw new RuntimeException("订单不存在");
			if(!Statuses.UNSEND.equals(order.getStatusId())) throw new RuntimeException(HintMSG.ILLEGAL);
			if(!params.getUserId().equals(order.getSupplierId())) throw new RuntimeException(HintMSG.NO_AUTH);
			ordersIssueService.consignment(params);
			return JSONUtil.getJsonMap(200, true, HintMSG.OPERATION_SUCCESS, null);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.OPERATION_FAIL+":"+e.getMessage(), null);
		}
	}
	
	/**
	 * 
	* @Title: generateOrderId
	* @Description: TODO(给前端生成一个订单id号)
	* @param @param params
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年2月5日 下午3:06:09
	* @throws
	 */
	@RequestMapping(value="/generateOrderId",method=RequestMethod.POST)
	public Map<String, Object> generateOrderId(){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.PLANNER);
			String orderId = new SimpleDateFormat("yyMMdd").format(new Date())+RandomUtil.getRandomDigits(3);
			return JSONUtil.getJsonMap(200, true, HintMSG.OPERATION_SUCCESS, orderId);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.OPERATION_FAIL+":"+e.getMessage(), null);
		}
		
	}
	
	
	/**
	 * 
	* @Title: addOrder
	* @Description: TODO(由计划员增加新订单)
	{
		"tokenId":"xxx",
		"orderId":"",
		"supplierId":"",
		"partNo":"",
		"boxNo":"",
		"inboxQty":""
	}
	* @params @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 Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			ValidationUtil.checkBlankAndAssignString(params.getSign());//前端签名非空校验
			ValidationUtil.checkAndAssignInt(params.getOrderId(),RegexConstant.ORDER_ID);
			ValidationUtil.checkAndAssignLong(params.getRequireTime());//======================================>>TODO这里的时间如何保证和前端一致？
			orderService.checkIfHasTheSameId(params.getOrderId());
			params.setUserId(Integer.parseInt(userId));
			UserDetail userDetail = userAuthoricationService.queryUserDetail(ValidationUtil.checkAndAssignInt(userId), Role.PLANNER);//检测当前操作用户权限
			String partNo = ValidationUtil.checkBlankAndAssignString(params.getPartNo());
			partService.checkIfHasThePartNo(partNo);
			ValidationUtil.checkBlankAndAssignString(params.getBoxNo(), RegexConstant.BOX_NO);
			List<UserDetail> users = userDetail.getUsers();
			int supplierId = ValidationUtil.checkAndAssignInt(params.getSupplierId());
			boolean flag=false;
			for (UserDetail user : users) {
				if(user.getUserId().equals(supplierId)){
					flag=true;
					break;
				}
			}
			if(!flag) throw new RuntimeException("查无此供应商");
			ValidationUtil.checkMinAndAssignInt(params.getInboxQty(),0);
			ordersIssueService.addOrder(params);//生成新订单
			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(当用户添加订单时点击供应商列表时显示该计划员下的所有供应商)
	{
		"tokenId":"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(){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			UserDetail userDetail = userAuthoricationService.queryUserDetail(ValidationUtil.checkAndAssignInt(userId), 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(当计划员点击箱号，显示所有箱号)
	{
		"tokenId":"xxx"
	}
	* @params @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 Params params){
		try {
			String userId = params.getTokenId().split("&")[1];
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), 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: showAllPartNo
	* @Description: TODO(当计划员点击零件号，显示所有零件号)
	{
		"tokenId":"xxx"
	}
	* @params @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月25日 下午3:57:17
	* @throws
	 */
	@RequestMapping(value="/showAllPartNo",method=RequestMethod.POST)
	public Map<String, Object> showAllPartNo(){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.PLANNER);//检测当前操作用户权限
			List<Part> partList = partService.queryAllPartInformation();
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, partList);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	
	
	/**
	 * 
	* @Title: orderTracking
	* @Description: TODO(查询订单的跟踪情况)
	{
		"tokenId":"xxx",
		"orderId":""
	}
	* @params @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 Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			UserDetail userDetail = userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId),Role.PLANNER,Role.SUPPLIER);//检测当前操作用户权限
			params.setUserId(Integer.parseInt(userId));
			Orders order = orderService.queryFullOrderByOrderId(ValidationUtil.checkAndAssignInt(params.getOrderId()));
			if(Role.PLANNER.equals(userDetail.getRoleName())){
				if(!params.getUserId().equals(order.getPlannerId())) throw new RuntimeException(HintMSG.NO_AUTH);
			}
			if(Role.SUPPLIER.equals(userDetail.getRoleName())){
				if(!params.getUserId().equals(order.getSupplierId())) throw new RuntimeException(HintMSG.NO_AUTH);
			}
			params.setOrder(order);
			List<Object> list = ordersIssueService.orderTracking(params);
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, list);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	
}
