package com.palmnest.webapp.controller.wechat;

import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.*;
import com.palmnest.application.dto.input.MeetingPushDto;
import com.palmnest.application.dto.output.FloorDto;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.RoleManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.virtProject.UserAccountService;
import com.palmnest.service.virtProject.VirtualAccountService;
import com.palmnest.webapp.controller.BaseFormController;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Controller
@RequestMapping(value = "/wechat/virtual/*")
public class WeChatVirtualArchController extends BaseFormController {


	private VirtualArchManager virtualArchManager;

	@Autowired
	public void setVirtualArchManager(VirtualArchManager virtualArchManager) {
		this.virtualArchManager = virtualArchManager;
	}

	@Autowired
	private UserManager            userManager;
	@Autowired
	private RoleManager            roleManager;
	@Autowired
	private FloorInfoManager       floorInfoManager;
	@Autowired
	private ScWxuserManager        scWxuserManager;
	@Autowired
	private EmigrationManager      emigrationManager;
	@Autowired
	private AppUserManager         appUserManager;
	@Autowired
	private UserAccountService     userAccountService;
	@Autowired
	private VirtualAccountService  virtualAccountService;
	@Autowired
	private ServiceTypeInfoManager serviceTypeInfoManager;
	
	@Autowired
	private PublicNoManager        publicNoManager;


	public static String host                = PropertiesKit.readPropertiesValue("meeting_index_url", "wechat.properties");
	public static String meeting_index_url   = PropertiesKit.readPropertiesValue("meeting_index_url", "wechat.properties");
	// 会议室推送详情url
	public static String meetingProDetailUrl = PropertiesKit.readPropertiesValue("meetingProDetailUrl", "wechat.properties");
	// webUrl
	public static String webUrl              = PropertiesKit.readPropertiesValue("webUrl", "wechat.properties");
	
	public static String newWebUrl              = PropertiesKit.readPropertiesValue("newWebUrl", "wechat.properties");


