package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.*;
import com.palmnest.model.User;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ShoppingMallManager;
import com.palmnest.service.wechat.WeChatApiManager;
import com.palmnest.webapp.controller.BaseFormController;
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.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城api控制类
 *
 * @version 1.0
 * @authr xiemin
 * @created 2017-2-10 上午9:58:20
 */
@Controller
@RequestMapping("/admin/shoppingMall*")
public class ShoppingMallController extends BaseFormController {

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

	/**
	 * 增加用户信息接口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	public JSONObject addAppUserInfo(Map<String, String> map) {
		JSONObject json              = new JSONObject();
		String     urlAddAppUserInfo = PropertiesKit.readPropertiesValue("adduser", "wechat.properties");
		try {
			Map<String, String> keyUrl   = shoppingMallManager.queryUrlKey(urlAddAppUserInfo);
			String              paramStr = StringUtil.paramStr(map);
			map.put("sign", DigestUtils.md5Hex(paramStr.toString()));
			String result = HttpKit.http(keyUrl.get("url"), map, Constants.METHOD_POST);
			json = JSON.parseObject(result);
			map = new HashMap<String, String>();
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			json.put("errcode", ElementConstant.YESORNO_1);
			json.put("errmsg", "服务器异常");
		}
		return json;
	}

	/**
	 * 获取Token接口
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	public JSONObject getToken(Map<String, String> map) {
		JSONObject json        = new JSONObject();
		String     urlGetToken = PropertiesKit.readPropertiesValue("getToken", "wechat.properties");

		try {
			Map<String, String> keyUrl = shoppingMallManager.queryUrlKey(urlGetToken);
			json = new JSONObject();

			map.put("username", map.get("username"));
			map.put("password", map.get("password"));
			map.put("t", DateUtils.getTimeCur(DateUtils.YYYY_MM_DD_MM_HH_SS, new Date()) + "");

			String paramStr = StringUtil.paramStr(map);
			map.put("sign", DigestUtils.md5Hex(paramStr));

			String result = HttpKit.http(keyUrl.get("url"), map, Constants.METHOD_POST);
			map = new HashMap<String, String>();
			json = JSON.parseObject(result);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			json.put("errcode", ElementConstant.YESORNO_1);
			json.put("errmsg", "服务器异常");
		}
		return json;
	}

	/**
	 * 单点登录商城
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/doLogin")
	private void doLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

		JSONObject json     = new JSONObject();
		String     path     = request.getContextPath();
		String     basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
		String     currPath = basePath.substring(0, basePath.length() - 1) + request.getRequestURI();
		String     login    = PropertiesKit.readPropertiesValue("adminLogin", "wechat.properties");
		try {
			User                user   = getUserManager().getUserByUsername(request.getRemoteUser());
			Map<String, String> keyUrl = shoppingMallManager.queryUrlKey(login);
			Map<String, String> map    = new HashMap<String, String>();
			//增加用户
			if (null == user) {
				response.sendRedirect(currPath + "/super_univ/logout");
				return;
			} else {
				String ticketKey = Constants.SSOID + user.getUsername();
				//是否登录过
				if (null != session.getAttribute(ticketKey)) {//进行登录操作
					String param = "?token=" + session.getAttribute(ticketKey);
					response.sendRedirect(keyUrl.get("url") + param);
					return;
				}
				String roleid = "115";
				map.put("username", user.getUsername());
				map.put("password", GenPass.Decrypt(user.getShopPassword()));
				map.put("roleid", roleid);
				map.put("tel", user.getTelephone());
				map.put("email", "");
				map.put("linkman", user.getUsername());

				//获取Token接口
				json = getToken(map);

				//获取成功则根据状态处理请求
				if (json.getString("errcode").equals(Constants.RESULT_FIAL)) {//请求成功进行登录操作
					session.setMaxInactiveInterval(1800);
					session.setAttribute(ticketKey, json.getString("token"));
					String param = "?token=" + json.getString("token");
					response.sendRedirect(keyUrl.get("url") + param);
					return;
				}
				//请求成功但数据不存在，进行数据添加，再登录
				if (json.getString("errcode").equals("20003")) {
					json = new JSONObject();
					//调用商城接口，增加用户信息
					json = addAppUserInfo(map);
					//添加成功。
					if (json.getInteger("errcode") == 0) {
						json = new JSONObject();
						//获取Token接口
						json = getToken(map);
						if (json.getInteger("errcode") == 0) {
							String token = json.getString("token");//获取token
							session.setAttribute(ticketKey, json.getString("token"));
							session.setMaxInactiveInterval(1800);
							String param = "token=" + token;
							response.sendRedirect(login + param);
							return;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 查询商城url列表
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String mallName = request.getParameter("mallName");
		String orgName  = request.getParameter("orgName");
		String pageNo   = request.getParameter("pageNo");

		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		modelMap.put("mallName", mallName);
		modelMap.put("orgName", orgName);
		modelMap.put("pageNo", pageNo);
		Pagenation<Map<String, String>> page = shoppingMallManager.queryMallList(modelMap);
		modelMap.addAttribute("page", page);
		return new ModelAndView("admin/mallList");
	}

	/**
	 * 跳转到添加商城页面
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/toAddMallUrl")
	public String toAddMallUrl(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		initFunctionOperate(request);       //初始化功能操作权限

		String id = request.getParameter("id");
		if (StringUtils.isNotEmpty(id)) {
			Map<String, String> map = new HashMap<String, String>();
			map = shoppingMallManager.queryDetails(id);
			modelMap.put("map", map);
		}
		return "admin/addMallUrl";
	}


	/**
	 * 添加商城url
	 *
	 * @param request
	 * @param response
	 * @param modelMap
	 * @return
	 */
	@RequestMapping(value = "/addMallUrl")
	public String addMallUrl(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String     mallName       = request.getParameter("mallName");
		String     url            = request.getParameter("url");
		String     id             = request.getParameter("id");
		String     organizationId = request.getParameter("organizationId");
		String     urlKey         = request.getParameter("urlKey");
		String     addressCode    = request.getParameter("addressCode");
		JSONObject json           = new JSONObject();
		modelMap.put("id", id);
		modelMap.put("mallName", mallName);
		modelMap.put("url", url);
		modelMap.put("urlKey", urlKey);
		modelMap.put("organizationId", organizationId);
		modelMap.put("addressCode", addressCode);
		try {
			User user = getUserManager().getUserByUsername(request.getRemoteUser());
			modelMap.put("userName", user.getUsername());
			json = shoppingMallManager.addMallUrl(modelMap);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		json.put("code", "-1");
		json.put("msg", "系统异常，添加失败");
		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 根据名称查询项目列表
	 */
	@RequestMapping(value = "/queryOrganizaiton")
	public String queryOrganizaiton(HttpServletRequest request,
									HttpServletResponse response, ModelMap modelMap) throws Exception {
		String     orgName = request.getParameter("orgName");
		JSONObject json    = new JSONObject();
		//根据名称查询项目列表
		List<Map<String, String>> organizaiton = shoppingMallManager.findByNameList(orgName);
		json.put("msg", organizaiton);
		StringUtil.charSet(json, request, response);
		return null;
	}

	/**
	 * 启用禁用
	 */
	@RequestMapping(value = "/mallDelete")
	public String mallDelete(HttpServletRequest request,
							 HttpServletResponse response, ModelMap modelMap) throws Exception {
		String     id     = request.getParameter("id");
		String     status = request.getParameter("status");
		JSONObject json   = new JSONObject();
		try {
			json = shoppingMallManager.mallDelete(id, status);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		json.put("code", "-1");
		json.put("msg", "系统异常，操作失败");
		StringUtil.charSet(json, request, response);
		return null;
	}
}
