package com.palmnest.webapp.controller.wechat;

import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ShoppingMallManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;

/**
 * 微信端跳转商城控制类
 *
 * @author xiemin
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/wechat/sikpMall/*")
public class AppSikpMallController extends BaseFormController {


	@Autowired
	private AppUserManager      appUserManager;
	@Autowired
	private WeChatApiManager    weChatApiManager;
	@Autowired
	private ShoppingMallManager shoppingMallManager;
	@Autowired
	private PropertyManager     propertyManager;

	private String webUrl = PropertiesKit.readPropertiesValue("webUrl", "wechat.properties");

	/**
	 * 跳转商城--福利商城
	 *
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	@RequestMapping(value = "/sikpMallManager")
	public String sikpMallManager(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {
		String      userId    = request.getParameter("userId");
		String      openId    = request.getParameter("openId");
		String      developId = request.getParameter("developId");
		String      urlKey    = request.getParameter("urlKey");
		AppUser     appUser   = appUserManager.get(Integer.parseInt(userId));
		PrintWriter out       = response.getWriter();
		response.setContentType("text/html;charset=UTF-8");

		log.info("sikpMallManager-----------");
		log.info("userId:" + userId);
		log.info("openId:" + openId);
		log.info("developId:" + developId);
		log.info("urlKey:" + urlKey);
		//跳转商城
		if (appUser == null) {
			request.setAttribute("openId", openId);
			request.setAttribute("developId", developId);
			return "/wechat/ubindphone";
		}
		//认证通过
		if ("1".equals(appUser.getStatus())) {
			log.info("do redirect to shopIndex.");

			String              userMobile = appUser.getUserMobile();
			String              key        = PropertiesKit.readPropertiesValue("key", "wechat.properties");
			String              token      = PropertiesKit.readPropertiesValue("token", "wechat.properties");
			long                t          = DateUtils.getTimeCur(DateUtils.YYYY_MM_DD_MM_HH_SS, new Date());
			String              k          = DigestUtils.md5Hex(userMobile + appUser.getId() + t + key);
			Map<String, String> map        = shoppingMallManager.queryUrlKey(urlKey);
			if (null != map.get("url") && !map.get("url").equals("")) {
				try {
					request.setAttribute("url", map.get("url"));
					request.setAttribute("token", token);
					request.setAttribute("ac", userMobile);
					request.setAttribute("ps", appUser.getId());
					request.setAttribute("t", t);
					request.setAttribute("k", k);

					log.info("url：" + map.get("url"));
					log.info("token：" + token);
					log.info("ac：" + userMobile);
					log.info("ps：" + appUser.getId());
					log.info("t：" + t);
					log.info("k：" + k);
					return "/wechat/wechatform";
				} catch (Exception e) {
					log.error("sikpMallManager occur error." + LogExceptionStackUtil.LogExceptionStack(e));
				}
			} else {
				request.setAttribute("openId", openId);
				request.setAttribute("developId", developId);
				request.setAttribute("userId", appUser.getId());
				response.setContentType("text/html; charset=UTF-8");
				out.print("<script>alert('福利商城暂时不可使用');window.location.href='" + webUrl + "/wechat/appUser/choiceOrgAddress?openId=" + openId + "&developId=" + developId + "&userId=" + appUser.getId() + "';</script>");
				return null;
			}
		} else {
			request.setAttribute("openId", openId);
			request.setAttribute("developId", developId);
			request.setAttribute("userId", appUser.getId());
			out.print("<script>alert('用户未认证，返回认证');window.location.href='" + webUrl + "/wechat/appUser/choiceOrgAddress?openId=" + openId + "&developId=" + developId + "&userId=" + appUser.getId() + "';</script>");
			return null;
		}
		return null;
	}

	/**
	 * urlKey == Cterminal
	 * 跳转商城--C端商城（开放的访问地址是不一样的）
	 *
	 * @param 0 访客 1 注册用户
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	@RequestMapping(value = "/sikpMallCterminal")
	public String sikpMallCterminal(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {

		String userId    = request.getParameter("userId");
		String openId    = request.getParameter("openId");
		String developId = request.getParameter("developId");
		String urlKey    = request.getParameter("urlKey");
		String mECode    = request.getParameter("mECode");
		String refererId = request.getParameter("refererId");

		PrintWriter out = response.getWriter();
		response.setContentType("text/html;charset=UTF-8");

		log.info("sikpMallManager-----------");
		log.info("userId:" + userId);
		log.info("openId:" + openId);
		log.info("developId:" + developId);
		log.info("urlKey:" + urlKey);
    	/*if(appUser == null){
    		request.setAttribute("openId", openId);
    		request.setAttribute("developId", developId);
    		return "/wechat/ubindphone";
    	}*/
		//注册用户
		if (null != userId && !userId.equals("")) {
			AppUser appUser = appUserManager.get(Integer.parseInt(userId));

			String              userMobile = appUser.getUserMobile();
			String              key        = PropertiesKit.readPropertiesValue("key", "wechat.properties");
			String              shopBlack  = PropertiesKit.readPropertiesValue("shopBlack", "wechat.properties");
			String              token      = PropertiesKit.readPropertiesValue("token", "wechat.properties");
			long                t          = DateUtils.getTimeCur(DateUtils.YYYY_MM_DD_MM_HH_SS, new Date());
			String              k          = DigestUtils.md5Hex(userMobile + t + key);
			Map<String, String> map        = shoppingMallManager.queryUrlKey(urlKey);
			if (null != map.get("url") && !map.get("url").equals("")) {
				try {
					/**
					 * 查询项目
					 */
					TbOrganization tbog = new TbOrganization();
					if (null != appUser.getOrganizationId() && !appUser.getOrganizationId().equals("")) {
						tbog = propertyManager.getTbOrganizationById(appUser.getOrganizationId());
					}
					request.setAttribute("url", map.get("url"));
					request.setAttribute("token", token);
					request.setAttribute("ac", userMobile);
					if (mECode == null || mECode.equals("") && (tbog != null && null != tbog.getCode() && !tbog.getCode().equals(""))) {
						mECode = tbog.getCode();
					}
					request.setAttribute("t", t);
					request.setAttribute("k", k);
					request.setAttribute("mECode", mECode);//项目id
					request.setAttribute("st", "1");//用户状态
					request.setAttribute("refererId", refererId);//原路id
					request.setAttribute("shopBlack", webUrl + shopBlack);

					log.info("url：" + map.get("url"));
					log.info("token：" + token);
					log.info("ac：" + userMobile);
					log.info("mECode：" + mECode);
					log.info("t：" + t);
					log.info("k：" + k);
					log.info("shopBlack：" + shopBlack);
					log.info("refererId：" + refererId);
					return "/wechat/wechatform";
				} catch (Exception e) {
					log.error("sikpMallManager occur error." + LogExceptionStackUtil.LogExceptionStack(e));
				}
			} else {
				request.setAttribute("openId", openId);
				request.setAttribute("developId", developId);
				request.setAttribute("userId", appUser.getId());
				response.setContentType("text/html; charset=UTF-8");
				out.print("<script>alert('C端商城暂时不可使用');window.location.href='" + webUrl + "/wechat/appUser/choiceOrgAddress?openId=" + openId + "&developId=" + developId + "&userId=" + appUser.getId() + "';</script>");
				return null;
			}
		} else {
			Map<String, String> map       = shoppingMallManager.queryUrlKey(urlKey);
			String              token     = PropertiesKit.readPropertiesValue("token", "wechat.properties");
			String              shopBlack = PropertiesKit.readPropertiesValue("shopBlack", "wechat.properties");
			request.setAttribute("url", map.get("url"));
			request.setAttribute("token", token);
			request.setAttribute("ps", "");
			request.setAttribute("ac", "");
			request.setAttribute("t", "");
			request.setAttribute("k", "");
			request.setAttribute("openId", openId);
			request.setAttribute("developId", developId);
			request.setAttribute("st", "0");//用户状态--欧法信需要传回，注册的时候做判断。
			request.setAttribute("shopBlack", webUrl + shopBlack);

			log.info("url：" + map.get("url"));
			log.info("token：" + token);
			log.info("ac：" + "");
			log.info("mECode：" + mECode);
			log.info("t：" + "");
			log.info("k：" + "");
			log.info("shopBlack：" + webUrl + shopBlack);
			log.info("refererId：" + refererId);

			return "/wechat/wechatform";
		}
		return null;
	}

	/**
	 * 更新用户C端商城项目公司信息
	 *
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	@RequestMapping(value = "/updateMallCterminal")
	public String updateMallCterminal(HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {
		String userMobile     = request.getParameter("userMobile");
		String organizationId = request.getParameter("organizationId");

		//注册用户
		if (null != userMobile && !userMobile.equals("")) {

			String key          = PropertiesKit.readPropertiesValue("key", "wechat.properties");
			String urlUpdateKey = PropertiesKit.readPropertiesValue("urlUpdateKey", "wechat.properties");
			String token        = PropertiesKit.readPropertiesValue("token", "wechat.properties");
			long   t            = DateUtils.getTimeCur(DateUtils.YYYY_MM_DD_MM_HH_SS, new Date());

			Map<String, String> map = shoppingMallManager.queryUrlKey(urlUpdateKey);
			if (null != map.get("url") && !map.get("url").equals("")) {
				try {

					TbOrganization tbog = new TbOrganization();
					if (null != organizationId && !organizationId.equals("")) {
						tbog = propertyManager.getTbOrganizationById(Integer.valueOf(organizationId));
					}
					request.setAttribute("url", map.get("url"));
					request.setAttribute("token", token);
					request.setAttribute("ac", userMobile);
					String mECode = "";
					String k      = "";
					if (null != tbog) {
						mECode = tbog.getCode();
						k = DigestUtils.md5Hex(userMobile + tbog.getCode() + t + key);
					}
					request.setAttribute("mECode", mECode);
					request.setAttribute("t", t);
					request.setAttribute("k", k);

					log.info("url：" + map.get("url"));
					log.info("token：" + token);
					log.info("ac：" + userMobile);
					log.info("mECode" + mECode);
					log.info("t：" + t);
					log.info("k：" + k);
					return "/wechat/wechatform";
				} catch (Exception e) {
					log.error("updateMallCterminal occur error." + LogExceptionStackUtil.LogExceptionStack(e));
				}
			}
		}
		return null;
	}

	public static void main(String[] args) {
		String key = PropertiesKit.readPropertiesValue("key", "wechat.properties");
		long   t   = 1495616689000L;
		try {
//			long t = DateUtils.getTimeCur(DateUtils.YYYY_MM_DD_MM_HH_SS,new Date());
		} catch (Exception e) {
			e.printStackTrace();
		}
		String k = DigestUtils.md5Hex("15605007005" + t + key);
		System.out.println(k);
	}

	/**
	 * C端商城-商品详情页信息查询
	 */
	@RequestMapping(value = "skiProductDetail")
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model            = new ExtendedModelMap();
		String openId           = request.getParameter("openId");
		String developId        = request.getParameter("developId");
		String productDetailUrl = request.getParameter("productDetailUrl");  //商品详情的链接
		String token            = PropertiesKit.readPropertiesValue("token", "wechat.properties");
		String shopBlack        = PropertiesKit.readPropertiesValue("shopBlack", "wechat.properties");
		String urlKey           = request.getParameter("urlKey");
		String st               = request.getParameter("st");
		log.info("-------skiProductDetail-------");
		log.info("openId:" + openId);
		log.info("developId:" + developId);
		log.info("refererId:" + productDetailUrl);
		log.info("token:" + token);
		log.info("shopBlack:" + webUrl + shopBlack);
		log.info("urlKey:" + urlKey);
		log.info("st:" + st);
		if (StringUtils.isNotBlank(urlKey)) {
			Map<String, String> map = shoppingMallManager.queryUrlKey(urlKey);
			if (map != null && map.size() > 0) {
				model.addAttribute("openId", openId);
				model.addAttribute("developId", developId);
				model.addAttribute("refererId", productDetailUrl);
				model.addAttribute("token", token);
				model.addAttribute("shopBlack", webUrl + shopBlack);
				model.addAttribute("url", map.get("url"));
				model.addAttribute("st", st);

				log.info("url:" + map.get("url"));
				return new ModelAndView("wechat/wechatform", model.asMap());
			}
		} else {
			log.warn("urlKey is null");
		}
		//TODO 505 error page
		return null;
	}

	/**
	 * C端商城，分享链接处理
	 */
	@RequestMapping(value = "customerShop")
	public ModelAndView skiCustomerShop(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model  model     = new ExtendedModelMap();
		String openId    = request.getParameter("openId");
		String developId = request.getParameter("developId");
		String userId    = request.getParameter("userId");
		String refererId = request.getParameter("refererId");    //商城链接
		String urlKey    = request.getParameter("urlKey");

		log.info("openId:" + openId);
		log.info("developId:" + developId);
		log.info("userId:" + userId);
		log.info("refererId:" + refererId);
		log.info("urlKey:" + urlKey);

		String token = PropertiesKit.readPropertiesValue("token", "wechat.properties");
		String key   = PropertiesKit.readPropertiesValue("key", "wechat.properties");
		//注册的会员用户
		if (StringUtils.isNotBlank(userId)) {
			AppUser appUser = appUserManager.get(Integer.parseInt(userId));
			model.addAttribute("st", "1");
			model.addAttribute("ac", appUser.getUserMobile());
			if (appUser.getOrganizationId() != null) {
				TbOrganization organization = propertyManager.getTbOrganizationById(appUser.getOrganizationId());
				model.addAttribute("mECode", organization.getCode());
			} else {
				model.addAttribute("mECode", "");
			}
			model.addAttribute("k", DigestUtils.md5Hex(appUser.getUserMobile() + key));
			model.addAttribute("shopBlack", "");
		}
		//游客
		else {
			model.addAttribute("st", "0");
			model.addAttribute("ac", "");
			model.addAttribute("mECode", "");
			model.addAttribute("k", "");
			model.addAttribute("shopBlack", webUrl + PropertiesKit.readPropertiesValue("shopBlack", "wechat.properties"));
		}
		model.addAttribute("token", token);
		model.addAttribute("developId", developId);
		model.addAttribute("refererId", refererId);
		model.addAttribute("t", "");
		model.addAttribute("openId", openId);

		Map<String, String> map = shoppingMallManager.queryUrlKey(urlKey);  //Cterminal
		model.addAttribute("url", map.get("url"));
		return new ModelAndView("wechat/wechatform", model.asMap());
	}
}