	/**
	 * 修改企业的时长
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/updateVirTimeInfo")
	@ResponseBody
	public AppResultDto updateVirTimeInfo(HttpServletRequest request, HttpServletResponse response) {
		String virId = request.getParameter("companyId");
//		String freeLenTime=request.getParameter("freeLenTime");
//		String remainderTime=request.getParameter("remainderTime");
		String useTime = request.getParameter("useTime");
		String msg     = "";
		if (StringUtils.isNotEmpty(virId) && StringUtils.isNotEmpty(useTime)) {
			try {
				msg = virtualArchManager.updateVirInfoByUseTime(virId, useTime);
				String code = "";
				if (StringUtils.isEmpty(msg)) {
					code = "200";
				} else {
					code = "100";
				}
				return AppResultUtil.createCommonDto(code, msg, null);
			} catch (Exception e) {
				e.printStackTrace();
				msg = "修改企业时长失败：" + e.getMessage();
				log.error("修改企业时长失败：" + e.getMessage());
			}
		}
		return AppResultUtil.createErrorDto("100", msg);
	}

	/**
	 * 获取企业的时长
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getVirTimeInfo")
	@ResponseBody
	public AppResultDto getVirTimeInfo(HttpServletRequest request, HttpServletResponse response) {
		String              virId = request.getParameter("companyId");
		Map<String, Object> map   = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(virId)) {
			try {
				VirtualArchitecture virInfo = virtualArchManager.get(Integer.parseInt(virId));
				if (virInfo != null) {
					map.put("freeLenTime", virInfo.getFreeLenTime() == null ? BigDecimal.ZERO : virInfo.getFreeLenTime());
					map.put("remainderTime", virInfo.getRemainderTime() == null ? BigDecimal.ZERO : virInfo.getRemainderTime());
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("获取企业时长失败：" + e.getMessage());
			}
		}
		return AppResultUtil.createSuccesDto(map);
	}


	/**
	 * 推送消息
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/sendPushMessage")
	@ResponseBody
	public AppResultDto sendPushMessage(@ModelAttribute("mePushDto") MeetingPushDto mePushDto, HttpServletRequest request, HttpServletResponse response) {
		try {
			virtualArchManager.sendPushMessage(mePushDto);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("推送消息失败，单据id为：" + mePushDto.getId() + "，错误信息为：" + e.getMessage());
		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 根据企业获取负责人的openId
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getOpenIdByCompanyId")
	@ResponseBody
	public AppResultDto getOpenIdByCompanyId(HttpServletRequest request, HttpServletResponse response) {
		String              virId = request.getParameter("companyId");
		Map<String, Object> map   = new HashMap<String, Object>();
		try {
			map = virtualArchManager.getOpenIdByCompanyId(virId);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取openId失败" + e.getMessage());
		}
		return AppResultUtil.createSuccesDto(map);
	}


	/**
	 * 获取用户所管理的楼层
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/getFloorBuUserId")
	@ResponseBody
	public AppResultDto getFloorBuUserId(HttpServletRequest request, HttpServletResponse response) {
		String         userId = request.getParameter("userId");
		List<FloorDto> list   = new ArrayList<FloorDto>();
		log.info("getFloorBuUserId====" + userId);
//		List<Role> roleList=roleManager.getRoleListByFuncCode(CodeConstants.MEETING_MANAGER,userId);
//		if(roleList!=null&&roleList.size()>0){
//			Role role=roleList.get(0);
		try {
//				List<AppUserFloorRelation> userFloorList=userManager.getAppUserFloorByUserId(Integer.parseInt(userId), Integer.parseInt(role.getId().toString()));
			List<Map<String, Object>> mapList = roleManager.getRoleListByFuncCode(CodeConstants.MEETING_MANAGER, userId);
			if (mapList != null && mapList.size() > 0) {
				for (int i = 0; i < mapList.size(); i++) {
					Map<String, Object> mapFloor = mapList.get(i);
					FloorDto            dto      = new FloorDto();
					if (mapFloor != null) {
						dto.setFloorId(mapFloor.get("floorId").toString());
						if (mapFloor.get("floorName") != null && StringUtils.isNotEmpty(mapFloor.get("floorName").toString())) {
							dto.setFloorName(mapFloor.get("floorName").toString() + "楼");
						}
					}
					list.add(dto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("获取楼层失败" + e.getMessage());
		}
//		}

		return AppResultUtil.createSuccesDto(list);
	}


	/**
	 * 登录微信用户根据userId查找对应的user,然后根据user查该用户负责的企业
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "getVirInfoList")
	@ResponseBody
	public AppResultDto getVirInfoList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String openId = request.getParameter("openId");
		String orgId  = request.getParameter("orgId");
		WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		if (StringUtils.isEmpty(orgId)) {
			if (wxUser != null && wxUser.getOrganizationId() != null) {
				orgId = wxUser.getOrganizationId().toString();
			}
			if (StringUtils.isEmpty(orgId)) {
				return AppResultUtil.createErrorDto("100", "项目不允许为空");
			}
		}
		Map<String, Object>     objMap = new HashMap<String, Object>();
		List<UserAccountRecode> list   = userAccountService.getUserAccountRecode(orgId, openId);
		if (list != null && list.size() > 0) {
			UserAccountRecode userAcc = list.get(0);
			if (userAcc != null) {
				VirtualAccount va = virtualAccountService.findById(userAcc.getAccountId());
				if (va != null) {
					BigDecimal                time    = new BigDecimal(0);
					List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
					VirtualArchitecture       virInfo = virtualArchManager.get(va.getVirId());
					if (virInfo != null) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("id", virInfo.getId());
						map.put("name", virInfo.getName());
						map.put("timeLen", virInfo.getRemainderTime());
						BigDecimal remainTime = virInfo.getRemainderTime();
						time = time.add(remainTime);
						mapList.add(map);
						objMap.put("count", 1);
						objMap.put("time", time);
						objMap.put("virList", mapList);
						return AppResultUtil.createSuccesDto(objMap);
					}
				}
			}
			return AppResultUtil.createSuccesDto("获取不到微信用户的企业信息", objMap);

//    	if(wxUser!=null){
//    		int userId=wxUser.getUserId();
//    		
//    		List<CommonDto> listDto=emigrationManager.getVirListByReman(userId);
//    		List<Map<String, Object>> mapList=new ArrayList<Map<String,Object>>();
//    		BigDecimal time=new BigDecimal(0);
//    		if(listDto!=null&&listDto.size()>0){
//    			for(int i=0;i<listDto.size();i++){
//    				CommonDto dto=listDto.get(i);
//    				VirtualArchitecture virInfo=virtualArchManager.get(Integer.parseInt(dto.getId().toString()));
//    				Map<String, Object> map=new HashMap<String, Object>();
//    				map.put("id", virInfo.getId());
//    				map.put("name", virInfo.getName());
//    				map.put("timeLen", virInfo.getRemainderTime());
//					BigDecimal remainTime=virInfo.getRemainderTime();
//					time=time.add(remainTime);
//    				mapList.add(map);
//        		}
//    			objMap.put("count", listDto.size());
//    			objMap.put("time", time);
//    			objMap.put("virList", mapList);
//    		}else {
//    			if(appUserManager.exists(userId)){
//    				AppUser userInfo=appUserManager.get(userId);
//    				VirtualArchitecture virInfo=virtualArchManager.get(userInfo.getVirtualArchId());
//    				Map<String, Object> map=new HashMap<String, Object>();
//    				map.put("id", virInfo.getId());
//    				map.put("name", virInfo.getName());
//    				map.put("timeLen", virInfo.getRemainderTime());
//    				time=virInfo.getRemainderTime();
//    				mapList.add(map);
//    			}
//    			objMap.put("count", mapList.size());
//    			objMap.put("time",time);
//    			objMap.put("virList", mapList);
//    		}

		}
		return AppResultUtil.createSuccesDto();
	}

	/**
	 * 获取会议室预约时绑定企业地址
	 *
	 * @param openId
	 * @return
	 */
	@RequestMapping(value = "getBandUrl")
	@ResponseBody
	public AppResultDto getBandUrl(String openId, String type) {
		WxUser  wxUser = scWxuserManager.getScWxuserByOpenId(openId);
		AppUser user   = null;
		String  url    = "";
		if (wxUser != null) {
			user = appUserManager.getAppUserByWxUserAndOrg(wxUser.getId(), wxUser.getOrganizationId());
			if ("index".equals(type)) {
				
				WxPublicno publicno      = publicNoManager.getByDevelopId(wxUser.getDevelopId());				
				
				//url = newWebUrl + "/wechat/index/homePageView?redirectUrl=%2Fwechat%2Findex%2FhomePageView&openId=" + openId + "&developId=" + wxUser.getDevelopId();
				url = newWebUrl + "/wx/main/?openid="+openId+"&state="+publicno.getId()+"#/home";
				
				return AppResultUtil.createSuccesDto(url);
				
			} else if ("userInfo".equals(type)) {
				url = webUrl + "/wechat/appUser/userInfo?openId=" + openId + "&developId=" + wxUser.getDevelopId() + "&organizationId=" + wxUser.getOrganizationId();
			} else if ("meetingFenxiangUrl".equals(type)) {

				//会议室分享链接 我要预定的链接
				List<ServiceTypeInfo> listServiceTypeInfo = serviceTypeInfoManager.getServiceTypeInfoByShkipAddress("wechat%2Fneigou%2FmeetingDo");
				if (null != listServiceTypeInfo && listServiceTypeInfo.size() >= 1) {
					url = listServiceTypeInfo.get(0).getSkipAddress();
				} else {
					url = "";
				}
			}
			if (user != null) {
				url += "&userId=" + wxUser.getUserId();
			}
			System.out.println("url:" + url);
			return AppResultUtil.createSuccesDto(url);
		}
		return AppResultUtil.createSuccesDto();
	}

