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

import cn.jiguang.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.TempOrderDinnerDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.input.EvaluateInputDto;
import com.palmnest.application.dto.input.OrderDinnerInputDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.model.dinner.OrderDinner;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.washcar.UserEvaluate;
import com.palmnest.service.AppUserService;
import com.palmnest.service.dinner.service.ConsumerUserService;
import com.palmnest.service.dinner.service.OrderDinnerService;
import com.palmnest.service.washcar.service.ElementGroupService;
import com.palmnest.service.washcar.service.UserEvaluateService;
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 org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

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


	@Autowired
	private OrderDinnerService  orderDinnerService;
	@Autowired
	private UserEvaluateService userEvaluateService;
	@Autowired
	private ConsumerUserService consumerUserService;
	@Autowired
	private ElementGroupService elementGroupService;
	@Autowired
	private AppUserService      appUserService;

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

	/**
	 * 获取我的订单列表
	 *
	 * @param consId
	 * @param status 0代表全部 1代表待送餐 2代表待评价 3代表已完成4已取消
	 *               (状态为待送餐时允许取消订单[取消订单的时间必须在指定时间之前])
	 * @return
	 */
	@RequestMapping(value = "getOrderDinnerList")
	@ResponseBody
	public WebPageResultDto getOrderDinnerList(OrderDinnerInputDto dto, int pageSize, int pageNo) {

		String orgId    = dto.getOrgId();
		String wxUserId = dto.getWxUserId();

		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 new WebPageResultDto("100", result, "");
		}

		String res = appUserService.getAppUser(Integer.parseInt(orgId), Integer.parseInt(dto.getWxUserId()));
		if (StringUtils.isNotEmpty(res)) {
			return new WebPageResultDto("100", res, "");
		}

		AppUser appUser = appUserService.getAUByWxUser(Integer.parseInt(dto.getWxUserId()));

		//设置过滤订餐人为当前操作人
		dto.setConsId(appUser.getId().toString());

		Page page = orderDinnerService.findList(dto, pageSize, pageNo);

		WebPageResultDto pageDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page == null ? null : page.getItems());

		if (page == null) {
			pageDto.setCount(Long.parseLong("0"));
		} else {
			pageDto.setCount(page.getTotalCount());
		}

		return pageDto;
	}
	//详情

	/**
	 * 获取详情
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "getOrderDinnerInfo")
	@ResponseBody
	public AppResultDto getOrderDinnerInfo(Long id) {
		if (null != id) {
			return orderDinnerService.findById(id);
		}
		return AppResultUtil.createErrorDto("100", "获取订单详情失败");

	}

	/**
	 * 取消订单(状态为待送餐时允许取消订单[取消订单的时间必须在指定时间之前])
	 *
	 * @param id
	 * @param wxUserId
	 * @param orgId
	 * @return
	 */
	@RequestMapping(value = "cancelOrderDinner")
	@ResponseBody
	public AppResultDto cancelOrderDinner(Long id, String wxUserId, String orgId) {
		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=isOverTime();
//		if(StringUtils.isNotEmpty(res)){//超出
//			return AppResultUtil.createErrorDto("100", "抱歉，订餐时间为00:00~"+res+":00，已超出订餐时间");
//		}
		return orderDinnerService.cancelOrderDinner(id, wxUserId, orgId);
	}

	/**
	 * 获取评星描述
	 *
	 * @param orgId
	 * @param star
	 * @return
	 */
	@RequestMapping(value = "evaluateDescribe")
	@ResponseBody
	public AppResultDto evaluateDescribe(String orgId, int star) {
		List<ElementDto> dtoList = new ArrayList<ElementDto>();
		if (1 == star) {
			dtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "star1Describe");
		} else if (2 == star) {
			dtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "star2Describe");
		} else if (3 == star) {
			dtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "star3Describe");
		} else if (4 == star) {
			dtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "star4Describe");
		} else if (5 == star) {
			dtoList = elementGroupService.getOrgElementGroupInfo(Integer.parseInt(orgId), "star5Describe");
		}
		Collections.sort(dtoList, new Comparator<ElementDto>() {
			@Override
			public int compare(ElementDto o1, ElementDto o2) {
				String name1 = o1.getId().toString();
				String name2 = o2.getId().toString();
				return name1.compareTo(name2);
			}
		});
		return AppResultUtil.createSuccesDto(dtoList);
	}

	/**
	 * 评价
	 *
	 * @param dto
	 * @param consId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "evaluate")
	@ResponseBody
	public AppResultDto evaluate(EvaluateInputDto dto, MultipartHttpServletRequest request) {
		String orgId    = dto.getOrgId();
		String wxUserId = dto.getWxUserId();
		log.info("evaluate begin " + System.currentTimeMillis());
		try {
			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);
			}
			AppUser user = appUserService.getAUByWxUser(Integer.parseInt(wxUserId));
			if (null != dto.getOrderId()) {
				OrderDinner order = orderDinnerService.getById(dto.getOrderId());
				if (order != null) {
					UserEvaluate ue = userEvaluateService.saveEvaluate(dto, "2", user.getId().toString(), request);
					if (ue != null) {
						orderDinnerService.updateOrderByStar(dto.getOrderId(), dto.getStar(), user.getId().toString());
						log.info("evaluate end " + System.currentTimeMillis());
						return AppResultUtil.createSuccesDto();
					}
				}
			} else {
				log.error("评价订餐信息时失败：id不能为空");
				return AppResultUtil.createErrorDto("100", "评价失败");
			}
			log.info("evaluate end " + System.currentTimeMillis());
			return AppResultUtil.createErrorDto("100", "评价失败");
		} catch (Exception e) {
			log.error("评价失败:" + e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "评价失败:" + e.getMessage());
		}
	}

	/**
	 * 获取当天的订单详情
	 *
	 * @return
	 */
	@RequestMapping(value = "getAllOrderInfo")
	@ResponseBody
	public AppResultDto getAllOrderInfo(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);
		}
		return orderDinnerService.getAllOrderInfo(orgId, wxUserId);
	}

	/**
	 * 当日订餐已送达
	 *
	 * @param orgId
	 * @param openId
	 * @param consId
	 * @return
	 */
	@RequestMapping(value = "confirmService")
	@ResponseBody
	public AppResultDto confirmService(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);
		}
		String str = orderDinnerService.getOrderTime(orgId, "importTime");
		if (StringUtils.isEmpty(str)) {
			//没有超出规定时间
			return AppResultUtil.createErrorDto("100", "抱歉，还未到送餐时间!");
		}
		//获取当天有效的状态为待评价的订单
		List<OrderDinner> list = orderDinnerService.findByCons("", orgId, "1");
		AppResultDto      dto  = orderDinnerService.confirmService(orgId, wxUserId);
		orderDinnerService.sendWechatMessage(orgId, list);
		return dto;
	}

	/**
	 * 提交临时工作餐
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "submitTempOrder")
	@ResponseBody
	public AppResultDto submitTempOrder(HttpServletRequest request) {
		String              orgId    = request.getParameter("orgId");
		String              wxUserId = request.getParameter("wxUserId");
		String              time     = request.getParameter("time");
		String              remark   = request.getParameter("remark");
		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);
		}
		List<TempOrderDinnerDto> dtoList    = new ArrayList<TempOrderDinnerDto>();
		String                   carDtoJson = request.getParameter("list");
		if (StringUtils.isNotEmpty(carDtoJson)) {
			dtoList = JSON.parseArray(carDtoJson, TempOrderDinnerDto.class);
		} else {
			return AppResultUtil.createErrorDto("100", "提交订单的数据不能为空");
		}
		//判断用户是否存在
		String res = appUserService.getAppUser(Integer.parseInt(orgId), Integer.parseInt(wxUserId));
		if (StringUtils.isNotEmpty(res)) {
			return AppResultUtil.createErrorDto("100", res);
		}
		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", "数据格式异常，请联系管理员");
		}
		Map<String, Object> parement = new HashMap<String, Object>();
		parement.put("time", time);
		parement.put("dtoList", dtoList);
		parement.put("orgId", orgId);
		parement.put("userId", wxUserId);
		parement.put("remark", remark);
		return orderDinnerService.submitTempOrder(parement);
	}
}
