package com.palmnest.webapp.controller.ws;

import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.ReturnObject;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ContractIinformationOrderManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 针对一键报修提供的接口（同步客户信息）
 *
 * @author HJY
 */
@Slf4j
@Controller
@RequestMapping("/api/userInformation/*")
public class UserinformationSyncController {


	@Autowired
	private ContractIinformationOrderManager contractIinformationOrderManager;
	@Autowired
	private WeChatApiManager                 weChatApiManager;
	@Autowired
	private AppUserManager                   appuserManager;
	@Autowired
	private ScWxuserManager                  scWxuserManager;
	@Autowired
	private ReplayContentDao                 replayContentDao;

	/**
	 * 同步创建客户订购记录信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/assignUdRecord", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String userinformationSync(HttpServletRequest request) {
		ReturnObject rt = new ReturnObject();
		try {
			String userMobile  = request.getParameter("userMobile");
			String serviceCode = request.getParameter("serviceCode");
			String customerNo  = request.getParameter("customerNo");

			log.info("------assignUdRecord");
			log.info("userMobile:" + userMobile);
			log.info("serviceCode:" + serviceCode);
			log.info("customerNo:" + customerNo);

			if (StringUtils.isNotBlank(userMobile) && StringUtils.isNotBlank(serviceCode)) {

				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_SUCC);

				boolean flag = contractIinformationOrderManager.saveContractIinformationOrder(userMobile, serviceCode, customerNo);

				if (flag) {
					rt.setReturnDTO("true");
				} else {
					rt.setReturnDTO("false");
				}

			} else {

				rt.setResult(Constants.RESULT_FIAL);
				rt.setResultCode(Constants.RESULTCODE_PARAMINVALID);
				rt.setResultDesc("无效参数");
			}
		} catch (Exception e) {

			log.info(LogExceptionStackUtil.LogExceptionStack(e));
			rt.setResult(Constants.RESULT_FIAL);
			rt.setResultCode(Constants.RESULTCODE_EXCEPTION);
			rt.setResultDesc("系统异常");
		}
		return JSONObject.fromObject(rt).toString();
	}


	/**
	 * 推送预定服务成功消息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/sendServerMessage", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String sendServerMessage(HttpServletRequest request) {
		ReturnObject rt = new ReturnObject();
		try {
			String userMobile     = request.getParameter("userMobile");        //电话号码
			String content        = request.getParameter("content");            //描述信息
			String customerMsg    = request.getParameter("customerMsg");        //企业客户信息
			String orderMsg       = request.getParameter("orderMsg");            //订单产品信息
			String orderNum       = request.getParameter("orderNum");            //订单编号
			String orderStateDesc = request.getParameter("orderStateDesc");//状态描述
			String orderDetailUrl = request.getParameter("orderDetailUrl");//订单详情地址
			orderDetailUrl = URLDecoder.decode(orderDetailUrl, "UTF-8");
			log.info("------sendServerMessage");
			log.info("userMobile:" + userMobile);
			log.info("content:" + content);
			log.info("customerMsg:" + customerMsg);
			log.info("orderMsg:" + orderMsg);
			log.info("orderNum:" + orderNum);
			log.info("orderStateDesc:" + orderStateDesc);
			log.info("orderDetailUrl:" + orderDetailUrl);

			if (StringUtils.isNotBlank(userMobile) && StringUtils.isNotBlank(content)) {
				AppUser appUser = appuserManager.getAppUsersByPhone(userMobile);
				if (appUser != null) {
					WxUser wxUser = scWxuserManager.getScWxuserByUserId(appUser.getId());
					if (wxUser != null) {
						List<Map<String, Object>> templateList = replayContentDao.getWxTemplate(ElementConstant.TemplateType04, 0);
						if (!CollectionUtils.isEmpty(templateList)) {
							String              templateId = (String) templateList.get(0).get("templateId");
							Map<String, String> paramMap   = new HashMap<String, String>();
							StringBuffer        remark     = new StringBuffer();
							remark.append("客户信息：" + customerMsg + "\\n");
							remark.append("订单内容：" + orderMsg);

							paramMap.put("openId", wxUser.getOpenId());
							paramMap.put("developId", wxUser.getDevelopId());
							paramMap.put("templateId", templateId);
							paramMap.put("url", orderDetailUrl);
							paramMap.put("title", content + "\\n");
							paramMap.put("orderNum", orderNum);
							paramMap.put("orderStateDesc", orderStateDesc);
							paramMap.put("remark", remark.toString());
							weChatApiManager.sendTemplateMsg03(paramMap);
						}
					} else {
						log.info("sendServerMessage(),the userid is not with wxuser." + appUser.getId());
					}
				}
				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_SUCC);
			} else {
				rt.setResult(Constants.RESULT_FIAL);
				rt.setResultCode(Constants.RESULTCODE_PARAMINVALID);
				rt.setResultDesc("无效参数");
			}
		} catch (Exception e) {
			log.info(LogExceptionStackUtil.LogExceptionStack(e));
			rt.setResult(Constants.RESULT_FIAL);
			rt.setResultCode(Constants.RESULTCODE_EXCEPTION);
			rt.setResultDesc("系统异常");
		}
		return JSONObject.fromObject(rt).toString();
	}

}