	//获得会议室模板推送链接
	//参数：openid bookid
	@RequestMapping(value = "getMeetingProUrl")
	@ResponseBody
	public AppResultDto getMeetingProUrl(@RequestParam("bookId") String bookId, @RequestParam("openId") String openId) throws Exception {

		//String bookid = request.getParameter("bookId");
		//String openId = request.getParameter("openId");

		log.info("getMeetingProUrl==bookId==" + bookId);
		log.info("getMeetingProUrl==openId==" + openId);

		WxUser wxUser    = scWxuserManager.getScWxuserByOpenId(openId);
		String detailUrl = "";
		if (null != wxUser && null != wxUser.getOpenId()) {
			Long   datatimeStr  = new Date().getTime();
			String sso_codeData = wxUser.getOpenId() + "|" + datatimeStr;

			log.info("getMeetingProUrl wxUser.getOpenId()====" + wxUser.getOpenId());

			String token = GenPass.Encrypt(sso_codeData);

			//meetingProDetailUrl=?token=@token#/recorddetail?bookid=@bookid
			detailUrl = meeting_index_url + meetingProDetailUrl.replaceAll("@token", token).replaceAll("@bookid", bookId);
		}

		Map<String, Object> objMap = new HashMap<String, Object>();
		objMap.put("detailUrl", detailUrl);

		return AppResultUtil.createSuccesDto(objMap);
	}

