package com.fs.app.controller;


import com.fs.common.core.controller.BaseController;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsUser;
import com.fs.store.enums.*;
import com.fs.store.service.*;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Api("微信支付接口")
@RestController
@RequestMapping("/app/wxpay")
public class WxPayController {

    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private IFsStoreOrderStatusService orderStatusService;
    @Autowired
    private IFsUserService userService;
    /**
     * 微信回调
     * 回调接口代码内部自动校验结果签名和业务代码
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation("微信回调")
    @PostMapping("/wxPayNotify")
    @Transactional
    public String wxPayNotify(HttpServletRequest request) {

        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            System.out.println(result.getReturnCode());
            if("SUCCESS".equals(result.getReturnCode())){
                //订单号
                String outtradeno = result.getOutTradeNo();
                String tradeNo = result.getTransactionId();
                System.out.println(outtradeno);
                System.out.println(tradeNo);
                String[] orderId=outtradeno.split("-");
                switch (orderId[0]){
                    case "store":
                        return storeOrderOp(orderId[1],tradeNo);

                }
                return WxPayNotifyResponse.success("");
            }else{
                return WxPayNotifyResponse.success("");
            }

        } catch (Exception e) {
            logger.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }




    //处理订单
    @Synchronized
    private String storeOrderOp(String orderCode,String tradeNo) {

        //     //回滚事务
        //     TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        //     return WxPayNotifyResponse.fail("");
        //更新订单状态
        FsStoreOrder order=orderService.selectFsStoreOrderByOrderCode(orderCode);
        if(!order.getStatus().equals(OrderInfoEnum.STATUS_0.getValue())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return WxPayNotifyResponse.success("处理成功!");
        }
        FsStoreOrder storeOrder = new FsStoreOrder();
        storeOrder.setId(order.getId());
        storeOrder.setPaid(OrderInfoEnum.PAY_STATUS_1.getValue());
        storeOrder.setPayType("1");
        storeOrder.setStatus(OrderInfoEnum.STATUS_1.getValue());
        storeOrder.setPayTime(new Date());
        orderService.updateFsStoreOrder(storeOrder);
        //增加用户购买次数
        userService.incPayCount(order.getUserId());
        //增加状态
        orderStatusService.create(storeOrder.getId(), OrderLogEnum.PAY_ORDER_SUCCESS.getValue(),
                OrderLogEnum.PAY_ORDER_SUCCESS.getDesc());
        FsUser user=userService.selectFsUserById(order.getUserId());
        //增加流水
        String payTypeMsg = PayTypeEnum.WEIXIN.getDesc();

//        billService.addBill(user.getUserId(),
//                BillDetailEnum.CATEGORY_1.getValue(),
//                0,
//                BillDetailEnum.TYPE_1.getDesc(),
//                order.getPayPrice().doubleValue(), user.getNowMoney().doubleValue(),
//                payTypeMsg + order.getPayPrice() + "元购买商品",order.getId().toString());
        return WxPayNotifyResponse.success("处理成功");

    }

}
