package com.fjs.scenic.controller;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

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

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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fjs.scenic.entity.order.ErrorOrder;
import com.fjs.scenic.service.ord.ErrorOrderService;
import com.fjs.scenic.service.ord.OrdersService;
import com.fjs.scenic.utils.AESUtil;
import com.fjs.scenic.utils.MessageByAli;
import com.fjs.scenic.utils.WXPayUtil;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/wechat")
public class DressController {

	private Logger log = LoggerFactory.getLogger(DressController.class);

	@Autowired
	private OrdersService ordersService;
	@Autowired
	private ErrorOrderService errorOrderService;
	/*@Autowired
	private WxMpService wxMpService;
	@Autowired
	private UserService userService;
	@Autowired
	private HttpServletRequest request;*/
	
    /**
     * 阿里短信配置
     */
    @Value("${ACCESS_KEY_ID}")
    private String accessKeyId;
    @Value("${ACCESS_KEY_SECRET}")
    private String accessKeySecret;
    @Value("${SIGN_NAME}")
    private String singName;
    @Value("${CAPTACHA_PHONE}")
    private String captcha;

    @PostConstruct
    public void init() {
        MessageByAli.accessKeyId = this.accessKeyId;
        MessageByAli.accessKeySecret = this.accessKeySecret;
        MessageByAli.singName = this.singName;
        MessageByAli.captcha = this.captcha;
    }

	/**
	 * 微信支付消息的通知地址
	 */
	@ApiOperation(value = "", hidden = true)
	@RequestMapping(value = "/notify", method = RequestMethod.POST, produces = { "application/xml; charset=UTF-8" })
	public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setCharacterEncoding("utf-8");
		log.warn("微信支付消息的通知地址 ------------------- >");
		// 获得微信返回的消息
		InputStream inputStream = request.getInputStream();
		StringBuilder sb = new StringBuilder();
		int len = -1;
		byte[] buffer = new byte[1024];
		while ((len = inputStream.read(buffer)) != -1) {
			sb.append(new String(buffer, 0, len));
		}
		inputStream.close();
		// 开始验签
		Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
		LinkedHashMap<String, String> return_data = new LinkedHashMap<String, String>();
		// 判断签名是否正确
		if (!WXPayUtil.isSignatureValid(map)) {
			return_data.put("return_code", "FAIL");
			return_data.put("return_msg", "签名错误");
			log.error("微信支付异步回掉修改订单状态失败msg={}", return_data);
		} else {
			if (map.get("result_code").equals("SUCCESS")) {
				try {
					ordersService.pay(map.get("out_trade_no"), map.get("cash_fee"));
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					log.info("wechat/notify:微信支付成功回调,只要微信支付成功都通知微信成功，订单号{}", map.get("out_trade_no"));
					return_data.put("return_code", "<![CDATA[SUCCESS]]>");
					return_data.put("return_msg", "<![CDATA[OK]]>");
					String return_data_str = WXPayUtil.mapToXml(return_data).replaceAll("&lt;", "<").replaceAll("&gt;",
							">");
					response.getWriter().print(return_data_str);
				}
			} else {
				log.error("微信支付异步回掉修改订单状态失败msg={}", return_data);
			}
		}
	}

	/**
	 * 微信退款消息的通知地址
	 */
	@ApiOperation(value = "", hidden = true)
	@PostMapping(value = "/refund/notify")
	public String refundNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		log.warn("微信退款消息的通知地址 ------------------> ");
		// 获得微信返回的消息
		InputStream inputStream = request.getInputStream();
		StringBuilder sb = new StringBuilder();
		int len = -1;
		byte[] buffer = new byte[1024];
		while ((len = inputStream.read(buffer)) != -1) {
			sb.append(new String(buffer, 0, len));
		}
		inputStream.close();
		Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
		Map<String, String> return_data = new HashMap<String, String>();
		if ("SUCCESS".equals(map.get("return_code"))) {
			// 获得加密的字符串信息
			String req_info = map.get("req_info");
			// 解密消息
			String result = AESUtil.decryptData(req_info);
			Map<String, String> data = WXPayUtil.xmlToMap(result);
			log.info("微信退款通知,orderno={}",data.get("out_trade_no") );
			return_data.put("return_code", "SUCCESS");
			return_data.put("return_msg", data.get("refund_status"));
			// 处理退款
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			ordersService.updateByParam(" status=7,refund_time='" + format.format(new Date()) + "',refund_price='"
					+ data.get("refund_fee") + "' where order_no='" + data.get("out_trade_no") + "'");
			// TODO 删除异常订单
			//ordersService.sendMessage(data.get("out_trade_no"));
			ErrorOrder record = new ErrorOrder();
			record.setOrderNo(data.get("out_trade_no"));
			errorOrderService.delete(record);
			try {
				sendMessage(data.get("out_trade_no"),data.get("total_fee"));
			} catch (Exception e) {
				log.error("发送模板消息失败");
				e.printStackTrace();
			}
			return WXPayUtil.mapToXml(return_data);
		}

		log.warn("微信退款消息的通知地址 ------------------> ");
		return_data.put("return_code", "FAIL");
		return_data.put("return_msg", "退款验证签名失败");
		return WXPayUtil.mapToXml(return_data);
	}
	
	//@ApiOperation(value = "测试模板消息", notes = "测试模板消息", hidden = true)
    //@GetMapping(value = "/sendMessage")
    //@ResponseBody
	public void sendMessage(String ordersNo, String totalFee) {
		//ordersService.sendMessage(ordersNo);
		
		/*try {
			String openId = userService.getOpenIdByOrderNo(ordersNo);
			WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
					.toUser(openId)
					.templateId("t4OS-KiLdwbC6xkEfJqbHSPt-nqnTBfc6laylmX7EKI")
					.url("http://wx.fjsfjq.com:8088/#/myCenter").build();
			templateMessage.addData(new WxMpTemplateData("first", "订单退款提醒", "#173177"));
			templateMessage.addData(new WxMpTemplateData("keyword1", "订单号" + ordersNo + "已退款", "#173177"));
			templateMessage.addData(new WxMpTemplateData("keyword2", "退款金额"+Integer.parseInt(totalFee)/100+"元", "#173177"));
			templateMessage.addData(new WxMpTemplateData("remark", "退款成功,门票已失效", "#173177"));
			log.error("openid={}",request.getHeader(Cons.TOKEN.WECHAT));
			String openId = userService.getOpenIdByOrderNo(ordersNo);
			WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
					.toUser(openId)
					.templateId("wyNqGquqJYzRDmXNdbMbk75SV6RvlYI2zuVyhIn8jnI")
					.url("http://t.cqhsrj.com:8087").build();
			templateMessage.addData(new WxMpTemplateData("first", "订单退款提醒", "#173177"));
			templateMessage.addData(new WxMpTemplateData("keyword1", "订单号" + ordersNo + "已退款", "#173177"));
			templateMessage.addData(new WxMpTemplateData("keyword2", totalFee, "#173177"));
			templateMessage.addData(new WxMpTemplateData("keyword3", totalFee, "#173177"));
			templateMessage.addData(new WxMpTemplateData("keyword4", totalFee, "#173177"));
			templateMessage.addData(new WxMpTemplateData("remark", "退款成功,门票已失效", "#173177"));
			wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
		} catch (WxErrorException e) {
			log.error("模板消息发送失败ordersNo={}", ordersNo);
			e.printStackTrace();
		}*/
	}

}