	/**
	 * 会议室发送客服消息接口
	 *
	 * @param openIds
	 * @param url
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "sendMeetingMessage")
	@ResponseBody
	public AppResultDto sendMeetingMessage(String openIds, String url, String content) {
		if (StringUtils.isEmpty(openIds) || StringUtils.isEmpty(url) || StringUtils.isEmpty(content)) {
			return AppResultUtil.createErrorDto("100", "参数不能为空");
		}
		log.info("sendMeetingMessage/openIds:" + openIds);
		log.info("sendMeetingMessage/url:" + url);
		log.info("sendMeetingMessage/content:" + content);
		try {
			virtualAccountService.sendMeetingMessage(openIds, url, content);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("发送客服消息失败：" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "发送客服消息失败");
		}
		return AppResultUtil.createSuccesDto();
	}

	@RequestMapping(value = "getOpenIdByCode")
	@ResponseBody
	public AppResultDto getOpenIdByCode(String code) {
		String openId = "";
		if (StringUtils.isNotEmpty(code)) {
			String path = Constants.FOXCONN_URL + "?code=" + code + "&appid=" + Constants.FOXCONN_APPID;
			String jsonStr;
			try {
				jsonStr = HttpKit.get(path, false);
				JSONObject obj = JSONObject.fromObject(jsonStr);
				if (obj != null && obj.has("openid")) {
					openId = obj.get("openid").toString();
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
				return AppResultUtil.createErrorDto("100", e.getMessage());
			}
		}
		return AppResultUtil.createSuccesDto(openId);
	}


	public static void main(String[] args) {
//			URL url=new URL("http://civetInterface.foxconn.com/open/access_token?code=05520GPJg1joIw4Nwx9VG1RIVzZyERqmqBi1iUkGSKtiIUzE1&appid=CBac1EORQqU1");
		String path = "http://civetInterface.foxconn.com/open/access_token?code=64406ZDcRogAE6ywg8UnRa7PN3zJyoOAiSOoTU4EqDUGzYkk&appid=CBac1EORQqU1";
		String jsonStr;
		try {
			jsonStr = HttpPostUtil.sendPost(path, "");
			JSONObject obj = JSONObject.fromObject(jsonStr);
			System.out.println(obj.get("openid"));
			System.out.println(obj.get("expires_in"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendMsgSender() {/*
		 List<CivetArticle> Articles = new ArrayList<CivetArticle>(); 
		 CivetArticle article = new CivetArticle();
		 article.setAuthor("香信生活频道主动推送图文消息");//作者
		 article.setTitle("香信生活频道搭建说明");//标题
		 article.setDescription("生活频道是为香信用户提供服务的平台，而生活频道 开发接口则是提供服务的基础)， 开发者在生活频道网站中创建频道号、获 取接口权限后，可以通过阅读本接口文档来帮助开发。");//描述
		 //CivetValue<eMediaValType> e=new CivetValue<eMediaValType>();
		 //article.setImageMedia(e);
		 //article.setImageMedia(eMediaValType.ID, "e7271470-65fe-4445-9dfc70f2eab38514");
		 //article.setUrl("http://civetpublic.foxconn.com/SpecDoc/Index");   
		 Articles.add(article);

		 CivetMsgBase data = CivetNewsMsg.Create(Articles);
		 MsgSender sender = new MsgSender("[生活频道帐号]", "[高级接口调用密 码]");
		 String[] openIds={""};//openId数组
		 try {
			sender.SendByOpenID(data, openIds);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	*/
	}

}
