package com.ruoyi.web.controller.api;

/**
 * @ClassName ApiPayController
 * @Description 请描述类的业务用途
 * @Author linlinee
 * @Date 2021/12/1 5:47 PM
 * @Version 1.0
 **/

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mall.domain.MallOrderOrder;
import com.ruoyi.mall.service.IMallOrderOrderService;
import com.ruoyi.web.controller.utils.PayCommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
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.util.*;

@RequestMapping("/api/pay")
@Controller
public class ApiPayController {
    @Autowired
    private IMallOrderOrderService orderOrderService;

    @ResponseBody
    @RequestMapping("/weixinpayNotify")
    public Object weixinpayNotify(HttpServletRequest req, HttpServletResponse res) {
        try {
            InputStream inStream = req.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
            Map<Object, Object> mapFromXml = PayCommonUtil.doXMLParse(result);
//            log.error("mapFromXml::" +mapFromXml.toString());
            SortedMap<String ,String > sortedMap = new TreeMap();
            if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
                String orderSn = mapFromXml.get("out_trade_no").toString();
                MallOrderOrder orderOrder = orderOrderService.queryByOrderSn(orderSn);
                if (!"0".equals(orderOrder.getStatus())){
                    return "fail";
                }
                //  验签成功后
                orderOrder.setStatus("1");
                orderOrder.setPayType("1");
                
                orderOrder.setPayAt(DateUtils.getTime());
                orderOrderService.updateMallOrderOrder(orderOrder);
                sortedMap.put("return_code","SUCCESS");
                sortedMap.put("return_msg","OK");
                res.reset();
                res.getWriter().write(parseXML(sortedMap));

                //小票机打印
                //增加积分


            }else {
//                log.error("微信支付失败::");
                sortedMap.put("return_code","FAIL");
                sortedMap.put("return_msg","签名失败");
                res.reset();
                res.getWriter().write(parseXML(sortedMap));
//                log.error("map012::");
            }
            return "success";
        } catch (Exception e) {
            return "failure";
        }
    }

    //输出XML
    public String parseXML(Map map) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>\n");
        Set es = map.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if(null != v && !"".equals(v) && !"appkey".equals(k)) {

                sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
}
