package cn.myapps.support.weixin.controller;

import cn.myapps.authtime.common.service.AuthTimeServiceManager;
import cn.myapps.authtime.user.model.UserVO;
import cn.myapps.authtime.user.service.UserProcess;
import cn.myapps.base.web.WebUser;
import cn.myapps.common.data.ParamsTable;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.common.util.Security;
import cn.myapps.common.util.StringUtil;
import cn.myapps.constans.Web;
import cn.myapps.support.weixin.WeixinServiceProxy;
import net.sf.json.JSONObject;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController(value="WeixinServiceAction")
@RequestMapping(value="/api/portal/weixin/jsapi")
@Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class WeixinServiceController {

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpSession session;

	protected static final String ACTION_RESULT_KEY = "status";
	protected static final int ACTION_RESULT_VALUE_SUCCESS = 1;
	protected static final int ACTION_RESULT_VALUE_FAULT = 0;

	protected static final String ACTION_MESSAGE_KEY = "message";
	protected static final String ACTION_DATA_KEY = "data";

	protected ParamsTable params;

	//将会被Struts2序列化为JSON字符串的对象,用来作为控制层返回结果的容器
	protected Map<String, Object> dataMap = new HashMap<String, Object>();

	@RequestMapping(value="/getJsapiConfig.action")

	public Map<String, Object> getJsapiConfig(){
		try {
			WebUser user = getUser();
			ParamsTable params = getParams();
			String url = params.getParameterAsString("_url");
			Map<String, String> config = WeixinServiceProxy.getJsapiConfig(url ,user.getDomainid());
			return addActionResult(true, "", config);
		} catch (Exception e) {
			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value="/upload.action")
	public Map<String, Object> doUpload(){
		try {
			//System.out.print("jsapi 回调--->doUpload");
			WebUser user = getUser();
			ParamsTable params = getParams();
			String serverId = params.getParameterAsString("serverId");
			String folder  = params.getParameterAsString("folder");
			String fileType = params.getParameterAsString("fileType");
			folder = StringUtil.isBlank(folder)? "photo" :folder;
			fileType = StringUtil.isBlank(fileType)? "jpg" :fileType;
			////System.out.println("serverId--->"+serverId);
			String path = "/uploads/"+folder+"/"+Calendar.getInstance().get(Calendar.YEAR)+"/"+UUID.randomUUID().toString()+"."+fileType;
//			String fileName = ServletActionContext.getRequest().getRealPath(path);
			File dir = new File( PropertyUtil.getPath() +File.separator+ "uploads"+File.separator+folder+File.separator+Calendar.getInstance().get(Calendar.YEAR));
			if(!dir.exists()){
				dir.mkdirs();
			}
			WeixinServiceProxy.downloadMedia(user.getDomainid(), serverId, path);
			////System.out.println("fileName--->"+fileName);

			return addActionResult(true, "", path);
		} catch (Exception e) {

			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}

	@RequestMapping(value="/PMupload.action")
	public Map<String, Object> doPMUpload(){
		try {
			WebUser user = getUser();
			ParamsTable params = getParams();
			String serverId = params.getParameterAsString("serverId");
			String taskid = params.getParameterAsString("taskid");
			String folder  = params.getParameterAsString("folder");
			String fileType = params.getParameterAsString("fileType");
			String time = params.getParameterAsString("time");
			folder = StringUtil.isBlank(folder)? "photo" :folder;
			fileType = StringUtil.isBlank(fileType)? "jpg" :fileType;
			////System.out.println("serverId--->"+serverId);
			String path = "/uploads/"+folder+"/"+UUID.randomUUID().toString()+"."+fileType;
			String fileName = PropertyUtil.getPath() + path;
			File dir = new File(PropertyUtil.getPath()+"/uploads/"+folder);
			if(!dir.exists()){
				dir.mkdirs();
			}
			WeixinServiceProxy.downloadMedia(user.getDomainid(), serverId, path);

			fileName = fileName.replace(".amr", ".mp3");

			File f2 = new File(fileName);
			Map<String, String> resultInfo = new HashMap<String, String>();
			Map<Object, Object> fileMap = new HashMap<Object, Object>();
			Map<Object, Object> fileMap2 = new HashMap<Object, Object>();
			String name = f2.getName();
			String id = UUID.randomUUID().toString();
			long size = f2.length();
			resultInfo.put("id", id);
			resultInfo.put("name", name);
			resultInfo.put("size", String.valueOf(size));
			resultInfo.put("taskid", taskid);
			// 生成文件名：
			resultInfo.put("url",path);

			fileMap.put("id", id);
			fileMap.put("name", name);
			fileMap.put("time", time);
			fileMap2.put(id, fileMap);

//			String attachjson = JsonUtil.toJson(fileMap2);
			//
			try {

//				TaskServiceImpl process = new TaskServiceImpl();
//				process.addAttachment(taskid, attachjson);
			} catch (Exception e) {
				e.printStackTrace();
			}
//			String result = JsonUtil.toJson(resultInfo);
//			//System.out.println("attachjson-->" + attachjson);

			return addActionResult(true, "", resultInfo);

			////System.out.println("fileName--->"+fileName);
		} catch (Exception e) {

			e.printStackTrace();
			return addActionResult(false, e.getMessage(), null);
		}
	}


	public ParamsTable getParams() {
		if (params == null) {
			params = ParamsTable.convertHTTP(this.request);

			params.setSessionid(this.request.getSession().getId());

			if (params.getParameter("_pagelines") == null){
				params.setParameter("_pagelines", Web.DEFAULT_LINES_PER_PAGE);
			}
		}

		return params;
	}

	public ParamsTable getParams(HttpServletRequest request) {
		if (params == null) {
			params = ParamsTable.convertHTTP(request);

			params.setSessionid(request.getSession().getId());

			if (params.getParameter("_pagelines") == null){
				params.setParameter("_pagelines", Web.DEFAULT_LINES_PER_PAGE);
			}
		}
		return params;
	}


	public WebUser getUser(){

		WebUser user = null;

		if (session == null || AuthTimeServiceManager.getWebUser(request) == null){
			if(isFromWeixin()){
				return getUserFromCookie();
			}else
				return null;
		}
		else{
			user = AuthTimeServiceManager.getWebUser(request);
		}

		return user;
	}

	/**
	 * 是否来自微信
	 * @param request
	 * @return
	 */
	private boolean isFromWeixin() {
		HttpServletRequest request = this.request;
		String userAgent = request.getHeader("user-agent");
		if(userAgent.contains("MicroMessenger")) return true;
		return false;
	}

	private WebUser getUserFromCookie(){
		HttpServletRequest request = this.request;
		Cookie[] cookies = request.getCookies();

		if(cookies == null) return null;

		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if("WEB_USER_COOKIE_KEY".equals(cookie.getName())){
				String value = Security.decryptPassword(cookie.getValue());
				if(value !=null){
					JSONObject jo = JSONObject.fromObject(value);
					String loginno = jo.getString("loginNo");
					if(!StringUtil.isBlank(loginno)){
						UserProcess process;
						try {
							process = AuthTimeServiceManager.userRuntimeService();
							UserVO user = (UserVO)process.login(loginno);
							if(user !=null){
								WebUser webUser = new WebUser(user);
								WebUser.setWebUser(webUser, request);
								return webUser;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				}

			}
		}

		return null;
	}

	/**
	 * Struts2序列化指定属性时，必须有该属性的getter方法
	 * @return
	 */
	public Map<String, Object> getDataMap() {
		return dataMap;
	}
	/**
	 * 添加Action处理结果
	 * @param isSuccess
	 * 		是否成功处理
	 * @param message
	 * 		返回消息
	 * @param data
	 * 		返回数据
	 * @return
	 */
	public Map<String, Object> addActionResult(boolean isSuccess,String message,Object data){
		dataMap.put(ACTION_RESULT_KEY, isSuccess?ACTION_RESULT_VALUE_SUCCESS : ACTION_RESULT_VALUE_FAULT );
		dataMap.put(ACTION_MESSAGE_KEY, message);
		if(data != null){
			dataMap.put(ACTION_DATA_KEY, data);
		}
		return dataMap;
	}

}
