package com.zcloud.controller.sms;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.invoice.BillingManageService;
import com.zcloud.service.sms.PayManagerService;
import com.zcloud.service.sms.PayService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.XMLUtil;
import org.apache.shiro.session.Session;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@RequestMapping("/pay")
public class PayController extends BaseController{
	@Autowired
	private PayService payService;
	@Autowired
	private PayManagerService paymanagerService;

	@Autowired
	private BillingManageService billingmanageService;
	@Autowired
	private CorpInfoService corpinfoService;
	 /**
		 * <p>统一下单入口</p>
		 *
		 * @throws Exception
		 */
		@RequestMapping(value="/payment")
		@ResponseBody
		@LogAnno(menuType= "综合管理",menuServer= "短信管理",instructionsOperate = "短信日志管理",instructionsType = "充值入口")
		public Object toPay() throws Exception {
			Map<String,Object> map = new HashMap<String,Object>();
			String errInfo = "success";
			PageData pd = new PageData();
			pd = this.getPageData();
//			if(pd.getString("openId")==null || pd.getString("openId")==""){
//				map.put("result", "error");
//				map.put("msg", "openId为空");
//				return map;
//			}
			//PageData sqepd =orderService.getSpeOrdernumber(pd);

			pd.put("ordernumber", DateUtil.getSdfTimes()+getNumber(9));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			pd.put("time_start", sdf.format(new Date()));
			pd.put("ORDER_BODY", "PAYSMS");
			pd.put("PRICE", "249.99");
			pd.put("time_start", sdf.format(new Date()));

		   	Map<String, String> resMap = payService.xcxPayment(pd);
		   	if("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))){

		   		PageData pmpd = new PageData();
				pmpd.put("TRADE_NO", pd.getString("ordernumber"));
				pmpd.put("ISSUCCESS", "待支付");
				pmpd.put("OPDATE",DateUtil.date2Str(new Date()));
				pmpd.put("MONEY",pd.getString("PRICE"));
				pmpd.put("CORPINFO_ID",Jurisdiction.getCORPINFO_ID());
				pmpd.put("PAYMANAGER_ID",this.get32UUID());
				paymanagerService.save(pmpd);

		   		//统一下单成功
		   		map.put("result", errInfo);
		   		map.put("pd",pd);
		   		map.put("msg", resMap);
				return map;
		   	}else{
		   		map.put("result", "error");
				map.put("msg", resMap.get("returnMsg"));
				return map;
		   }
		}

		@RequestMapping(value="/zypayment")
		@ResponseBody
		@LogAnno(menuType= "综合管理",menuServer= "短信管理",instructionsOperate = "短信日志管理",instructionsType = "充值")
		public Object toyz() throws Exception {
			Map<String,Object> map = new HashMap<String,Object>();
			PageData pd = new PageData();
			pd = this.getPageData();
			System.out.println("验证支付进来了");

			PageData opd = new PageData();
			if(pd.getString("ordernumber") != null){
				opd.put("TRADE_NO",  pd.getString("ordernumber"));
				opd=paymanagerService.findByOId(opd);
				if(opd.getString("ISSUCCESS").equals("支付成功")) {
					map.put("payType", "true");
				}else {
					map.put("payType", "false");
				}
			}
			map.put("result", "success");
			return map;
		}
		public static long getNumber(int length) {
	        StringBuilder buf = new StringBuilder();
	        Random random = new Random();
	/*开头不为0,建议数据量较少时只放开部分，比如1至3开头的数，等业务达到一定数量时，再逐步放开剩余的号码段，由于是固定位数，总数量一定，生成的数越多，重复的几率越大**/
	        int firstNumber = random.nextInt(9) + 1;
	        buf.append(firstNumber);

	        for(int i = 0; i < length - 1; ++i) {
	            buf.append(random.nextInt(10));
	        }

	        return Long.valueOf(buf.toString());
	    }

		 @RequestMapping(value = "/getnotify")
		    public void getnotify(HttpServletRequest request, HttpServletResponse response)
		            throws Exception {
		        System.out.println("微信支付回调");
		        PrintWriter writer = response.getWriter();
		        InputStream inStream = request.getInputStream();
		        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		        byte[] buffer = new byte[1024];
		        int len = 0;
		        while ((len = inStream.read(buffer)) != -1) {
		            outSteam.write(buffer, 0, len);
		        }
		        outSteam.close();
		        inStream.close();
		        String result = new String(outSteam.toByteArray(), "utf-8");
		        System.out.println("微信支付通知结果：" + result);
		        Map<String, String> map = null;
		        try {
		            /**
		             * 解析微信通知返回的信息
		             */
		            map = XMLUtil.doXMLParse(result);
		        } catch (JDOMException e) {
		            // TODO Auto-generated catch block
		            e.printStackTrace();
		        }
		        System.out.println("=========:"+result);
		        // 若支付成功，则告知微信服务器收到通知
				if (map.get("return_code").equals("SUCCESS")) {
					if (map.get("result_code").equals("SUCCESS")) {
						System.out.println("支付成功！");
						Session session = Jurisdiction.getSession();
						session.setAttribute(map.get("out_trade_no"), true);
						PageData opd = new PageData();
						opd.put("TRADE_NO",  map.get("out_trade_no"));
						opd=paymanagerService.findByOId(opd);
						if(opd!=null) {
							opd.put("ISSUCCESS", "支付成功");
							paymanagerService.edit(opd);
							PageData cpd = 	corpinfoService.findById(opd);
							if(cpd!=null) {
								PageData epd = new PageData();
								epd.put("CORPINFO_ID", cpd.getString("CORPINFO_ID"));
								epd.put("SMS_COUNT", Integer.parseInt(cpd.getString("SMS_COUNT"))+5000);
								corpinfoService.editSMSCOUNT(epd);
							}
							PageData bpd = new PageData();
							bpd.put("BILLINGMANAGE_ID", this.get32UUID());	//主键
							bpd.put("PAYMENTTIME", DateUtil.date2Str(new Date()));	//支付时间
							bpd.put("MONEY", "249.99");	//金额
							bpd.put("BILLINGSTATUS", "0");	//开票状态
							bpd.put("OPDATE", DateUtil.date2Str(new Date()));	//开票状态
							bpd.put("ISDELETE", "0");	//开票状态
							bpd.put("CORPINFO_ID", cpd.getString("CORPINFO_ID"));	//发票ID
							billingmanageService.save(bpd);

							PageData cepd = new PageData();
							cepd.put("ISREMIND", "0");
							cepd.put("CORPINFO_ID", cpd.getString("CORPINFO_ID"));
							corpinfoService.editISRemind(cpd);

						}
//						pmpd.put("ORDERNUMBER", map.get("out_trade_no"));
//						pmpd.put("STATUS", "1");
//						pmpd = orderbillService.findByOrderNumber(pmpd);
//						if (pmpd == null) {
//							PageData savepd = new PageData();
//							savepd.put("ORDERBILL_ID", this.get32UUID()); // 主键
//							savepd.put("ORDERNUMBER", map.get("out_trade_no"));
//							savepd.put("APPID",map.get("openid") );
//							savepd.put("STATUS",1);//付款
//							savepd.put("ISDELETE",0);
//							savepd.put("CREATTIME", DateUtil.date2Str(new Date()));
//							orderbillService.save(savepd);
//						}
					}
					 String notifyStr = XMLUtil.setXML("SUCCESS", "");
		             writer.write(notifyStr);
		             writer.flush();
		        }
		    }

}
