package com.palmnest.webapp.controller.washcar;

import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.WashCarOrderDto;
import com.palmnest.application.dto.input.WashOrderInputDto;
import com.palmnest.application.dto.output.WashCarServiceDto;
import com.palmnest.application.dto.output.WashOrderOutputDto;
import com.palmnest.model.User;
import com.palmnest.model.washcar.ExtraService;
import com.palmnest.model.washcar.ProjectSet;
import com.palmnest.model.washcar.WashCarOrder;
import com.palmnest.service.AppUserService;
import com.palmnest.service.washcar.service.ExtraServiceService;
import com.palmnest.service.washcar.service.ProjectSetService;
import com.palmnest.service.washcar.service.WashCarOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 洗车controller
 *
 * @author longmeizhen
 */
@Slf4j
@Controller
@RequestMapping("/admin/washcar/*")
public class WashCarOrderController {


	@Autowired
	private ExtraServiceService extraServiceService;
	@Autowired
	private WashCarOrderService washCarOrderService;
	@Autowired
	private ProjectSetService   projectSetService;
	@Autowired
	private AppUserService      appUserService;

	/**
	 * 跳转到设置中心界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "jumpOrderManager")
	public ModelAndView jumpOrderManager(HttpServletRequest request,
										 HttpServletResponse response) {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		return new ModelAndView("admin/vehicleClean/orderManage", model.asMap());
	}

	@RequestMapping(value = "getOrgList")
	@ResponseBody
	public AppResultDto getOrgList(HttpServletRequest request,
								   HttpServletResponse response) {
		try {
			User         user = (User) request.getSession().getAttribute("UserCache");
			List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
			return AppResultUtil.createSuccesDto(dtos);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取项目信息失败:" + e.getMessage());
		}

	}

	/**
	 * //订单列表接口
	 *
	 * @param washCarOrderDto
	 * @param page
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "getOrderList")
	@ResponseBody
	public WebPageResultDto getOrderList(WashCarOrderDto washCarOrderDto, int page, int limit, HttpServletRequest request, HttpServletResponse response) {
		User         user   = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos   = appUserService.getUserOrgs(user.getId());
		String       orgIds = washCarOrderDto.getOrgId();
		try {
			if (StringUtils.isEmpty(orgIds) || "0".equals(orgIds)) {
				if (dtos != null && dtos.size() > 0) {
					orgIds = "";
					for (int i = 0; i < dtos.size(); i++) {
						OrgDto dto = dtos.get(i);
						orgIds = orgIds + dto.getId() + ";";
					}
				}
			}
			washCarOrderDto.setOrgId(orgIds);
			Page             orderPage = washCarOrderService.findSearch(washCarOrderDto, page, limit);
			WebPageResultDto dto       = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", orderPage.getItems());
			dto.setCount(orderPage.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return new WebPageResultDto("100", "查询列表失败:" + e.getMessage(), null);
		}
	}

	/**
	 * //订单详情接口
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "getWashOrderInfo")
	@ResponseBody
	public AppResultDto getWashOrderInfo(Long id) {
		try {
			WashOrderOutputDto dto = washCarOrderService.getOrderInfo(id);
			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取失败:" + e.getMessage());
		}
	}

	/**
	 * 删除订单接口  删除接口(只有待接单的单据允许删除)
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "deleteOrder")
	@ResponseBody
	public AppResultDto deleteOrder(Long id) throws Exception {
		int count = 0;
		try {
			count = washCarOrderService.deleteOrder(id);
			if (count > 0) {
				return AppResultUtil.createSuccesDto();
			} else {
				return AppResultUtil.createErrorDto("100", "删除失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "删除失败:" + e.getMessage());
		}

	}

	/**
	 * 下单入口(获取所有的服务)
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getOrderIn")
	@ResponseBody
	public AppResultDto getOrderIn(String projectId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			int num = washCarOrderService.getWashCountByDas(projectId);
			if (num <= 0) {
				return AppResultUtil.createErrorDto("100", "剩余下单数为0，不允许下单");
			}
			ProjectSet proSet = projectSetService.fingByProjectId(projectId);
			if (proSet != null) {
				List<ExtraService> extraList = extraServiceService.findByProSetId(proSet.getId());
				return AppResultUtil.createSuccesDto(extraList);
			} else {
				return AppResultUtil.createErrorDto("100", "获取失败");
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取失败:" + e.getMessage());
		}
	}


	/**
	 * //派单接口(入口)
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getWashCarService")
	@ResponseBody
	public AppResultDto getWashCarService(Long id, HttpServletRequest request, HttpServletResponse response) {
		//获取洗车人员(名称，工号，进行中的单据，上班状态)
//		String orgId=request.getParameter("orgId");
		try {
			//根据订单获取项目id
			if (washCarOrderService.exists(id)) {
				WashCarOrder            order = washCarOrderService.findById(id);
				List<WashCarServiceDto> list  = washCarOrderService.getWashCarService(order.getOrgId(), CodeConstants.CARWASH_SERVICE);
				return AppResultUtil.createSuccesDto(list);
			} else {
				return AppResultUtil.createErrorDto("100", "订单找不到");
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取失败:" + e.getMessage());
		}
	}

	/**
	 * 派单接口
	 * 首先修改订单的状态和洗车人员以及管理人员
	 * 然后新增操作记录
	 *
	 * @param id        订单id
	 * @param washSerId 洗车人员id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "dispatch")
	@ResponseBody
	public AppResultDto dispatch(Long id, String washSerId, HttpServletRequest request, HttpServletResponse response) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		try {
			String res = washCarOrderService.dispatch(1, id, washSerId, userId);
			if ("SUCCESS".equals(res)) {
				return AppResultUtil.createSuccesDto();
			} else if ("OPERATED".equals(res)) {
				return AppResultUtil.createErrorDto("100", "该单据已被操作，不能重复操作");
			} else {
				return AppResultUtil.createErrorDto("100", "派单失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "派单失败:" + e.getMessage());
		}
	}

	/**
	 * 下单接口
	 *
	 * @param washOrderInputDto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "saveWashOrder")
	@ResponseBody
	public AppResultDto saveWashOrder(WashOrderInputDto washOrderInputDto, HttpServletRequest request, HttpServletResponse response) {
		User   user   = (User) request.getSession().getAttribute("UserCache");
		String userId = "";
		if (user != null) {
			userId = String.valueOf(user.getId());
		}
		Map<String, Object> map   = new HashMap<String, Object>();
		String              orgId = washOrderInputDto.getOrgId();
		try {
			int num = washCarOrderService.getWashCountByDas(orgId);
			if (num <= 0) {
				return AppResultUtil.createErrorDto("100", "剩余下单数为0，不允许下单");
			}
			if (washOrderInputDto.getUserId() == null) {
				return AppResultUtil.createErrorDto("100", "用户不能为空");
			}
			map = washCarOrderService.saveWashCarOrder(washOrderInputDto, userId, 1);
//			if(map.get("orderInfo")!=null&&"".equals(map.get("msg"))){
//				return AppResultUtil.createSuccesDto(map.get("orderInfo"));
//			}
//			else{
//				return AppResultUtil.createErrorDto("100", "下单失败");  
//			}
			if (map.get("orderInfo") != null && "".equals(map.get("msg"))) {
				//派单
				if (map.get("orderInfo") instanceof WashCarOrder) {
					WashCarOrder order = (WashCarOrder) map.get("orderInfo");
					String       res   = washCarOrderService.automaticDispatch(orgId, order.getId(), userId);
					if ("FAIL".equals(res)) {
						return AppResultUtil.createCommonDto("200", "下单成功", map.get("orderInfo"));
					}
					return AppResultUtil.createCommonDto("200", "派单成功", map.get("orderInfo"));
				}
				return AppResultUtil.createCommonDto("200", "下单成功", map.get("orderInfo"));
			} else {
				return AppResultUtil.createErrorDto("100", "下单失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "下单失败:" + e.getMessage());
		}
	}

	//查询用户接口(共用查询用户接口)

}
