package com.fuzamei.web;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
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.Orders;
import com.fuzamei.entity.Params;
import com.fuzamei.entity.Status;
import com.fuzamei.entity.UserDetail;
import com.fuzamei.service.CargoConsignService;
import com.fuzamei.service.OrderService;
import com.fuzamei.service.StatusService;
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(path="/cargoConsign")
public class CargoConsignAction {

	@Autowired
	private CargoConsignService cargoConsignService;
	
	@Autowired
	private UserAuthoricationService userAuthoricationService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private StatusService statusService;
	
	@Autowired
	private HttpServletRequest req;
	
	private static final String CARNO_PATTERN =RegexConstant.CAR_NO;
	/**
	 * 
	* @Title: queryOrdersBySupplier
	* @Description: TODO(供应商查询订单信息)
	{
		"tokenId":"xx",
		"page":"1",
		"orderId":"",
		"boxNo":"",
		"statusId":"",
		"startTime":"",
		"endTime":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月26日 上午11:35:13
	* @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 = cargoConsignService.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: queryOrdersByCarrier
	* @Description: TODO(承运商查看订单信息)
	{
		"tokenId":"",
		"page":"1",
		"orderId":"",
		"boxNo":"",
		"statusId":"",
		"startTime":"",
		"endTime":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月26日 下午1:03:33
	* @throws
	 */
	@RequestMapping(value="/queryOrdersByCarrier",method=RequestMethod.POST)
	public Map<String, Object> queryOrdersByCarrier(@RequestBody Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.CARRIER);
			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 = cargoConsignService.queryOrdersByCarrier(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: doCarry
	* @Description: TODO(承运商点击承运按钮后对订单表进行更新)
	{
		"tokenId":"",
		"orderId":"",
		"carNo":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月26日 下午1:14:26
	* @throws
	 */
	@RequestMapping(value="/doCarry",method=RequestMethod.POST)
	public Map<String, Object> doCarry(@RequestBody Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			ValidationUtil.checkBlankAndAssignString(params.getSign());//前端签名非空校验
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.CARRIER);
			ValidationUtil.checkAndAssignLong(params.getTransportTime());
			params.setUserId(Integer.parseInt(userId));
			Orders order = orderService.queryFullOrderByOrderId(ValidationUtil.checkAndAssignInt(params.getOrderId()));
			ValidationUtil.checkBlankAndAssignString(params.getCarNo(),CARNO_PATTERN);//车牌号校验
			if(order==null) throw new RuntimeException("订单不存在");
			if(!Statuses.UNDELIVER.equals(order.getStatusId())) throw new RuntimeException("非法操作");
			if(!params.getUserId().equals(order.getCarrierId())) throw new RuntimeException("无权操作");
			cargoConsignService.doCarry(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: showAllCarriersUnderSupplier
	* @Description: TODO(当供应商点击发货时候，跳出的弹框中承运商下拉框中显示所有承运商)
	{
		"tokenId":"xxx"
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月26日 下午12:03:48
	* @throws
	 */
	@RequestMapping(value="/showAllCarriersUnderSupplier",method=RequestMethod.POST)
	public Map<String, Object> showAllCarriersUnderSupplier(){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			userAuthoricationService.queryUserDetail(ValidationUtil.checkAndAssignInt(userId), Role.SUPPLIER);
			List<UserDetail> carrierList = userAuthoricationService.showAllCarriersUnderSupplier();
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, carrierList);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	
	
	/**
	 * 
	* @Title: showAllStatus
	* @Description: TODO(返回给前端所有状态的id和状态名称)
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月31日 下午4:16:11
	* @throws
	 */
	@RequestMapping(value="/showAllStatus",method=RequestMethod.POST)
	public Map<String, Object> showAllStatus(){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId), Role.PLANNER,Role.SUPPLIER,Role.CARRIER);//检测当前操作用户权限
			List<Status> statusList = statusService.queryAllStatusInformation();
			return JSONUtil.getJsonMap(200, true, HintMSG.QUERY_SUCCESS, statusList);
		} catch (Exception e) {
			return JSONUtil.getJsonMap(500, false, HintMSG.QUERY_FAIL+":"+e.getMessage(), null);
		}
	}
	
	
	/**
	 * 
	* @Title: orderTracking
	* @Description: TODO(供应商和承运商的订单查询)
	{
		"tokenId":"xxx",
		"orderId":""
	}
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @author ylx
	* @date 2018年1月26日 下午1:47:45
	* @throws
	 */
	@RequestMapping(value="/orderTracking",method=RequestMethod.POST)
	public Map<String, Object> orderTracking(@RequestBody Params params){
		try {
			String userId = req.getHeader("Authorization").split("&")[1];
			params.setUserId(Integer.parseInt(userId));
			UserDetail userDetail = userAuthoricationService.queryUserAuthority(ValidationUtil.checkAndAssignInt(userId),Role.CARRIER,Role.SUPPLIER);//检测当前操作用户权限
			Orders order = orderService.queryFullOrderByOrderId(ValidationUtil.checkAndAssignInt(params.getOrderId()));
			if(Role.SUPPLIER.equals(userDetail.getRoleName())){
				if(!params.getUserId().equals(order.getSupplierId())) throw new RuntimeException("无权查看");
			}
			if(Role.CARRIER.equals(userDetail.getRoleName())){
				if(!params.getUserId().equals(order.getCarrierId())) throw new RuntimeException("无权查看");
			}
			params.setOrder(order);
			List<Object> list = cargoConsignService.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);
		}
	}
	
}
