package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.HttpKit;
import com.palmnest.application.core.util.MD5;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.model.User;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.AppUserService;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
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.ResponseBody;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping(value = "/admin/other/*")
public class OtherProIntegrationController {


	private static       String      hostUrl         = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	private static       String      postHeadUrl     = PropertiesKit.readPropertiesValue("postHeadUrl", "wechat.properties");
	private static       String      meetingHeadUrl  = PropertiesKit.readPropertiesValue("meetingHeadUrl", "wechat.properties");
	private static       String      wjdcHeadUrl     = PropertiesKit.readPropertiesValue("wjdcHeadUrl", "wechat.properties");
	private static       String      tsbyHeadUrl     = PropertiesKit.readPropertiesValue("tsbyHeadUrl", "wechat.properties");
	private static final String      DEFAULT_CHARSET = "UTF-8";
	private static final String      APPKEY          = "1b02709a6681349beb43d737c504dec0";
	@Autowired
	private              UserManager userManager;

	@Autowired
	private AppUserService appUserService;

	@Autowired
	private OrganizationManager organizationManager;


	//会议室、小邮局 单点
	@RequestMapping(value = "/getPostOfficeUrl")
	@ResponseBody
	public AppResultDto getPostOfficeUrl(HttpServletRequest request, HttpServletResponse response) {
		User                user = userManager.getUserByUsername2(request.getRemoteUser());
		AppResultDto        dto  = new AppResultDto();
		Map<String, Object> map  = new HashMap<String, Object>();

		String       mettingClient    = "";//
		String       postofficeClient = "";
		List<OrgDto> dtos             = appUserService.getUserOrgs(user.getId());
		if (dtos != null && dtos.size() >= 1) {
			TbOrganization org = organizationManager.getOrganizationById(dtos.get(0).getId());
			mettingClient = org.getMettingClient();//会议室客户端编码
			postofficeClient = org.getPostofficeClient();
		}

		if (user == null) {
			String postUrl    = postHeadUrl + "/WebUI/TokenLogin.html?client=" + postofficeClient;
			String meetingUrl = meetingHeadUrl + "/WebUI/TokenLogin.html?client=" + mettingClient;

			map.put("postUrl", postUrl);
			map.put("meetingUrl", meetingUrl);
			dto = AppResultUtil.createSuccesDto(map);
			return dto;
		}
		String userName     = user.getUsername();
		long   time         = System.currentTimeMillis();
		String timeStamp    = String.valueOf(time);
		String password     = user.getPassword();
		String userFullName = user.getFullName();
		if (StringUtils.isNotEmpty(userFullName)) {
			try {
				userFullName = URLEncoder.encode(URLEncoder.encode(userFullName, DEFAULT_CHARSET), DEFAULT_CHARSET);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				log.error(e.getMessage());
				String postUrl    = postHeadUrl + "/WebUI/TokenLogin.html?client=" + postofficeClient;
				String meetingUrl = meetingHeadUrl + "/WebUI/TokenLogin.html?client=" + mettingClient;
				map.put("postUrl", postUrl);
				map.put("meetingUrl", meetingUrl);
				dto = AppResultUtil.createSuccesDto(map);
				return dto;
			}
		}
//    	System.out.println("加密前："+userName+timeStamp+APPKEY+password);
		String token = MD5.sign(userName + timeStamp + APPKEY + password, "", DEFAULT_CHARSET);
//    	System.out.println("加密后："+token);
		String postUrl    = postHeadUrl + "/WebUI/TokenLogin.html?client=" + postofficeClient + "&userName=" + userName + "&timeStamp=" + timeStamp + "&token=" + token + "&password=" + password + "&userFullName=" + userFullName;
		String meetingUrl = meetingHeadUrl + "/WebUI/TokenLogin.html?client=" + mettingClient + "&userName=" + userName + "&timeStamp=" + timeStamp + "&token=" + token + "&password=" + password + "&userFullName=" + userFullName;
		map.put("postUrl", postUrl);
		map.put("meetingUrl", meetingUrl);


		String pcToken = (String) request.getSession().getAttribute("PcToken");

		String wjdcHeadUrl = this.wjdcHeadUrl + "?token=" + pcToken;
		try {
			String result = HttpKit.HttpClientPost("", pcToken, this.wjdcHeadUrl);

			log.info("wjx getManager result:" + result);
			JSONObject jsonObject = JSONObject.parseObject(result);
			String sdata = jsonObject.getString("data");
			jsonObject  = JSONObject.parseObject(sdata);
			String mgrUrl = jsonObject.getString("url");
			log.info("wjx getManager url:" + mgrUrl);
			wjdcHeadUrl = mgrUrl;
		}catch (Exception ex2)
		{
			log.error(ex2.getMessage());
		}


		String tsbyHeadUrl = this.tsbyHeadUrl + "?token=" + pcToken;

		map.put("wjdcHeadUrl", wjdcHeadUrl);//问卷调查
		map.put("tsbyHeadUrl", tsbyHeadUrl);//投诉表扬

		dto = AppResultUtil.createSuccesDto(map);
		return dto;


	}
}
