package com.bonus.canteen.core.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.bonus.canteen.core.account.constants.AccTradeStateEnum;
import com.bonus.canteen.core.account.constants.AccTradeTypeEnum;
import com.bonus.canteen.core.account.constants.AccWalletIdEnum;
import com.bonus.canteen.core.account.domain.AccTrade;
import com.bonus.canteen.core.account.domain.WalletUpdateDTO;
import com.bonus.canteen.core.account.service.AccSubService;
import com.bonus.canteen.core.account.service.IAccTradeService;
import com.bonus.canteen.core.account.service.IAccWalletInfoService;
import com.bonus.canteen.core.pay.constants.AliPayTradeStatusEnum;
import com.bonus.canteen.core.pay.constants.PayChannelEnum;
import com.bonus.canteen.core.pay.constants.PayStateEnum;
import com.bonus.canteen.core.account.domain.vo.AccTradeVo;
import com.bonus.canteen.core.pay.constants.PayTypeEnum;
import com.bonus.canteen.core.pay.util.AlipayConfig;
import com.bonus.common.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "支付异步通知")
@RestController
@RequestMapping("/alipay/notify")
public class NotifyCotroller {

    @Autowired
    IAccTradeService accTradeService;
    @Autowired
    AccSubService accSubService;
    @Autowired
    @Lazy
    private IAccWalletInfoService accWalletInfoService;
    @RequestMapping("getnotify")
    public void getNotify(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        Iterator<String> iter = requestParams.keySet().iterator();
        while(iter.hasNext()) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean singVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        if (singVerified) {
            //商户订单号
            String order_no = request.getParameter("out_trade_no");
            //金额
            String total_amount = request.getParameter("total_amount");
            BigDecimal totalAmount = new BigDecimal(total_amount);
            //支付宝交易号
            String third_trade_no = request.getParameter("trade_no");
            //交易状态
            String trade_status = request.getParameter("trade_status");
            AccTrade accTradeInDB = accTradeService.selectAccTradeByOrderNo(Long.valueOf(order_no)).get(0);
            if (AliPayTradeStatusEnum.TRADE_STATUS_FINISHED.getKey().equals(trade_status)) {
                //判断该笔订单是否已经做过处理
                //如果没做过处理，根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详情，判断金额是否等于 total_amount，并执行商户的业务程序
                //如果做过处理，不执行商户的业务程序
                //注意： 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态 TRADE_FINISHED
                AccTradeVo updateTrade = new AccTradeVo();
                updateTrade.setOrderNo(Long.valueOf(order_no));
                updateTrade.setThirdTradeNo(third_trade_no);
                updateTrade.setPayState(PayStateEnum.PAY_SUCC.getKey());
                updateTrade.setTradeState(AccTradeStateEnum.TAKE_EFFECT.getKey().longValue());
                updateTrade.setFailReason(trade_status);
                if (PayStateEnum.PAY_INPROCESS.getKey().equals(accTradeInDB.getPayState())) {
                    WalletUpdateDTO walletUpdateDTO = new WalletUpdateDTO();
                    walletUpdateDTO.setAmount(totalAmount);
                    walletUpdateDTO.setUserId(SecurityUtils.getUserId());
                    walletUpdateDTO.setAccWalletIdEnum(AccWalletIdEnum.WALLET);
                    walletUpdateDTO.setAccTradeTypeEnum(AccTradeTypeEnum.RECHARGE);
                    walletUpdateDTO.setPayChannelEnum(PayChannelEnum.ALI);
                    walletUpdateDTO.setPayTypeEnum(PayTypeEnum.ALI_H5_PAY);
                    accWalletInfoService.addAccWalletBalance(walletUpdateDTO);
                }
                this.accTradeService.updateAccTradeVoByOrderNo(updateTrade);
            } else if (AliPayTradeStatusEnum.TRADE_STATUS_SUCCESS.getKey().equals(trade_status)) {
                //判断该笔订单是否已经做过处理
                //如果没做过处理，根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详情，判断金额是否等于 total_amount，并执行商户的业务程序
                //如果做过处理，不执行商户的业务程序
                //注意： 付款完成后，支付宝系统发送该交易状态 TRADE_SUCCESS
                AccTradeVo updateTrade = new AccTradeVo();
                updateTrade.setOrderNo(Long.valueOf(order_no));
                updateTrade.setThirdTradeNo(third_trade_no);
                updateTrade.setPayState(PayStateEnum.PAY_SUCC.getKey());
                updateTrade.setTradeState(AccTradeStateEnum.TAKE_EFFECT.getKey().longValue());
                updateTrade.setFailReason(trade_status);
                if (PayStateEnum.PAY_INPROCESS.getKey().equals(accTradeInDB.getPayState())) {
                    WalletUpdateDTO walletUpdateDTO = new WalletUpdateDTO();
                    walletUpdateDTO.setAmount(totalAmount);
                    walletUpdateDTO.setUserId(SecurityUtils.getUserId());
                    walletUpdateDTO.setAccWalletIdEnum(AccWalletIdEnum.WALLET);
                    walletUpdateDTO.setAccTradeTypeEnum(AccTradeTypeEnum.RECHARGE);
                    walletUpdateDTO.setPayChannelEnum(PayChannelEnum.ALI);
                    walletUpdateDTO.setPayTypeEnum(PayTypeEnum.ALI_H5_PAY);
                    accWalletInfoService.addAccWalletBalance(walletUpdateDTO);
                }
                this.accTradeService.updateAccTradeVoByOrderNo(updateTrade);
            } else {
                AccTradeVo updateTrade = new AccTradeVo();
                updateTrade.setOrderNo(Long.valueOf(order_no));
                updateTrade.setThirdTradeNo(third_trade_no);
                updateTrade.setPayState(PayStateEnum.PAY_FAIL.getKey());
                updateTrade.setTradeState(AccTradeStateEnum.CLOSE.getKey().longValue());
                updateTrade.setFailReason(trade_status);
                this.accTradeService.updateAccTradeVoByOrderNo(updateTrade);
            }
            out.println("success");
        } else {
            out.println("fail");
            //调试用，写文本函数记录程序运行情况是否正常
            //String reason = AlipaySignature.getSignCheckContentV1(params);
            //log.info(reason);
        }
        response.getWriter().flush();
    }
}
