package com.palmnest.service.estateserve.release.impl;

import com.alibaba.fastjson.JSON;
import com.palmnest.application.GoodsCodeConstants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.DateHelper;
import com.palmnest.application.core.util.GenPass;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.PropertiesKit;
import com.palmnest.application.dto.input.GoodsReleaseBillInputDto;
import com.palmnest.dao.estateserve.VirtUserDao;
import com.palmnest.dao.release.GoodsReleaseDao;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.VirtUserInfo;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.notice.WxtemplateMessageTypeModel;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.model.release.GoodsRelease;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.service.estateserve.release.GoodsReleaseManager;
import com.palmnest.service.impl.GenericManagerImpl;
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.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("goodsReleaseManager")
public class GoodsReleaseManagerImpl extends GenericManagerImpl<GoodsRelease, Long> implements GoodsReleaseManager {


	private GoodsReleaseDao goodsReleaseDao;

	@Autowired
	public void setGoodsReleaseDao(GoodsReleaseDao goodsReleaseDao) {
		this.goodsReleaseDao = goodsReleaseDao;
		this.dao = goodsReleaseDao;
	}

	@Autowired
	private UserManager         userManager;
	@Autowired
	private AppUserManager      appUserManager;
	@Autowired
	private VirtUserDao         virtUserDao;
	@Autowired
	private ReplayContentDao    replayContentDao;
	@Autowired
	private WeChatApiManager    weChatApiManager;
	@Autowired
	private ScWxuserManager     scWxuserManager;
	@Autowired
	private VirtualArchManager  virtualArchManager;
	@Autowired
	private ElementGroupManager elementGroupManager;


	public static String host                     = PropertiesKit.readPropertiesValue("hostUrl", "wechat.properties");
	public static String wxReleaseAuditUrl        = PropertiesKit.readPropertiesValue("wxReleaseAuditUrl", "wechat.properties");
	public static String wxReleaseRecordDetailUrl = PropertiesKit.readPropertiesValue("wxReleaseRecordDetailUrl", "wechat.properties");
	//审批结果
	public static String auditResultTempleteId    = PropertiesKit.readPropertiesValue("auditResultTempleteId", "wechat.properties");
	//放行审批通知
	public static String releaseAuditTempleteId   = PropertiesKit.readPropertiesValue("releaseAuditTempleteId", "wechat.properties");

	public static String goodsTsOrgs        = PropertiesKit.readPropertiesValue("goodsTsOrgs", "wechat.properties");
	
	public List<Integer> getGoodsOrgs(){
		if(StringUtils.isEmpty(goodsTsOrgs)){
			return null;
		}
		String [] arr=goodsTsOrgs.split(",");
		if(arr == null || arr.length <= 0){
			return null;
		}
		List<Integer> list=new ArrayList<Integer>();
		for(int i=0;i<arr.length;i++){
			if(StringUtils.isEmpty(arr[i])){
				continue;
			}
			list.add(Integer.parseInt(arr[i]));
		}
		if(CollectionUtils.isEmpty(list)){
			return null;
		}
		return list;
	}
	@Override
	public Page findPageBy(Map<String, Object> params, int pageSize, int pageNo) {

		return goodsReleaseDao.findPageBy(params, pageSize, pageNo);
	}

	@Override
	public Page findRecordPageBy(Map<String, Object> params, int pageSize, int pageNo) {

		return goodsReleaseDao.findRecordPageBy(params, pageSize, pageNo);
	}

	@Override
	public Page findStatisticsPageBy(Map<String, Object> params, int pageSize, int pageNo) {

		return goodsReleaseDao.findStatisticsPageBy(params, pageSize, pageNo);
	}

	@Override
	public Integer findCountBy(Map<String, Object> params) {

		return goodsReleaseDao.findCountBy(params);
	}

