package com.palmnest.webapp.controller.washcar.api;

import cn.jiguang.common.utils.StringUtils;
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.input.SlipInputDto;
import com.palmnest.application.dto.input.WashCarOrderDto;
import com.palmnest.application.dto.output.WashCarServiceDto;
import com.palmnest.application.dto.output.WashOrderOutputDto;
import com.palmnest.model.Element;
import com.palmnest.model.User;
import com.palmnest.service.AppUserService;
import com.palmnest.service.UserManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.washcar.service.CustomerService;
import com.palmnest.service.washcar.service.ElementGroupService;
import com.palmnest.service.washcar.service.WashCarOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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


@Slf4j
@Controller
@RequestMapping("/api/washcar/*")
public class ApiWashCarOrderController {


	@Autowired
	private CustomerService     customerService;
	@Autowired
	private WashCarOrderService washCarOrderService;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private BaseRedisService    baseRedisService;
	@Autowired
	private ElementGroupService elementGroupService;
	@Autowired
	private AppUserService      appUserService;

	//订单列表

	/**
	 * //订单列表接口
	 *
	 * @param washCarOrderDto
	 * @param page
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "getOrderList")
	@ResponseBody
	public AppResultDto getOrderList(WashCarOrderDto washCarOrderDto, int pageNo, int pageSize, HttpServletRequest request, HttpServletResponse response) {
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User         user   = userManager.getUserByUsername2(userName);
		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, pageNo, pageSize);
			return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, orderPage);
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "查询列表失败:" + e.getMessage());
		}
	}
	//取消订单

	/**
	 * 取消订单
	 * 只有待接单的单据允许取消订单
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "cancelWashOrder")
	@ResponseBody
	public AppResultDto cancelWashOrder(Long id, HttpServletRequest request, HttpServletResponse response) {
		String userId = "";
		String res    = "";
		try {
			String userName = baseRedisService.get(request.getHeader("token"));
			if (userName == null) {
				return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
			}
			User user = userManager.getUserByUsername2(userName);
			if (user == null) {
				return AppResultUtil.createErrorDto("100", "用户不存在");
			}
			userId = user.getId().toString();
			res = washCarOrderService.cancelWashOrder(id, userId, "USER");
			if ("SUCCESS".equals(res)) {
				return AppResultUtil.createSuccesDto();
			} else {
				return AppResultUtil.createErrorDto("100", "取消订单失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "取消订单失败:" + e.getMessage());
		}
	}


	/**
	 * 转单
	 *
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "transferBill")
	@ResponseBody
	public AppResultDto transferBill(SlipInputDto dto, HttpServletRequest request, HttpServletResponse response) {

		String userName = baseRedisService.get(request.getHeader("token"));

		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}

		User user = userManager.getUserByUsername2(userName);

		String userId = "";

		if (user != null) {
			userId = String.valueOf(user.getId());
		}

		try {

			String res = washCarOrderService.transferBill(dto, userId);

			if ("SUCCESS".equals(res)) {
				return AppResultUtil.createSuccesDto();
			}

			return AppResultUtil.createErrorDto("100", "转单失败");

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

	/**
	 * 转单入口
	 *
	 * @return
	 */
	@RequestMapping(value = "getSlipReason")
	@ResponseBody
	public AppResultDto getSlipReason() {
		List<Element> elList = elementGroupService.getElementsByGroupName("slipReason");
		return AppResultUtil.createSuccesDto(elementGroupService.convert(elList));
	}


	/**
	 * //派单接口(入口)
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getWashCarService")
	@ResponseBody
	public AppResultDto getWashCarService(HttpServletRequest request, HttpServletResponse response) {
		//获取洗车人员(名称，工号，进行中的单据，上班状态)d
		String userName = baseRedisService.get(request.getHeader("token"));
		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}
		User         user = userManager.getUserByUsername2(userName);
		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());
		//app端派单的项目id，应该根据下单的项目id来进行过滤
		try {
			String orgIds = "";
			if (dtos != null && dtos.size() > 0) {
				OrgDto dto = dtos.get(0);
				orgIds = dto.getId().toString();
			}
//			WashCarOrder order=washCarOrderService.get(id);
			List<WashCarServiceDto> list = washCarOrderService.getWashCarService(orgIds, CodeConstants.CARWASH_SERVICE);
			return AppResultUtil.createSuccesDto(list);

		} 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) {

		String userName = baseRedisService.get(request.getHeader("token"));

		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}

		User user = userManager.getUserByUsername2(userName);

		String userId = "";

		if (user != null) {
			userId = String.valueOf(user.getId());
		}

		try {
			String res = washCarOrderService.dispatch(3, 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 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       订单id
	 * @param type     1取钥匙2完成
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "updateWashOrder")
	@ResponseBody
	public AppResultDto updateWashOrder(Long id, Integer type, String keySpace, String parkSpace, HttpServletRequest request, HttpServletResponse response) {

		String userName = baseRedisService.get(request.getHeader("token"));

		if (userName == null) {
			return AppResultUtil.createErrorDto(AppConstants.TOKEN_EXPIRED, "token已过期");
		}

		User user = userManager.getUserByUsername2(userName);

		String userId = "";

		if (user != null) {
			userId = String.valueOf(user.getId());
		}

		try {

			String res = washCarOrderService.updateWashOrder(id, type, userId, keySpace, parkSpace);
			if ("SUCCESS".equals(res)) {
				return AppResultUtil.createSuccesDto();
			} else {
				return AppResultUtil.createErrorDto("100", "操作失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "操作失败:" + e.getMessage());
		}
	}
}
