package com.palmnest.webapp.controller.ws;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.ReturnObject;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.property.ProvinceCity;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 基础架构服务接口
 *
 * @author yubing
 * @since 2017-08-04 18:19:00
 */
@Slf4j
@Controller
@RequestMapping("/api/base/*")
public class BaseStructureController {


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

	/**
	 * 获取省份、城市信息接口
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getProvincecity", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String getProvincecity(HttpServletRequest request) {

		ReturnObject rt = new ReturnObject();

		String type = request.getParameter("type");
		String code = request.getParameter("code");

		log.info("type:" + type);
		log.info("code:" + code);

		if (StringUtils.isNotBlank(type)) {
			if ("1".equals(type) || ("2".equals(type) && StringUtils.isNotBlank(code))) {
				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_SUCC);
				rt.setResultDesc("success");
				List<Map<String, String>> list          = new ArrayList<Map<String, String>>();
				List<ProvinceCity>        provinceCitys = propertyManager.getProvinceCityList(type, code);
				for (ProvinceCity provinceCity : provinceCitys) {
					Map<String, String> data = new HashMap<String, String>();
					data.put("name", provinceCity.getName());
					if ("1".equals(type)) {
						data.put("code", provinceCity.getProvinceCode());
					} else {
						data.put("code", provinceCity.getCityCode());
					}
					list.add(data);
				}
				rt.setReturnDTO(list);
			} else {
				rt.setResult(Constants.RESULT_FIAL);
				rt.setResultCode(Constants.RESULTCODE_PARAMINVALID);
				rt.setResultDesc("无效参数");
			}
		} else {
			rt.setResult(Constants.RESULT_FIAL);
			rt.setResultCode(Constants.RESULTCODE_PARAMINVALID);
			rt.setResultDesc("无效参数");
		}

		String str = JSONObject.toJSONString(rt, SerializerFeature.WriteMapNullValue);

		if (StringUtils.isNotBlank(request.getParameter("callback"))) {
			return request.getParameter("callback") + "(" + str + ")";
		}

		return str;
	}

	/**
	 * 获取项目列表信息接口
	 * 根据城市编码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getOrgByCityCode", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String getOrgByCityCode(HttpServletRequest request) {

		ReturnObject rt       = new ReturnObject();
		String       cityCode = request.getParameter("cityCode");

		log.info("cityCode:" + cityCode);

		if (StringUtils.isNotBlank(cityCode)) {

			List<Map<String, String>> list             = new ArrayList<Map<String, String>>();
			List<TbOrganization>      organizationList = propertyManager.getOrgByCityCode(cityCode);

			for (TbOrganization organization : organizationList) {
				Map<String, String> data = new HashMap<String, String>();
				data.put("name", organization.getName());
				data.put("code", organization.getCode());
				data.put("telephone", organization.getTelephone());
				data.put("provinceName", organization.getProvinceName());
				data.put("provinceCode", organization.getProvinceCode());
				data.put("cityName", organization.getCityName());
				data.put("cityCode", organization.getCityCode());
				data.put("address", organization.getAddress());
				data.put("lng", organization.getLng() == null ? "" : organization.getLng().toString());
				data.put("lat", organization.getLat() == null ? "" : organization.getLat().toString());
				list.add(data);
			}

			rt.setReturnDTO(list);
			rt.setResult(Constants.RESULT_SUCC);
			rt.setResultCode(Constants.RESULTCODE_SUCC);
			rt.setResultDesc("success");

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

		String str = JSONObject.toJSONString(rt, SerializerFeature.WriteMapNullValue);

		if (StringUtils.isNotBlank(request.getParameter("callback"))) {
			return request.getParameter("callback") + "(" + str + ")";
		}

		return str;
	}

	/**
	 * 返回超级前台服务号access_token
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "access_token", method = {RequestMethod.POST}, produces = "application/json")
	public @ResponseBody
	String access_token(HttpServletRequest request,
						HttpServletResponse response) {

		ReturnObject rt        = new ReturnObject();
		String       developId = request.getParameter("developId");

		//超级前台服务号 developId
		if (StringUtils.isEmpty(developId)) {
			developId = "gh_5e42b7c7c069";
		}

		if (StringUtils.isNotBlank(developId)) {
			try {
				String              accessToken = weChatApiManager.getAccessToken(developId);
				Map<String, String> resultMap   = new HashMap<String, String>();
				resultMap.put("accessToken", accessToken);

				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_SUCC);
				rt.setReturnDTO(resultMap);
			} catch (Exception e) {
				rt.setResult(Constants.RESULT_FIAL);
				rt.setResultCode(Constants.RESULTCODE_EXCEPTION);
				rt.setResultDesc("服务器异常");
			}
		} else {
			rt.setResult(Constants.RESULT_FIAL);
			rt.setResultCode(Constants.RESULTCODE_PARAMINVALID);
			rt.setResultDesc("请检查参数");
		}
		String str = JSONObject.toJSONString(rt, SerializerFeature.WriteMapNullValue);
		if (StringUtils.isNotBlank(request.getParameter("callback"))) {
			return request.getParameter("callback") + "(" + str + ")";
		}
		return str;
	}

	/**
	 * 用户资料信息获取接口
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/userInfo", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String userInfo(HttpServletRequest request) {
		ReturnObject rt     = new ReturnObject();
		String       userId = request.getParameter("userId");
		log.info("userId:" + userId);
		if (StringUtils.isNotBlank(userId)) {
			AppUser appUser = appUserManager.get(Integer.parseInt(userId));
			if (appUser != null) {
				Map<String, String> data = new HashMap<String, String>();
				data.put("userName", appUser.getUserName());
				data.put("userMobile", appUser.getUserMobile());
				data.put("userPhotoUrl", appUser.getUserPhotoUrl());
				data.put("status", appUser.getStatus());
				//项目信息组装
				if (appUser.getOrganizationId() != null) {
					TbOrganization organization = propertyManager.getTbOrganizationById(appUser.getOrganizationId());
					data.put("organizationName", organization.getName());
					data.put("organizationCode", organization.getCode());
				} else {
					data.put("organizationName", "");
					data.put("organizationCode", "");
				}
				//企业信息组装
				if (appUser.getVirtualArchId() != null) {
					VirtualArchitecture virtual = propertyManager.getVirtualArchitectureById(appUser.getVirtualArchId());
					data.put("virtualName", virtual.getName());
					data.put("virtualCode", virtual.getCodeNumber());
				} else {
					data.put("virtualName", "");
					data.put("virtualCode", "");
				}
				rt.setReturnDTO(data);
				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_SUCC);
				rt.setResultDesc("success");
			} else {
				rt.setResult(Constants.RESULT_SUCC);
				rt.setResultCode(Constants.RESULTCODE_NODATA);
				rt.setResultDesc("暂无用户数据");
			}
		} else {
			rt.setResult(Constants.RESULT_FIAL);
			rt.setResultCode(Constants.RESULTCODE_PARAMINVALID);
			rt.setResultDesc("无效参数");
		}
		String str = JSONObject.toJSONString(rt, SerializerFeature.WriteMapNullValue);
		if (StringUtils.isNotBlank(request.getParameter("callback"))) {
			return request.getParameter("callback") + "(" + str + ")";
		}
		return str;
	}


}
