package com.palmnest.webapp.controller.dinner.wechat;

import cn.jiguang.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.WeekMealCarDto;
import com.palmnest.application.dto.input.MealCarInputDto;
import com.palmnest.application.dto.input.MealDto;
import com.palmnest.service.AppUserService;
import com.palmnest.service.dinner.service.ConsumerUserService;
import com.palmnest.service.dinner.service.MealService;
import com.palmnest.service.dinner.service.OrderDinnerService;
import com.palmnest.webapp.controller.BaseFormController;
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 java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author longmeizhen
 */
@Slf4j
@Controller
@RequestMapping("/wechat/dinner/mealCar/*")
public class WechatDinnerMealController extends BaseFormController {


	@Autowired
	private MealService         mealService;
	@Autowired
	private ConsumerUserService consumerUserService;
	@Autowired
	private OrderDinnerService  orderDinnerService;
	@Autowired
	private AppUserService      appUserService;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 加入购物车
	 * 首先判断时间有没有超过11点，然后再判断该用户能不能再提交一份
	 * 判断餐品是否有效
	 *
	 * @param carDto
	 * @return
	 */
	@RequestMapping(value = "joinMealCar")
	@ResponseBody
	public AppResultDto joinMealCar(HttpServletRequest request) {

		String orgId    = request.getParameter("orgId");
		String wxUserId = request.getParameter("wxUserId");

		Map<String, String> map = new HashMap<String, String>();
		map.put("orgId", orgId);
		map.put("userId", wxUserId);

		String result = decideParameter(map);
		if (StringUtil.isNotEmpty(result)) {
			return AppResultUtil.createErrorDto("100", result);
		}

		String res = appUserService.getAppUser(Integer.parseInt(orgId), Integer.parseInt(wxUserId));
		if (StringUtils.isNotEmpty(res)) {
			return AppResultUtil.createErrorDto("100", res);
		}

		List<MealCarInputDto> carDto       = new ArrayList<MealCarInputDto>();
		List<MealCarInputDto> removeCarDto = new ArrayList<MealCarInputDto>();
		String                carDtoJson   = request.getParameter("carDto");

		if (StringUtils.isNotEmpty(carDtoJson)) {
			carDto = JSON.parseArray(carDtoJson, MealCarInputDto.class);
		}

		String removeCarDtoJson = request.getParameter("removeCarDto");
		if (StringUtils.isNotEmpty(removeCarDtoJson)) {
			removeCarDto = JSON.parseArray(removeCarDtoJson, MealCarInputDto.class);
		}

		if (StringUtils.isEmpty(carDtoJson) && StringUtils.isEmpty(removeCarDtoJson)) {
			return AppResultUtil.createErrorDto("100", "加入购物车的餐品不能为空哦");
		}

//		//判断当前时间是否超出11点
//		String str=orderDinnerService.getOrderTime("orderTime");
//		if(StringUtils.isNotEmpty(str)){//超出
//			return AppResultUtil.createErrorDto("100", "抱歉，当前时间已超过订餐截止时间（"+str+"），明天记得早点哦");
//		}

		return orderDinnerService.joinMealCar(carDto, removeCarDto, orgId, wxUserId);
	}

	/**
	 * 清空或删除购物车数量
	 *
	 * @param consId 用户id
	 * @param id     购物车id
	 * @param type   1删除数量2清空购物车
	 * @return
	 */
	@RequestMapping(value = "removeMealCar")
	@ResponseBody
	public AppResultDto removeMealCar(String orgId, String wxUserId, String id, int type) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("orgId", orgId);
		map.put("userId", wxUserId);

		String result = decideParameter(map);
		if (StringUtil.isNotEmpty(result)) {
			return AppResultUtil.createErrorDto("100", result);
		}

		String res = appUserService.getAppUser(Integer.parseInt(orgId), Integer.parseInt(wxUserId));
		if (StringUtils.isNotEmpty(res)) {
			return AppResultUtil.createErrorDto("100", res);
		}

