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

import cn.jiguang.common.utils.StringUtils;
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.dto.input.EvaluateInputDto;
import com.palmnest.application.dto.input.WashCarOrderDto;
import com.palmnest.application.dto.input.WashOrderInputDto;
import com.palmnest.application.dto.output.ExtraServiceOutputDto;
import com.palmnest.application.dto.output.WashOrderOutputDto;
import com.palmnest.model.Element;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.washcar.*;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.washcar.service.*;
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.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping("/wechat/washcar/*")
public class WechatWashCarOrderController {


	@Autowired
	private CustomerService     customerService;
	@Autowired
	private WashCarOrderService washCarOrderService;
	@Autowired
	private ExtraServiceService extraServiceService;
	@Autowired
	private ProjectSetService   projectSetService;
	@Autowired
	private UserEvaluateService userEvaluateService;
	@Autowired
	private ElementGroupService elementGroupService;
	@Autowired
	private ScWxuserManager     scWxuserManager;

	/**
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public AppResultDto login(HttpServletRequest request, HttpServletResponse response) {

		String mobile = request.getParameter("mobile");
		String code   = request.getParameter("authCode");
		String openId = request.getParameter("openId");
		String orgId  = request.getParameter("orgId");

		try {
//			String orgId=scWxuserManager.getOrgByOpenId(openId);
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			Customer cust = customerService.getCustByMobile(orgId, mobile);
			if (cust == null) {//没有注册
				return AppResultUtil.createErrorDto(AppConstants.USER_NOT_EXIST, "登录用户不存在");
			} else {
				//如果用户存在了，就对比code,然后返回成功
				int isExist = customerService.isExistence(mobile, code);
				if (isExist == 1) {//没找到对应的数据
					return AppResultUtil.createErrorDto("100", "验证码无效");
				} else {
					//登录成功后需要将用户和微信用户绑定
					cust.setOpenId(openId);
					customerService.updateCustomer(cust);
					return AppResultUtil.createSuccesDto(cust);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "登录失败:" + e.getMessage());
		}
	}

	@RequestMapping(value = "/exitLogin")
	@ResponseBody
	public AppResultDto exitLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {

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

		try {
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			if (StringUtils.isNotEmpty(openId)) {
				String res = customerService.exitLogin(orgId, openId);
				if ("SUCCESS".equals(res)) {
					return AppResultUtil.createSuccesDto();
				} else {
					return AppResultUtil.createErrorDto("100", res);
				}
			} else {
				return AppResultUtil.createErrorDto("100", "openId不能为空");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "退出失败:" + e.getMessage());
		}
	}

	/**
	 * 根据openId获取客户
	 *
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "getCustByOpenId")
	@ResponseBody
	public AppResultDto getCustByOpenId(String orgId, String openId) {
		if (StringUtils.isEmpty(openId)) {
			return AppResultUtil.createErrorDto("100", "openId不允许为空");
		}
		try {
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			if (StringUtils.isEmpty(openId)) {
				return AppResultUtil.createErrorDto("100", "微信用户不能为空");
			}
			Customer cust = customerService.getCustByOpenId(orgId, openId);
			if (cust == null) {
				return AppResultUtil.createErrorDto("100", "该用户尚未登录过，请先登录。");
			} else {
				return AppResultUtil.createSuccesDto(cust);

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

	/**
	 * 获取当天的剩余名额
	 * 查询当天不为取消状态的订单
	 *
	 * @return
	 */
	@RequestMapping(value = "getQutoaOfDays")
	@ResponseBody
	public AppResultDto getQutoaOfDays(String openId, HttpServletRequest request) {
		String orgId = request.getParameter("orgId");
		if (StringUtils.isEmpty(orgId)) {
			WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
			if (user != null && user.getOrganizationId() != null) {
				orgId = user.getOrganizationId().toString();
			}
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
		int num = 0;
		try {
			num = washCarOrderService.getWashCountByDas(orgId);
			ExtraServiceOutputDto dto = extraServiceService.getExtraList(orgId);
			dto.setQuota(num);
			return AppResultUtil.createSuccesDto(dto);
		} 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 openId, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String orgId = request.getParameter("orgId");
		if (StringUtils.isEmpty(orgId)) {
			WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
			if (user != null && user.getOrganizationId() != null) {
				orgId = user.getOrganizationId().toString();
			}
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
		try {
			int num = washCarOrderService.getWashCountByDas(orgId);
			if (num > 0) {
				ProjectSet proSet = projectSetService.fingByProjectId(orgId);
				if (proSet != null) {
					List<ExtraService> extraList = extraServiceService.findByProSetId(proSet.getId());
					return AppResultUtil.createSuccesDto(extraList);
				} else {
					return AppResultUtil.createErrorDto("100", "获取失败");
				}
			} else {
				return AppResultUtil.createErrorDto("100", "剩余下单数为0，不允许下单");
			}

		} 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, String openId, HttpServletRequest request, HttpServletResponse response) {
		String              userId = "";//需要根据微信用户获取用户id
		Map<String, Object> map    = new HashMap<String, Object>();
		String              orgId  = request.getParameter("orgId");
		if (StringUtils.isEmpty(orgId)) {
			WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
			if (user != null && user.getOrganizationId() != null) {
				orgId = user.getOrganizationId().toString();
			}
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
		try {
			int num = washCarOrderService.getWashCountByDas("");
			if (num <= 0) {
				return AppResultUtil.createErrorDto("100", "剩余下单数为0，不允许下单");
			}
			Customer cust = customerService.getCustByOpenId(orgId, openId);
			if (cust != null) {
				userId = cust.getId().toString();
			}
			map = washCarOrderService.saveWashCarOrder(washOrderInputDto, userId, 2);//2代表微信
			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());
		}
	}

	/**
	 * //订单详情接口
	 *
	 * @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
	 */
	@RequestMapping(value = "cancelWashOrder")
	@ResponseBody
	public AppResultDto cancelWashOrder(Long id, String openId, String orgId) {

		String userId = "";//需要根据微信用户获取用户id
		String res    = "";
		try {
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			Customer cust = customerService.getCustByOpenId(orgId, openId);
			if (cust == null) {
				return AppResultUtil.createErrorDto("100", "用户不存在");
			}
			userId = cust.getId().toString();
			res = washCarOrderService.cancelWashOrder(id, userId, "CUST");
			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 washCarOrderDto
	 * @param page
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "getOrderList")
	@ResponseBody
	public AppResultDto getOrderList(HttpServletRequest request, WashCarOrderDto washCarOrderDto, String openId, int pageNo, int pageSize) {
		try {
			String orgId = request.getParameter("orgId");
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(openId);
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			washCarOrderDto.setOrgId(orgId);
			if (StringUtils.isEmpty(washCarOrderDto.getCustId())) {
				Customer cust = customerService.getCustByOpenId(orgId, openId);
				if (cust == null) {
					return AppResultUtil.createErrorDto("100", "用户不存在");
				}
				washCarOrderDto.setCustId(cust.getId().toString());
			}
			Page orderPage = washCarOrderService.findSearch(washCarOrderDto, pageNo, pageSize);
			if (orderPage != null) {
				return AppResultUtil.createSuccesDto(AppConstants.SUCCESS_CODE, orderPage.getItems());
			} else {
				return AppResultUtil.createSuccesDto();
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "查询列表失败:" + e.getMessage());
		}
	}

	/**
	 * 评价入口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "evaluateIn")
	@ResponseBody
	public AppResultDto evaluateIn(HttpServletRequest request, HttpServletResponse response) {
		List<Element> elList = elementGroupService.getElementsByGroupName("impressionGroup");
		return AppResultUtil.createSuccesDto(elementGroupService.convert(elList));
	}

	/**
	 * 评价
	 *
	 * @param dto
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "evaluate")
	@ResponseBody
	public AppResultDto evaluate(EvaluateInputDto dto, HttpServletRequest request, HttpServletResponse response) {
		try {
			String orgId = dto.getOrgId();
			if (StringUtils.isEmpty(orgId)) {
				WxUser user = scWxuserManager.getScWxuserByOpenId(dto.getOpenId());
				if (user != null && user.getOrganizationId() != null) {
					orgId = user.getOrganizationId().toString();
				}
				if (StringUtils.isEmpty(orgId)) {
					return AppResultUtil.createErrorDto("100", "项目不允许为空");
				}
			}
			Customer cust = customerService.getCustByOpenId(orgId, dto.getOpenId());
			if (cust == null) {
				return AppResultUtil.createErrorDto("100", "用户不存在");
			}
			String       userId = cust.getId().toString();
			UserEvaluate ue     = userEvaluateService.saveEvaluate(dto, "1", userId, null);
			if (ue != null) {
				return AppResultUtil.createSuccesDto();
			} else {
				return AppResultUtil.createErrorDto("100", "评价失败");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return AppResultUtil.createErrorDto("100", "评价失败:" + e.getMessage());
		}
	}

}
