package com.icloud.server.payutils;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.icloud.server.payutils.dto.PayOrderDO;
import com.icloud.server.scala.paynotify.PayNotifyEntity;
import com.icloud.server.scala.paynotify.PayNotifyLogEntity;
import com.icloud.server.scala.paynotify.PayNotifyLogRepository;
import com.icloud.server.scala.paynotify.PayNotifyRepository;
import com.icloud.server.scala.payorder.PayOrderRepository;
import com.icloud.server.utils.log.Logs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.annotation.Resource;
import javax.xml.parsers.DocumentBuilder;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.LoggerFactory;
/**微信
 * @Author : yang
 * @Date : 2022-07-26 01:09
 * @Version : 2.1.2
 */

@Api("微信支付")
@RestController
@RequestMapping("/pay/order2")
@AllArgsConstructor
public class WxPayNotify {

//    private WxPayService wxService;
//    @Autowired
//    private WxPayService wxService;
//private WxPayService wxService;
    @Resource
    private PayNotifyRepository pnr;
    @Resource
    private PayNotifyLogRepository pnlr;
    @Resource
    private PayOrderRepository por;

    static Logger logger = LoggerFactory.getLogger("wxrepay");

//    private  pay = LoggerFactory.getLogger( "req" );

    @ApiOperation(value = "支付回调通知处理")
    @PostMapping("/notify/order/{channelId}")
    public String parseOrderNotifyResult(@RequestBody String xmlData, @PathVariable("channelId") Long channelId) throws WxPayException {
        System.out.println("======xmlData:"+xmlData);
        try {
            Map map = xmlToMap(xmlData);
            String transaction_id =(String) map.get("transaction_id");
            String nonce_str = (String)map.get("nonce_str");
            String bank_type = (String)map.get("bank_type");
            String openid = (String)map.get("openid");
            String sign = (String)map.get("sign");
            String fee_type = (String)map.get("fee_type");
            String mch_id = (String)map.get("mch_id");
            String cash_fee = (String)map.get("cash_fee");
            String out_trade_no = (String)map.get("out_trade_no");
            String appid = (String)map.get("appid");
            String total_fee = (String)map.get("total_fee");
            String trade_type = (String)map.get("trade_type");
            String result_code = (String)map.get("result_code");
            String time_end = (String)map.get("time_end");
            String is_subscribe = (String)map.get("is_subscribe");
            String return_code = (String)map.get("return_code");
            String attach = (String)map.get("attach");
//            System.out.println("transaction_id:"+transaction_id);
//            System.out.println("nonce_str:"+nonce_str);
//            System.out.println("bank_type:"+bank_type);
//            System.out.println("channelId:"+channelId);
            System.out.println("out_trade_no:"+out_trade_no);
//            System.out.println("attach:"+attach);


            //mysql --校验
            List<PayNotifyEntity> pnes = pnr.findByMerchantorderidAndOuttradenoAndStatus(out_trade_no, attach,0);
            if(!pnes.isEmpty()){
                PayNotifyLogEntity paynotifylogentity = new PayNotifyLogEntity().toEntity(nonce_str, xmlData, "wx", "wx", appid.toString());
                //log 日志----输出
                new Logs(logger).toLog( xmlData);
                //mysql 记录
                pnlr.save(paynotifylogentity);
                PayNotifyEntity entity = pnes.get(0);
                String merchantorderid = entity.getMerchantorderid();
                entity.setStatus(1);
                pnr.save(entity);
                PayOrderDO por1 = por.findByMerchantorderid(merchantorderid);
                por1.setStatus(1);
                //mysql --修改订单状态
                por.save(por1);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        //校验订单
//        wxService.queryOrder(transactionId, outTradeNo);
        // TODO 根据自己业务场景需要构造返回对象
        return WxPayNotifyResponse.success("成功");
    }

    public static Map xmlToMap(String strXML) throws Exception {
        try {
            Map data = new HashMap();
            // TODO 在这里更换
            DocumentBuilder documentBuilder = WXPayXmlUtil.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
//            WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }



//
//    public WxPayOrderNotifyResult parseOrderNotifyResult(String xmlData, String signType) throws WxPayException {
//        try {
//            log.debug("微信支付异步通知请求参数：{}", xmlData);
//            WxPayOrderNotifyResult result = WxPayOrderNotifyResult.fromXML(xmlData);
//            if (signType == null) {
//                if (result.getSignType() != null) {
//                    // 如果解析的通知对象中signType有值，则使用它进行验签
//                    signType = result.getSignType();
//                } else if (this.getConfig().getSignType() != null) {
//                    // 如果配置中signType有值，则使用它进行验签
//                    signType = this.getConfig().getSignType();
//                }
//            }
//
//            log.debug("微信支付异步通知请求解析后的对象：{}", result);
//            result.checkResult(this, signType, false);
//            return result;
//        } catch (WxPayException e) {
//            throw e;
//        } catch (Exception e) {
//            throw new WxPayException("发生异常！", e);
//        }
//    }
//
//    private WxOrderInfo parseXml(String xmlString) {
//        WxOrderInfo orderInfo = null;
//        XmlPullParser xmlPullParser = Xml.newPullParser(); //由android.util.Xml创建一个XmlPullParser实例
//        InputStream is = new ByteArrayInputStream(xmlString.getBytes());
//        try {
//            xmlPullParser.setInput(is, "UTF-8");               //设置输入流 并指明编码方式
//            int eventType =xmlPullParser.getEventType();
//            //eventType 默认值为0，每次调用parser.next()会自动向后读取
//            while(eventType != XmlPullParser.END_DOCUMENT){
//                switch (eventType){
//                    case XmlPullParser.START_TAG:
//                        if(xmlPullParser.getName().equals("xml")){
//                            orderInfo = new WxOrderInfo();
//                        }else if(xmlPullParser.getName().equals("appid")){
//                            eventType = xmlPullParser.next();
//                            orderInfo.appid = xmlPullParser.getText();
//                        }else if(xmlPullParser.getName().equals("noncestr")){
//                            eventType = xmlPullParser.next();
//                            orderInfo.noncestr = xmlPullParser.getText();
//                        }else if(xmlPullParser.getName().equals("package")){
//                            eventType = xmlPullParser.next();
//                            orderInfo.wxpackage = xmlPullParser.getText();
//                        }else if(xmlPullParser.getName().equals("partnerid")){
//                            eventType = xmlPullParser.next();
//                            orderInfo.partnerid = xmlPullParser.getText();
//                        }else if(xmlPullParser.getName().equals("prepayid")) {
//                            eventType = xmlPullParser.next();
//                            orderInfo.prepayid = xmlPullParser.getText();
//                        }else if(xmlPullParser.getName().equals("timestamp")) {
//                            eventType = xmlPullParser.next();
//                            orderInfo.timestamp = String.valueOf(Long.parseLong(xmlPullParser.getText())*1000);
//                        }else if(xmlPullParser.getName().equals("sign")) {
//                            eventType = xmlPullParser.next();
//                            orderInfo.sign = xmlPullParser.getText();
//                        }
//                        break;
//                    case XmlPullParser.END_TAG:
//                        if (xmlPullParser.getName().equals("xml")) {
//                            Log.i("tag","XML 解析完毕");
//                            eventType = xmlPullParser.next();
//                        }
//                        break;
//                }
//                eventType = xmlPullParser.next();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return orderInfo;
//    }




}
