package com.ruoyi.weChat.service;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.commons.math3.analysis.function.Add;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service
public class WeChatService {

	private static final Logger log = LoggerFactory.getLogger(WeChatService.class);


	@Value(value = "${wx.appId}")
	private String appId;
	@Value(value = "${wx.appSecret}")
	private String appSecret;
	@Value(value = "${wx.state}")
	private String wxState;

	@Autowired
	private RedisCache redisCache;




	/**
	 * 审批流程消息提醒
	 */
	private static final String SEND_TEMPLATE_ID ="2L9AJWl2yNfgd83Fw_f_E6HiaEvPf109iw_xFtI8PXI";



	/**
	 * 推送地址
	 */
	private static  String send_url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";





		public String getOpenId(String code) {
		String url = "https://api.weixin.qq.com/sns/jscode2session?";
		url=url+"appid="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";

		JSONObject js= HttpUtils.sendGetToJson(url);
		String openid=js.getString("openid");
		if (openid==null){
			log.error("openId 获取异常");
		}else {

			return openid;
		}
		return null;
	}

	public String getAccessToken() {
		Date date = new Date();
		String  access_token = redisCache.getCacheObject("access_token");
		if (access_token!=null) {
			log.debug("缓存读取access_token成功");
			return access_token;
		} else {
			return setSessionAccessToken();
		}
	}

	/**
	 *
	 * @return
	 */
	private String setSessionAccessToken() {
		String url =String.format(
				"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", appId,
				appSecret);
		JSONObject js= HttpUtils.sendGetToJson(url);
		String errcode =js.getString("errcode");
		Integer expires_in = js.getInteger("expires_in");
		String access_token=null;
		if (errcode!=null) {
			log.error("获取AccessToken失败！");
		}else {
			access_token = js.getString("access_token");
			redisCache.setCacheObject("access_token", access_token,expires_in, TimeUnit.SECONDS);
			log.debug("获取并存入AccessToken成功,accesstoken="+access_token);
		}
		return access_token;
	}


	public Integer addNotice(String openid ,Long id, Date date, String remarks){
		String dateTime= DateUtils.parseStrYYYYnMMyDDrHH_MM_SS(date);
		return addNotice(openid,id,dateTime,remarks);
	}


	/**
	 * 推送微信订阅信息，跳转为公出信息
	 * @param openid 发送对象微信openid
	 * @param remarks 发送信息，不能大于十五个字
	 */
	public Integer addNotice(String openid ,Long id, String dateTime, String remarks) {
		Map<String, Object> map=new HashMap<String, Object>();
		String accessToken=getAccessToken();
		String url=send_url.replace("ACCESS_TOKEN", accessToken);
		map.put("access_token", accessToken);
		map.put("template_id", SEND_TEMPLATE_ID);
		map.put("page", "pages/egressDetails/index?id="+id);
		map.put("touser", openid);
		map.put("data",getPublicData(dateTime,remarks));
		map.put("miniprogram_state", wxState);
		map.put("lang", "zh_CN");
		String resString = HttpUtils.sendJsonPost(url, map);
		JSONObject res = JSON.parseObject(resString);
		if (res.get("errcode")!=null) {
			log.error(String.format("errcode={%s}",res.getInteger("errcode").toString()));
			return res.getInteger("errcode");
		}else {
			return 1;
		}

	}


//
//	private Integer SendHttpPost(String params, String url) {
//		String res= HttpUtils.sendPost(url,params);
//		if (res.get("errcode")!=null) {
//			log.error(String.format("errcode={%s}",res.getInteger("errcode").toString()));
//			return res.getInteger("errcode");
//		}else {
//			return 1;
//		}
//	}

	/**
	 * 公出订阅消息组装
	 * @param dateTime 时间
	 * @param remarks 备注
	 * @return
	 */
	private Map<String, Object> getPublicData(String dateTime,  String remarks) {
		Map<String, Object> we=new HashMap<String, Object>();
		if (remarks.length()>20)remarks=remarks.substring(0,17)+"...";
			Map<String, Object> v1=new HashMap<String, Object>();
			v1.put("value",dateTime);
			we.put("time15", v1);
			Map<String, Object> v2=new HashMap<String, Object>();
			v2.put("value", remarks);
			we.put("thing13", v2);
		return we;
	}



}