		return orderDinnerService.removeMealCar(orgId, wxUserId, id, type);
	}

	/**
	 * 提交订单
	 * 首先判断时间有没有超过11点，然后再判断该用户能不能再提交一份
	 * 判断餐品是否有效
	 * 然后根据当前登录用户将购物车中的餐品提交到餐品详情中
	 *
	 * @param consId
	 * @return
	 */
	@RequestMapping(value = "submitDinnerOrder")
	@ResponseBody
	public AppResultDto submitDinnerOrder(HttpServletRequest request) {

		String orgId    = request.getParameter("orgId");
		String wxUserId = request.getParameter("wxUserId");

		List<WeekMealCarDto> list = new ArrayList<WeekMealCarDto>();

		String carDtoJson = request.getParameter("list");

		if (StringUtils.isNotEmpty(carDtoJson)) {
			list = JSON.parseArray(carDtoJson, WeekMealCarDto.class);
		} else {
			return AppResultUtil.createErrorDto("100", "提交订单的数据不能为空");
		}

		Map<String, String> map = new HashMap<String, String>();
		map.put("orgId", orgId);
		map.put("userId", wxUserId);

		String result = decideParameter(map);
		if (StringUtil.isNotEmpty(result)) {
			return AppResultUtil.createErrorDto("100", result);
		}

		String res = appUserService.getAppUser(Integer.parseInt(orgId), Integer.parseInt(wxUserId));
		if (StringUtils.isNotEmpty(res)) {
			return AppResultUtil.createErrorDto("100", res);
		}

//		//判断当前时间是否超出11点
//		String str=orderDinnerService.getOrderTime("orderTime");
//		if(StringUtils.isNotEmpty(str)){//超出
//			return AppResultUtil.createErrorDto("100", "抱歉，当前时间已超过订餐截止时间（"+str+"），明天记得早点哦");
//		}
		try {
			return orderDinnerService.submitDinnerOrder(wxUserId, orgId, list);
		} catch (Exception e) {
			log.error("提交订单：" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "提交订单失败,请联系管理员");
		}

	}

	/**
	 * 获取购物车
	 *
	 * @param consId
	 * @return
	 */
	@RequestMapping(value = "gainMealCarList")
	@ResponseBody
	public AppResultDto gainMealCarList(String orgId, String wxUserId) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("orgId", orgId);
		map.put("userId", wxUserId);

		String result = decideParameter(map);

		if (StringUtil.isNotEmpty(result)) {
			return AppResultUtil.createErrorDto("100", result);
		}

		String res = appUserService.getAppUser(Integer.parseInt(orgId), Integer.parseInt(wxUserId));
		if (StringUtils.isNotEmpty(res)) {
			return AppResultUtil.createErrorDto("100", res);
		}

		try {
			String str    = orderDinnerService.getOrderTime(orgId, "orderTime");
			int    isOver = 0;
			if (StringUtils.isNotEmpty(str)) {
				//超出
				isOver = 1;
			}
			return orderDinnerService.gainMealCarList(orgId, wxUserId, isOver);
		} catch (Exception e) {
			log.error("获取购物车失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取购物车失败");
		}

	}
	//是否允许下订单(个人下过一份了不允许再下了)
	//添加购物车(添加购物车前先得判断这个人是否是能再下订单【既要判断购物车中是否有，也要判断是否已经下过订单了】)
	//提交订单(提交订单前先判断这个人能否下订单)
	//删除购物车餐品份数
	//清空购物车

	/**
	 * 获取菜品详情
	 *
	 * @param dto
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getMealInfo")
	@ResponseBody
	public AppResultDto getMealInfo(Long id, String wxUserId, String time) {

		try {

			if (null == id) {
				return AppResultUtil.createErrorDto("100", "id不能为空");
			}

			try {

				if (!StringUtil.isNotEmpty(time)) {
					return AppResultUtil.createErrorDto("100", "数据格式异常，请联系管理员");
				} else {
					time = sdf.format(sdf.parse(time));
				}
			} catch (Exception e) {
				log.error("数据格式异常：" + time);
				return AppResultUtil.createErrorDto("100", "数据格式异常，请联系管理员");
			}

			MealDto dto = mealService.findById(id, wxUserId, time);
			if (dto == null) {
				return AppResultUtil.createErrorDto("100", "获取餐品详情失败");
			}

			return AppResultUtil.createSuccesDto(dto);
		} catch (Exception e) {
			log.error("获取餐品详情失败：" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取餐品详情失败");
		}
	}

	/**
	 * 获取该用户购物车中总数量
	 *
	 * @param orgId
	 * @param wxUserId
	 * @return
	 */
	@RequestMapping(value = "getMealCarCount")
	@ResponseBody
	public AppResultDto getMealCarCount(String orgId, String wxUserId) {

		Map<String, String> map = new HashMap<String, String>();
		map.put("orgId", orgId);
		map.put("userId", wxUserId);

		String result = decideParameter(map);

		if (StringUtil.isNotEmpty(result)) {
			return AppResultUtil.createErrorDto("100", result);
		}

		int count = orderDinnerService.getMealCarList(wxUserId, orgId);

		return AppResultUtil.createSuccesDto(count);
	}

	/**
	 * 获取该用户购物车中总数量
	 *
	 * @param orgId
	 * @param wxUserId
	 * @return
	 */
	@RequestMapping(value = "getMealCarCountByMealId")
	@ResponseBody
	public AppResultDto getMealCarCount(String orgId, String wxUserId, String time, String mealId) {

		if (!StringUtil.isNotEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "抱歉，项目不允许为空，请联系管理员!");
		}

		if (!StringUtil.isNotEmpty(wxUserId)) {
			return AppResultUtil.createErrorDto("100", "抱歉，您还没有登录，请先登录!");
		}

		if (!StringUtil.isNotEmpty(time)) {
			return AppResultUtil.createErrorDto("100", "抱歉，您还没有登录，请先登录!");
		}

		if (!StringUtil.isNotEmpty(mealId)) {
			return AppResultUtil.createErrorDto("100", "抱歉，您还没有登录，请先登录!");
		}

		try {

			time = sdf.format(sdf.parse(time));
			int count = orderDinnerService.getMealCarCountByMealId(orgId, wxUserId, time, mealId);
			return AppResultUtil.createSuccesDto(count);
		} catch (Exception e) {
			log.error("获取餐品数量失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "获取餐品数量失败");
		}

	}

	/**
	 * 是否超时
	 *
	 * @param orgId
	 * @param time
	 * @return
	 */
	@RequestMapping(value = "isOverTime")
	@ResponseBody
	public AppResultDto isOverTime(String orgId, String time) {

		if (!StringUtil.isNotEmpty(orgId)) {
			return AppResultUtil.createErrorDto("100", "抱歉，项目不允许为空，请联系管理员!");
		}

		if (!StringUtil.isNotEmpty(time)) {
			return AppResultUtil.createErrorDto("100", "抱歉，您还没有登录，请先登录!");
		}

		try {
			time = sdf.format(sdf.parse(time));
			String sysDate = DateUtils.formatDate(new Date(), "yyyy-MM-dd");

			//当前时间大于传过来的时间
			if (sdf.parse(sysDate).compareTo(sdf.parse(time)) == 0) {
				//判断当前时间是否超出11点
				String str = orderDinnerService.getOrderTime(orgId, "orderTime");
				if (StringUtils.isNotEmpty(str)) {
					//超出
					return AppResultUtil.createErrorDto("100", "抱歉，当前时间已超过订餐截止时间（" + str + "），明天记得早点哦");
				}
			} else if (sdf.parse(sysDate).after(sdf.parse(time))) {
				return AppResultUtil.createErrorDto("100", "抱歉，当前时间已超过订餐截止时间，明天记得早点哦");
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("失败");
			return AppResultUtil.createErrorDto("100", "失败");
		}

	}
}
