package com.palmnest.service.wechat.impl;

import com.palmnest.application.Constants;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.dao.estateserve.*;
import com.palmnest.dao.property.PropertyDao;
import com.palmnest.model.Element;
import com.palmnest.model.estateserve.WxPublicno;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.virtProject.VirtualArchService;
import com.palmnest.service.wechat.WeChatIndexManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("weChatIndexManager")
public class WeChatIndexManagerImpl implements WeChatIndexManager {


	@Autowired
	private ServiceProjectAllocationDao  serviceProjectAllocationDao;
	@Autowired
	private ContractIinformationOrderDao contractIinformationOrderDao;
	@Autowired
	private AppUserDao                   appUserDao;
	@Autowired
	private PublicNoDao                  publicNoDao;
	@Autowired
	private PropertyDao                  propertyDao;
	@Autowired
	private ScWxuserDao                  scWxuserDao;
	@Autowired
	private VirtualArchService           virtualArchService;

	@Override
	public Map<String, Object> getServiceListAll(String openId,
												 String developId, String orgId) {
		List<Map<String, Object>> resulList   = null;
		List<Map<String, Object>> serviceList = null;
		Map<String, Object>       reusltMaps  = new HashMap<String, Object>();
		WxPublicno                pub         = new WxPublicno();
		try {
			if (StringUtils.isNotEmpty(developId)) {
				pub = publicNoDao.getByDevelopId(developId);
			}
			//已认证
			//type 0 ，项目 ；1，企业
			resulList = serviceProjectAllocationDao.getServiceProjectAllocationList(orgId, "0");
			String serviceType = "";
			for (Map<String, Object> resultMap : resulList) {
				serviceType = resultMap.get("serviceType") + "";
				Object object = reusltMaps.get("serviceMap" + serviceType);

				String imgUrl = resultMap.get("customIcon") + "";//获取自定义图标路径
				if (StringUtils.isBlank(imgUrl) || "null".equalsIgnoreCase(imgUrl)) {
					imgUrl = resultMap.get("serviceIcon") + "";//获取默认图标路径
				}

				String resUrl = resultMap.get("skipAddress") + "";// 未认证跳转链接
				String url    = resultMap.get("jumpAddress") + "";// 认证后跳转链接
				String code   = resultMap.get("serviceCode") + "";// 服务编码
				//serviceNumber
				String serviceNumber         = resultMap.get("serviceNumber") + "";// 服务编码
				String status                = resultMap.get("status") + "";//服务状态 0-下线 1-上线 2-灰度
				String grayWechatServiceIcon = resultMap.get("grayWechatServiceIcon") + "";//微信端灰度图标
				String linkUrlType           = (String) resultMap.get("linkUrlType");
				if (pub != null && linkUrlType.equals("0")) {// 0-内链才替换，1-外链不替换
					if (StringUtils.isNotEmpty(resUrl) && resUrl.indexOf("/wx/outlink") != -1) {// 维修服务
						resultMap.put("skipAddress", getPXUrl(resUrl, developId, openId));
						log.info("服务连接：reUrl:" + resultMap.get("skipAddress"));
					}
					if (StringUtils.isNotEmpty(url) && url.indexOf("/wx/outlink") != -1) {
						resultMap.put("jumpAddress", getPXUrl(url, developId, openId));
						log.info("服务连接：reUrl:" + resultMap.get("jumpAddress"));
					}/*else if(StringUtils.isNotEmpty(url)&&code.indexOf("postoffice")!=-1) {
						// 小邮局不处理
						log.info("小邮局服务连接：reUrl:"+resultMap.get("skipAddress"));
					}*/ else {
						resultMap.put("skipAddress", getUrl(resUrl, pub.getAppId(), pub.getId().toString() + ";" + code));
						log.info("服务连接：reUrl:" + resultMap.get("skipAddress"));
						resultMap.put("jumpAddress", getUrl(url, pub.getAppId(), pub.getId().toString() + ";" + code));
						log.info("服务连接：reUrl:" + resultMap.get("jumpAddress"));
					}
				}
				//充值中心
				if ("CZZX".equals(serviceNumber) && StringUtil.isNotEmpty(orgId)) {
					log.info("服务连接：resUrl:" + resUrl);
					log.info("服务连接：url:" + url);
					if (StringUtil.isNotEmpty(resUrl)) {
						if ("?".equals(resUrl)) {
							resUrl = resUrl + "&zhwycode=zhwy" + orgId;
						} else {
							resUrl = resUrl + "?zhwycode=zhwy" + orgId;
						}
					}
					if (StringUtil.isNotEmpty(url)) {
						if ("?".equals(url)) {
							url = url + "&zhwycode=zhwy" + orgId;
						} else {
							url = url + "?zhwycode=zhwy" + orgId;
						}
					}
					resultMap.put("skipAddress", resUrl);
					log.info("服务连接：resUrl:" + resultMap.get("skipAddress"));
					resultMap.put("jumpAddress", url);
					log.info("服务连接：url:" + resultMap.get("jumpAddress"));
				}
//				//企业饭卡---登录后且企业饭卡ID不为空的情况下，跳转到B端地址，否则跳转到C端地址
//				if("QYFK".equals(serviceNumber)&&dto!=null&&StringUtil.isNotEmpty(dto.getFoodCardNo())&&dto.getIsLogin()!=null&&2==dto.getIsLogin()){
//					log.info("QYFK--服务连接：resUrl:"+resUrl);
//					log.info("QYFK--服务连接：url:"+url);
//					if(StringUtil.isNotEmpty(dto.getFoodCardH5())){
//						String reUrl=dto.getFoodCardH5()+"?spid="+dto.getFoodCardNo()+"&out_account_id="+openId+"&name="+dto.getUserName()+"&mobile="+dto.getMobile();
//						log.info("QYFK--reUrl:"+reUrl);
//						resultMap.put("skipAddress",reUrl);
//						log.info("QYFK--服务连接：resUrl:"+resultMap.get("skipAddress"));
//						resultMap.put("jumpAddress", reUrl);
//						log.info("QYFK--服务连接：url:"+resultMap.get("jumpAddress"));
//					}
//				}

				resultMap.put("serviceIcon", Constants.IMAGE_SERVER + imgUrl);//给图片路径拼接前缀
				resultMap.put("isGray", "2".equals(status) ? true : false);//是否灰度
				resultMap.put("grayWechatServiceIcon", Constants.IMAGE_SERVER + (StringUtils.isBlank(grayWechatServiceIcon) ? imgUrl : grayWechatServiceIcon));//给图片路径拼接前缀
				if (object == null) {
					serviceList = new ArrayList<Map<String, Object>>();
					serviceList.add(resultMap);
					reusltMaps.put("serviceMap" + serviceType, serviceList);
				} else {
					serviceList = (List<Map<String, Object>>) object;
					serviceList.add(resultMap);
				}
			}
			return reusltMaps;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	@Override
	public List<Map<String, Object>> getServiceListCategory(String openId,
															String developId, String orgId) {

		List<Map<String, Object>> finalList = new ArrayList<Map<String, Object>>();//最终返回的结果
		List<Map<String, Object>> resulList = null;//查询结果list

		List<Element> categoryList = serviceProjectAllocationDao.getElementsByGroupName("serviceCategory");//服务分类列表
		WxPublicno    pub          = new WxPublicno();
		try {
			if (StringUtils.isNotEmpty(developId)) {
				pub = publicNoDao.getByDevelopId(developId);
			}

			resulList = serviceProjectAllocationDao.getServiceProjectAllocationList(orgId, "0");
			for (Element element : categoryList) {
				Map<String, Object> categoryMap = new HashMap<String, Object>();
				categoryMap.put("categoryId", element.getItemcode());
				categoryMap.put("categoryName", element.getItemname());

				List<Map<String, Object>> categorys = new ArrayList<Map<String, Object>>();

				for (Map<String, Object> resultMap : resulList) {

					String serviceCategory = resultMap.get("serviceCategory") + "";//服务类别
					String serviceType     = resultMap.get("serviceType") + "";//服务分类 0-企业服务包 1-键件服务 2-商圈
					if (!serviceCategory.equals(element.getItemcode()) || !"0".equals(serviceType)) {//如果该服务不属于此分类或者不是企业服务包类型,则跳过
						continue;
					}

					String imgUrl = resultMap.get("customIcon") + "";//获取自定义图标路径
					if (StringUtils.isBlank(imgUrl) || "null".equalsIgnoreCase(imgUrl)) {
						imgUrl = resultMap.get("serviceIcon") + "";//获取默认图标路径
					}

					String resUrl = resultMap.get("skipAddress") + "";
					String url    = resultMap.get("jumpAddress") + "";
					String code   = resultMap.get("serviceCode") + "";
					//serviceNumber
					String serviceNumber         = resultMap.get("serviceNumber") + "";// 服务编码
					String grayWechatServiceIcon = resultMap.get("grayWechatServiceIcon") + "";//微信端灰度图标
					String status                = resultMap.get("status") + "";//服务状态 0-下线 1-上线 2-灰度
					String linkUrlType           = (String) resultMap.get("linkUrlType");
					if (pub != null && linkUrlType.equals("0")) {//内链才替换，外链不替换
						if (StringUtils.isNotEmpty(resUrl) && resUrl.indexOf("/wx/outlink") != -1) {
							resultMap.put("skipAddress", getPXUrl(resUrl, developId, openId));
							log.info("服务连接：reUrl:" + resultMap.get("skipAddress"));
						}
						if (StringUtils.isNotEmpty(url) && url.indexOf("/wx/outlink") != -1) {
							resultMap.put("jumpAddress", getPXUrl(url, developId, openId));
							log.info("服务连接：reUrl:" + resultMap.get("jumpAddress"));
						}/*else if((StringUtils.isNotEmpty(resUrl)&&resUrl.indexOf("postoffice")!=-1)|| (StringUtils.isNotEmpty(url)&&url.indexOf("postoffice")!=-1)) {
							//小邮局不处理
							log.info("小邮局服务连接：reUrl:"+resultMap.get("skipAddress"));
						}*/ else {
							resultMap.put("skipAddress", getUrl(resUrl, pub.getAppId(), pub.getId().toString() + ";" + code));
							log.info("服务连接：reUrl:" + resultMap.get("skipAddress"));
							resultMap.put("jumpAddress", getUrl(url, pub.getAppId(), pub.getId().toString() + ";" + code));
							log.info("服务连接：reUrl:" + resultMap.get("jumpAddress"));
						}
					}

					//充值中心
					if ("CZZX".equals(serviceNumber) && StringUtil.isNotEmpty(orgId)) {
						log.info("服务连接：resUrl:" + resUrl);
						log.info("服务连接：url:" + url);
						if (StringUtil.isNotEmpty(resUrl)) {
							if ("?".equals(resUrl)) {
								resUrl = resUrl + "&zhwycode=zhwy" + orgId;
							} else {
								resUrl = resUrl + "?zhwycode=zhwy" + orgId;
							}
						}
						if (StringUtil.isNotEmpty(url)) {
							if ("?".equals(url)) {
								url = url + "&zhwycode=zhwy" + orgId;
							} else {
								url = url + "?zhwycode=zhwy" + orgId;
							}
						}
						resultMap.put("skipAddress", resUrl);
						log.info("服务连接：resUrl:" + resultMap.get("skipAddress"));
						resultMap.put("jumpAddress", url);
						log.info("服务连接：url:" + resultMap.get("jumpAddress"));
					}
//					//企业饭卡---登录后且企业饭卡ID不为空的情况下，跳转到B端地址，否则跳转到C端地址
//					if("QYFK".equals(serviceNumber)&&dto!=null&&StringUtil.isNotEmpty(dto.getFoodCardNo())&&dto.getIsLogin()!=null&&2==dto.getIsLogin()){
//						log.info("QYFK--服务连接：resUrl:"+resUrl);
//						log.info("QYFK--服务连接：url:"+url);
//						if(StringUtil.isNotEmpty(dto.getFoodCardH5())){
//							String reUrl=dto.getFoodCardH5()+"?spid="+dto.getFoodCardNo()+"&out_account_id="+openId+"&name="+dto.getUserName()+"&mobile="+dto.getMobile();
//							log.info("QYFK--reUrl:"+reUrl);
//							resultMap.put("skipAddress",reUrl);
//							log.info("QYFK--服务连接：resUrl:"+resultMap.get("skipAddress"));
//							resultMap.put("jumpAddress", reUrl);
//							log.info("QYFK--服务连接：url:"+resultMap.get("jumpAddress"));
//						}
//					}

					resultMap.put("serviceIcon", Constants.IMAGE_SERVER + imgUrl);//给图片路径拼接前缀
					if (resultMap.get("grayWechatServiceIcon") == null || StringUtils.isBlank(grayWechatServiceIcon)) {
						resultMap.put("grayWechatServiceIcon", Constants.IMAGE_SERVER + imgUrl);//给图片路径拼接前缀

					} else {
						resultMap.put("grayWechatServiceIcon", Constants.IMAGE_SERVER + grayWechatServiceIcon);//给图片路径拼接前缀

					}
					resultMap.put("isGray", "2".equals(status) ? true : false);//是否灰度

					categorys.add(resultMap);//将此对象放入该分类对象中
				}

				if (null != categorys && categorys.size() > 0) {
					categoryMap.put("serviceList", categorys);
					finalList.add(categoryMap);
				}
			}

			return finalList;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getDiscoverServiceList(String orgId) {
		List<Map<String, Object>> resulList = null;
		try {
			resulList = serviceProjectAllocationDao.getDiscoverServiceList();

			if (resulList == null) {
				return null;
			}

			for (Map<String, Object> resultMap : resulList) {
//				String imgUrl = resultMap.get("customIcon")+"";//获取自定义图标路径
//				if (StringUtils.isBlank(imgUrl) || "null".equalsIgnoreCase(imgUrl)){//如果自定义图标为空,使用服务默认图标
//					imgUrl = resultMap.get("serviceIcon")+"";//获取默认图标路径
//				}
//
//				String status = resultMap.get("status")+"";//服务状态 0-下线 1-上线 2-灰度
//				String grayWechatServiceIcon = resultMap.get("grayWechatServiceIcon")+"";//微信端灰度图标
				String imgUrl = resultMap.get("serviceIcon") + "";//获取图标路径
				resultMap.put("serviceIcon", Constants.IMAGE_SERVER + imgUrl);//给图片路径拼接前缀
				//request
//				resultMap.put("isGray","2".equals(status)?true :false);//是否灰度
//				//灰度图标 给图片路径拼接前缀
//				resultMap.put("grayWechatServiceIcon", Constants.IMAGE_SERVER +(StringUtils.isBlank(grayWechatServiceIcon)? imgUrl : grayWechatServiceIcon));
				//serviceNumber
				String serviceNumber = resultMap.get("serviceNumber") + "";// 服务编码
				//充值中心
				if ("CZZX".equals(serviceNumber) && StringUtil.isNotEmpty(orgId)) {
					String resUrl = resultMap.get("skipAddress") + "";
					String url    = resultMap.get("jumpAddress") + "";
					log.info("服务连接：resUrl:" + resUrl);
					log.info("服务连接：url:" + url);
					if (StringUtil.isNotEmpty(resUrl)) {
						if ("?".equals(resUrl)) {
							resUrl = resUrl + "&zhwycode=zhwy" + orgId;
						} else {
							resUrl = resUrl + "?zhwycode=zhwy" + orgId;
						}
					}
					if (StringUtil.isNotEmpty(url)) {
						if ("?".equals(url)) {
							url = url + "&zhwycode=zhwy" + orgId;
						} else {
							url = url + "?zhwycode=zhwy" + orgId;
						}
					}
					resultMap.put("skipAddress", resUrl);
					log.info("服务连接：resUrl:" + resultMap.get("skipAddress"));
					resultMap.put("jumpAddress", url);
					log.info("服务连接：url:" + resultMap.get("jumpAddress"));
				}
			}

		} catch (Exception e) {
			log.info("WeChatIndexManagerImpl getDiscoverServiceList Error{}", e.getMessage());
		}

		return resulList;
	}

	@Override
	public List<Map<String, Object>> discoverServiceListCategory(String orgId) {

		List<Map<String, Object>> finalList = new ArrayList<Map<String, Object>>();//最终返回的结果
		List<Map<String, Object>> resulList = null;//查询结果list

		List<Element> categoryList = serviceProjectAllocationDao.getElementsByGroupName("serviceCategory");//服务分类列表

		try {

			resulList = serviceProjectAllocationDao.getDiscoverServiceList();

			for (Element element : categoryList) {
				Map<String, Object> categoryMap = new HashMap<String, Object>();
				categoryMap.put("categoryId", element.getItemcode());
				categoryMap.put("categoryName", element.getItemname());

				List<Map<String, Object>> categorys = new ArrayList<Map<String, Object>>();

				for (Map<String, Object> resultMap : resulList) {

					String serviceCategory = resultMap.get("serviceCategory") + "";//服务类别
					String serviceType     = resultMap.get("serviceType") + "";//服务分类 0-企业服务包 1-键件服务 2-商圈
					if (!serviceCategory.equals(element.getItemcode()) || !"2".equals(serviceType)) {//如果该服务不属于此分类或者不是商圈发现服务包类型,则跳过
						continue;
					}

					String imgUrl = resultMap.get("customIcon") + "";//获取自定义图标路径
					if (StringUtils.isBlank(imgUrl) || "null".equalsIgnoreCase(imgUrl)) {
						imgUrl = resultMap.get("serviceIcon") + "";//获取默认图标路径
					}

					String grayWechatServiceIcon = resultMap.get("grayWechatServiceIcon") + "";//微信端灰度图标
					String status                = resultMap.get("status") + "";//服务状态 0-下线 1-上线 2-灰度

					resultMap.put("serviceIcon", Constants.IMAGE_SERVER + imgUrl);//给图片路径拼接前缀
					if (resultMap.get("grayWechatServiceIcon") == null || StringUtils.isBlank(grayWechatServiceIcon)) {
						resultMap.put("grayWechatServiceIcon", Constants.IMAGE_SERVER + imgUrl);//给图片路径拼接前缀
					} else {
						resultMap.put("grayWechatServiceIcon", Constants.IMAGE_SERVER + grayWechatServiceIcon);//给图片路径拼接前缀

					}
					resultMap.put("isGray", "2".equals(status) ? true : false);//是否灰度
					String serviceNumber = resultMap.get("serviceNumber") + "";
					//充值中心
					if ("CZZX".equals(serviceNumber) && StringUtil.isNotEmpty(orgId)) {
						String resUrl = resultMap.get("skipAddress") + "";
						String url    = resultMap.get("jumpAddress") + "";
						log.info("服务连接：resUrl:" + resUrl);
						log.info("服务连接：url:" + url);
						if (StringUtil.isNotEmpty(resUrl)) {
							if ("?".equals(resUrl)) {
								resUrl = resUrl + "&zhwycode=zhwy" + orgId;
							} else {
								resUrl = resUrl + "?zhwycode=zhwy" + orgId;
							}
						}
						if (StringUtil.isNotEmpty(url)) {
							if ("?".equals(url)) {
								url = url + "&zhwycode=zhwy" + orgId;
							} else {
								url = url + "?zhwycode=zhwy" + orgId;
							}
						}
						resultMap.put("skipAddress", resUrl);
						log.info("服务连接：resUrl:" + resultMap.get("skipAddress"));
						resultMap.put("jumpAddress", url);
						log.info("服务连接：url:" + resultMap.get("jumpAddress"));
					}

					categorys.add(resultMap);//将此对象放入该分类对象中
				}

				if (null != categorys && categorys.size() > 0) {
					categoryMap.put("serviceList", categorys);
					finalList.add(categoryMap);
				}
			}

			return finalList;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	public String getUrl(String str1, String appid, String state) {
		String reUrl = "";
		if (StringUtils.isNotEmpty(str1)) {
			if (str1.indexOf("appid=") != -1) {
				reUrl = str1.substring(0, str1.indexOf("appid=") + 6) + appid + str1.substring(str1.indexOf("&", 1), str1.lastIndexOf("=") + 1) + state;
				if (reUrl.indexOf("realse") != -1) {
					reUrl += "&moduleCode=2";
				}
				if (reUrl.indexOf("emig") != -1) {
					reUrl += "&moduleCode=1";
				}
				reUrl += str1.substring(str1.lastIndexOf("#"));
			} else {
				reUrl = str1;
			}

		}
		return reUrl;
	}

	public String getPXUrl(String str, String developId, String openId) {
//		String reUrl=str.substring(0,str.indexOf("openid="))+"openid="+openId+"&developid="+developId+str.substring(str.indexOf("&projectno="));
		String projectno = "";
		//获取当前登录用户所选择的项目id
		WxUser wxUser = scWxuserDao.getScWxuserByOpenId(openId);
		if (wxUser != null) {
			//根据项目id查询绑定的航电项目id
			TbOrganization organization = propertyDao.getTbOrganizationById(wxUser.getOrganizationId());
			if (organization != null) {
				projectno = organization.getHdProjectId();
			}
		}

		String reUrl = str.substring(0, str.indexOf("openid=")) + "openid=" + openId + "&developid=" + developId + "&projectno=" + projectno;
		return reUrl;
	}
}