	/**
	 * 微信物品放行申请后 要发模板消息给负责人审批
	 * 判断物品放行权限
	 */
	@Async
	public void sendWechat(GoodsReleaseBillInputDto dto) {

		log.info("sendWechat===========");
		/*申请人姓名：{{keyword1.DATA}}
		放行企业：{{keyword2.DATA}}
		申请时间：{{keyword3.DATA}}
		放行物品：{{keyword4.DATA}}
		申请人电话：{{keyword5.DATA}}*/
		try {
			List<WxtemplateMessageTypeModel> templateList = replayContentDao.getWxTemplateByTempId(0, releaseAuditTempleteId);

			//根据企业id查出相应的负责人----要给两个负责人发送
			if (StringUtils.isNotEmpty(String.valueOf(dto.getCompanyid()))) {//放行公司查两个两个负责人
				List<VirtUserInfo> list = virtUserDao.getVirUserByVirId(Integer.valueOf(String.valueOf(dto.getCompanyid())));
				if (list != null && list.size() > 0) {
					for (int k = 0; k < list.size(); k++) {
						VirtUserInfo virUserInfo = list.get(k);
						int          userId      = virUserInfo.getUserId();//这个是tb_user表中的id

						AppUser appUser = null;
						if (appUserManager.exists(userId)) {
							appUser = appUserManager.get(userId);
						} else {
							log.info("sendWechat 没有找到 userId===========" + userId);
						}

						if (!(null != appUser && appUser.getIsReleasePower() == 1)) {
							continue;//没有物品放行权限不发推送
						}
						WxUser wxUser = scWxuserManager.getScWxuserByUserId(userId);
						if (wxUser != null) {
							if (!CollectionUtils.isEmpty(templateList)) {
								String templateId = (String) templateList.get(0).getTemplateid();

								Map<String, String> paramMap = new HashMap<String, String>();
								paramMap.put("developId", wxUser.getDevelopId());
								paramMap.put("openId", wxUser.getOpenId());
								//paramMap.put("openId", "o4L9Qty_oT8c4lWUQnkQ9ZAXgG_U");


								paramMap.put("templateId", templateId);

								paramMap.put("title", "您好！您已收放行申请消息一则，请审核！");

								String new_id   = encodeNewId(dto.getId().toString());
								String auditUrl = host + wxReleaseAuditUrl.replaceAll("@id", new_id).replaceAll("@openId", wxUser.getOpenId());

								paramMap.put("url", auditUrl);//微信端 放行审批url
								paramMap.put("keyword1", dto.getApplyUser());

								VirtualArchitecture vir = virtualArchManager.get(Integer.parseInt(String.valueOf(dto.getCompanyid())));
								if (null != vir && StringUtils.isNotEmpty(vir.getName())) {
									paramMap.put("keyword2", vir.getName());
								} else {
									paramMap.put("keyword2", "");
								}
								paramMap.put("keyword3", DateHelper.formatDate(new Date(), DateHelper.CURRENT_DATE));
								//paramMap.put("keyword4",elementGroupManager.getElementId(dto.getReleaseType()).getItemname());
								paramMap.put("keyword5", dto.getApplyTel());
								paramMap.put("remark", "请您及时处理！");
								String str = weChatApiManager.sendTemplateMsg11(paramMap);
								//JSONObject json = JSONObject.parseObject(str); 
								//String errmsg=json.get("errmsg").toString();

								log.info(str);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			log.info(LogExceptionStackUtil.LogExceptionStack(e));
		}

	}

	@Override
	public void sendNextAgreeWechat(GoodsRelease bill, WxUser wxUser) {
		log.info("WxGoodsReleaseController sendNextAgreeWechat.bill======{}",JSON.toJSONString(bill));
		log.info("WxGoodsReleaseController sendNextAgreeWechat.wxUser======{}",JSON.toJSONString(wxUser));

		if (wxUser != null) {

			String new_id    = encodeNewId(bill.getId().toString());
			//String detailUrl = host + wxReleaseAuditUrl.replaceAll("@id", new_id).replaceAll("@orgId", bill.getOrgId().toString());
			
			log.info("WxGoodsReleaseController sendNextAgreeWechat.wxReleaseAuditUrl======{}",wxReleaseAuditUrl);
			String detailUrl = wxReleaseAuditUrl.replaceAll("@id", bill.getId().toString());
			detailUrl = detailUrl.replaceAll("@virId", bill.getVirAccountId());
			detailUrl = detailUrl.replaceAll("@orgId", bill.getOrgId().toString());
			detailUrl = detailUrl.replaceAll("@userId", wxUser.getUserId().toString());
			detailUrl = detailUrl.replaceAll("@openId", wxUser.getOpenId().toString());
			log.info("WxGoodsReleaseController sendNextAgreeWechat.detailUrl======{}",detailUrl);

			
//			String content = "你好，你有新的电子放行单待审核！";
//			content += "<a href=\""+detailUrl+"\">点击审核>></a>";

			//String content = "你的企业有人发起了电子放行条申请，请前往服务之窗电子放行条放行审核模块审核相应的放行申请单！";
			String content = "你的企业有人发起了电子放行条申请,请前往服务之窗 > 电子放行条 > 企业审核模块审核相应的放行申请单！";
			List<Integer> goodsOrgs=getGoodsOrgs();
			if(null != bill.getOrgId() && null != goodsOrgs && goodsOrgs.contains(bill.getOrgId().intValue())){
				content = "你的企业有人发起了电子放行条申请,请前往员工之窗 > 电子放行条 > 放行审批模块审核相应的放行申请单!";
			}
			//content += "<a href=\"" + detailUrl + "\">去审批>></a>";
			if (bill.getApplyType() == 1) {
				content = "你的企业有人发起了电子通行证申请，请前往服务之窗电子通行证审核模块审核相应的电子通行证单！";
			}
			content += "<a href=\"" + detailUrl + "\">去审批>></a>";
			
			log.info("WxGoodsReleaseController sendNextAgreeWechat.sendServiceWithOpenId content ======>",content);
			weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
		}
	}


	/**
	 * 放行同意后发通知 根据creatorBillId(openid
	 */
	@Override
	public void sendAgreeWechat(GoodsRelease bill, String remark) {

//		List<WxtemplateMessageTypeModel> templateList=replayContentDao.getWxTemplateByTempId(0, auditResultTempleteId);
//		if(!CollectionUtils.isEmpty(templateList)){
//			String templateId=(String) templateList.get(0).getTemplateid();
//			Map<String,String> paramMap=new HashMap<String,String>();
//			boolean bool=scWxuserManager.exists(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));
//			if(bool){
//				WxUser wxUser=scWxuserManager.get(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));
//				String detailUrl=host+wxReleaseRecordDetailUrl.replaceAll("@id", bill.getId().toString());
//				paramMap.put("developId", wxUser.getDevelopId());
//				paramMap.put("openId", wxUser.getOpenId());
//				paramMap.put("templateId", templateId);
//				paramMap.put("url", detailUrl);
//				paramMap.put("title","您好！您已通过贵司审核！");
//				paramMap.put("type", "物品放行");//审核类型
//				paramMap.put("result", "审核通过");//审核结果
//				paramMap.put("suggestion", "同意放行");//审核原因
//				paramMap.put("remark", "感谢您的配合，祝您生活愉快！");
//				String str=weChatApiManager.sendTemplateMsg02(paramMap);
//				log.info(str);
//			}
//		}
		WxUser wxUser = scWxuserManager.get(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));

		if (wxUser != null) {

			String new_id    = encodeNewId(bill.getId().toString());
			String detailUrl = host + wxReleaseRecordDetailUrl.replaceAll("@id", new_id).replaceAll("@orgId", bill.getOrgId().toString());
			String content   = "你好，你的电子放行单已经审核通过，请点击详情查看放行二维码！";

			if (bill.getApplyType() == 1) {
				content = "你好，你的电子通行证已经审核通过，请点击详情查看放行二维码！";
				detailUrl = detailUrl.replace("release", "applyPass");
			}

			content += "<a href=\"" + detailUrl + "\">查看详情>></a>";

			weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
		}

	}


	private String encodeNewId(String oldId) {

		String new_id = "";
		try {
			new_id = URLEncoder.encode(GenPass.Encrypt(oldId), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new_id;
	}

	/**
	 * 拒绝同意后发通知 根据creatorBillId(openid
	 */
	@Override
	public void sendRefuseWechat(GoodsRelease bill, String remark) {

//		List<WxtemplateMessageTypeModel> templateList=replayContentDao.getWxTemplateByTempId(0, auditResultTempleteId);
//		if(!CollectionUtils.isEmpty(templateList)){
//			String templateId=(String) templateList.get(0).getTemplateid();
//			Map<String,String> paramMap=new HashMap<String,String>();
//			boolean bool=scWxuserManager.exists(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));
//			if(bool){
//				WxUser wxUser=scWxuserManager.get(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));
//				String detailUrl=host+wxReleaseRecordDetailUrl.replaceAll("@id", bill.getId().toString());
//				paramMap.put("developId", wxUser.getDevelopId());
//				paramMap.put("openId", wxUser.getOpenId());
//				paramMap.put("templateId", templateId);
//				paramMap.put("url", detailUrl);
//				paramMap.put("title","您好！您已通过贵司审核！");
//				paramMap.put("type", "物品放行");//审核类型
//				paramMap.put("result", "审核不通过");//审核结果
//				paramMap.put("suggestion",remark);//审核原因
//				paramMap.put("remark", "感谢您的配合，祝您生活愉快！");
//				String str=weChatApiManager.sendTemplateMsg02(paramMap);
//				log.info(str);
//			}
//		}

		WxUser wxUser = scWxuserManager.get(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));

		if (wxUser != null) {
			String new_id    = encodeNewId(bill.getId().toString());
			String detailUrl = host + wxReleaseRecordDetailUrl.replaceAll("@id", new_id).replaceAll("@orgId", bill.getOrgId().toString());
			String content   = "抱歉，你的电子放行单审核未通过！拒绝理由：" + remark;

			if (bill.getApplyType() == 1) {
				content = "抱歉，你的电子通行证审核未通过！拒绝理由：" + remark;
				detailUrl = detailUrl.replace("release", "applyPass");
			}

			content += " <a href=\"" + detailUrl + "\">查看详情>></a>";

			weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
		}

	}



	/**
	 * 安保放行后给下单人提醒
	 */
	@Override
	public void sendReleaseWechat(GoodsRelease bill, String remark) {

		try {
			WxUser wxUser = scWxuserManager.get(Integer.valueOf(String.valueOf(bill.getCreatorBillId())));

			if (wxUser != null) {

				String new_id    = encodeNewId(bill.getId().toString());
				String detailUrl = host + wxReleaseRecordDetailUrl.replaceAll("@id", new_id).replaceAll("@orgId", bill.getOrgId().toString());
				String content   = "你好，你的电子放行单";

				if (bill.getApplyType() == 1) {
					content = "你好，你的电子通行证";
					detailUrl = detailUrl.replace("release", "applyPass");
				}

				if (bill.getReleaseStatus().equals(GoodsCodeConstants.ST_YETRELEASE)) {
					content += "已放行";
				} else if (bill.getReleaseStatus().equals(GoodsCodeConstants.ST_REFUSE)) {
					content += "已被拒绝，拒绝原因：" + remark;
				}
				content += "，<a href=\"" + detailUrl + "\">查看详情>></a>";

				weChatApiManager.sendServiceWithOpenId(wxUser.getDevelopId(), wxUser.getId(), content);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}


	}

	@Override
	public List<Map<String, Object>> getVirIdsByOpenId(String openId, Integer isReleasePower) {

		return goodsReleaseDao.getVirIdsByOpenId(openId, isReleasePower);
	}

	@Override
	public List<GoodsRelease> getGoodsReleaseByParams(Map<String, Object> params) {

		return goodsReleaseDao.getGoodsReleaseByParams(params);
	}

	@Override
	public List<Map<String, Object>> reportExcel(Map<String, Object> params) {

		return goodsReleaseDao.reportExcel(params);
	}

	@Override
	public List<Map<String, Object>> reportStatistics(Map<String, Object> params) {

		return goodsReleaseDao.reportStatistics(params);
	}

	@Override
	public List<Map<String, Object>> reportRecord(Map<String, Object> params) {

		return goodsReleaseDao.reportRecord(params);
	}

	@Override
	public List<Map<String, Object>> getStatisticsData(Map<String, Object> params) {

		return goodsReleaseDao.getStatisticsData(params);
	}
}
