package com.cweb.notify;

import com.hfkj.channel.weixin.utils.IOUtil;
import com.hfkj.channel.weixin.utils.XmlUtil;
import com.hfkj.config.device.SoundService;
import com.hfkj.entity.BsDevice;
import com.hfkj.entity.BsTradeOrder;
import com.hfkj.entity.BsTradeOrderMsg;
import com.hfkj.entity.BsTradeOrderProfitSharing;
import com.hfkj.service.BsDeviceService;
import com.hfkj.service.BsTradeOrderMsgService;
import com.hfkj.service.BsTradeOrderProfitSharingService;
import com.hfkj.service.BsTradeOrderService;
import com.hfkj.sysenum.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xml.sax.SAXException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @className: WeiXinController
 * @author: HuRui
 * @date: 2022/11/23
 **/
@Controller
@Api(value = "微信支付通知")
@RequestMapping(value = "/weiXinNotify")
public class WeiXinController {

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

    @Resource
    private BsTradeOrderMsgService tradeOrderMsgService;

    @Resource
    private BsDeviceService deviceService;

    @Resource
    private SoundService soundService;

    @Resource
    private BsTradeOrderService tradeOrderService;

    @Resource
    private BsTradeOrderProfitSharingService tradeOrderProfitSharingService;

    @RequestMapping(value="/jsapiPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "交易【主扫】通知")
    public void jsapiPay(HttpServletRequest request, HttpServletResponse response){
        try {
            log.info("微信支付 -> 异步通知：处理开始");
            String resXml = "<xml> <return_code><![CDATA[SUCCESS]]></return_code>" +
                            " <return_msg><![CDATA[OK]]></return_msg> </xml> ";
            String notifyXml = IOUtil.inputStreamToString(request.getInputStream(), "UTF-8");
            log.info("微信支付 -> 异步通知数据：", notifyXml);

            SortedMap<String, String> map = XmlUtil.parseXmlToTreeMap(notifyXml, "UTF-8");

            // 请求记录
            BsTradeOrderMsg orderMsg = new BsTradeOrderMsg();
            orderMsg.setOutTradeNo(map.get("out_trade_no"));
            orderMsg.setType(TradeOrderMsgTypeEnum.type2.getNumber());
            orderMsg.setResponseContent(notifyXml);
            tradeOrderMsgService.editTradeOrderMsg(orderMsg);

            if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
                tradeOrderService.paySuccess(map.get("out_trade_no"),map.get("transaction_id"),
                        PlatformTypeEnum.type4,
                        TradeOrderPayModeEnum.WECHAT,
                        new BigDecimal(map.get("total_fee")).divide(new BigDecimal("100")),
                        map.get("sub_mch_id"),
                        new HashMap<>());
            }
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
            log.info("微信支付 -> 异步通知：处理完成");
        } catch (Exception e) {
            log.error("login error!",e);
        }
    }

    @RequestMapping(value="/test",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "交易【主扫】通知")
    public void test(@RequestBody String reqBody, HttpServletRequest request, HttpServletResponse response){
        try {
            log.info("微信支付 -> 异步通知：处理开始");
            String resXml = "<xml> <return_code><![CDATA[SUCCESS]]></return_code>" +
                    " <return_msg><![CDATA[OK]]></return_msg> </xml> ";
            String notifyXml = reqBody;
            log.info("微信支付 -> 异步通知数据：", notifyXml);

            SortedMap<String, String> map = XmlUtil.parseXmlToTreeMap(notifyXml, "UTF-8");

            // 请求记录
            BsTradeOrderMsg orderMsg = new BsTradeOrderMsg();
            orderMsg.setOutTradeNo(map.get("out_trade_no"));
            orderMsg.setType(TradeOrderMsgTypeEnum.type2.getNumber());
            orderMsg.setResponseContent(notifyXml);
            tradeOrderMsgService.editTradeOrderMsg(orderMsg);

            if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
                // 查询订单
                BsTradeOrder order = tradeOrderService.getOrderByOutTradeNo(map.get("out_trade_no"));
                if (order != null && order.getStatus().equals(TradeOrderStatusEnum.status1.getNumber())) {
                    order.setPayMode(TradeOrderPayModeEnum.WECHAT.getCode());
                    order.setPlatformType(PlatformTypeEnum.type4.getNumber());
                    order.setPlatformMerNo(map.get("sub_mch_id"));
                    order.setPlatformTradeNo(map.get("transaction_id"));
                    order.setTradeActualAmount(new BigDecimal(map.get("total_fee")).divide(new BigDecimal("100")));
                    // order.setStatus(TradeOrderStatusEnum.status3.getNumber());
                    order.setPayTime(new Date());
                    tradeOrderService.editOrder(order);

                    new Thread(() -> {
                        Map<String,Object> param = new HashMap<>();
                        param.put("storeId", order.getStoreId());
                        param.put("deviceType", DeviceTypeEnum.type1.getNumber());
                        param.put("status", DeviceStatusEnum.status1.getNumber());
                        List<BsDevice> deviceList = deviceService.getDeviceList(param);
                        for (BsDevice device : deviceList) {
                            soundService.sendPayMsg(device.getDeviceNo(), order.getTradeAmount());
                        }
                    });

                    // 创建分账
                    if (order.getProfitSharingStatus().equals(true)) {
                        tradeOrderProfitSharingService.createProfitSharing(order);
                    }
                }
            }
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
            log.info("微信支付 -> 异步通知：处理完成");
        } catch (Exception e) {
            log.error("login error!",e);
        }
    }

}
