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

import com.alibaba.excel.util.StringUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
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.pay.constants.PayTypeEnum;
import com.bonus.canteen.core.pay.util.AlipayConfig;
import com.bonus.canteen.core.account.domain.vo.AccTradeVo;
import com.bonus.common.houqin.constant.GlobalConstants;
import com.bonus.common.houqin.utils.id.Id;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Api(tags = "支付接口")
@RestController
@RequestMapping("/alipay")
public class PayController {
    @Resource
    AlipayClient alipayClient;
    @Resource
    AlipayTradePagePayRequest alipayRequest;
    @Autowired
    IAccTradeService accTradeService;
    @Autowired
    AccSubService accSubService;
    @Autowired
    @Lazy
    private IAccWalletInfoService accWalletInfoService;
    @PostMapping("pay")
    public void pay(@RequestBody AccTradeVo accTradeVo, HttpServletResponse response) throws AlipayApiException, IOException {
        // 预装数据，存档
        accTradeVo.setUserId(SecurityUtils.getUserId());
        accTradeVo.setDeptId(SecurityUtils.getLoginUser().getSysUser().getDeptId());
        accTradeVo.setTradeType(AccTradeTypeEnum.CONSUME.getKey().longValue());
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        accTradeVo.setOrderNo(Id.next());
        accTradeVo.setOrderName(accTradeVo.getOrderNo() + "_" + GlobalConstants.PERSONAL_RECHARGE);
        accTradeVo.setTradeTime(new Date());
        accTradeVo.setAmount(accTradeVo.getPaymentAmount().multiply(new BigDecimal(100)).longValue());
        accTradeVo.setPayType(PayTypeEnum.MEAL_CARD.getKey().longValue());
        accTradeVo.setPayState(PayStateEnum.PAY_INPROCESS.getKey());
        accTradeVo.setTradeState(AccTradeStateEnum.CREATE.getKey().longValue());
        accTradeService.insertAccTradeVo(accTradeVo);
        // 调用alipay
        alipayRequest.setBizContent(
                "{\"out_trade_no\":\""+ accTradeVo.getOrderNo() +"\","
                + "\"total_amount\":\""+ accTradeVo.getPaymentAmount().toString() +"\","
                + "\"subject\":\""+ accTradeVo.getOrderName() +"\","
                + "\"body\":\""+ accTradeVo.getProductDesc() +"\","
                + "\"timeout_express\":\"10m\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        AlipayTradePagePayResponse alipayResponse = alipayClient.pageExecute(alipayRequest);
        log.info("alipay body = " + alipayResponse.getBody());
        log.info("alipay msg = " + alipayResponse.getMsg());
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(alipayResponse.getBody());
        response.getWriter().flush();
    }

    /**
     * 查询支付宝订单状态
     * @param accTradeVo 商户订单号
     * @return 订单查询结果
     */
    @PostMapping("queryOrder")
    public AlipayTradeQueryResponse queryOrder(@RequestBody AccTradeVo accTradeVo) {
        // 创建查询请求
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        // 设置业务参数
        String bizContent = String.format("{\"out_trade_no\":\"%s\"}", accTradeVo.getOrderNo());
        request.setBizContent(bizContent);

        try {
            // 发送查询请求
            AlipayTradeQueryResponse response = alipayClient.execute(request);
            // 根据结果处理充值记录，成功的话，存入钱包
            String trade_status = response.getTradeStatus();
            String third_trade_no = response.getTradeNo();
            if (AliPayTradeStatusEnum.TRADE_STATUS_FINISHED.getKey().equals(trade_status) ||
                    AliPayTradeStatusEnum.TRADE_STATUS_SUCCESS.getKey().equals(trade_status)) {
                AccTradeVo updateTrade = new AccTradeVo();
                updateTrade.setOrderNo(accTradeVo.getOrderNo());
                updateTrade.setThirdTradeNo(third_trade_no);
                updateTrade.setPayState(PayStateEnum.PAY_SUCC.getKey());
                updateTrade.setTradeState(AccTradeStateEnum.TAKE_EFFECT.getKey().longValue());
                updateTrade.setFailReason(trade_status);
                AccTrade accTradeInDB = accTradeService.selectAccTradeByOrderNo(accTradeVo.getOrderNo()).get(0);
                if (PayStateEnum.PAY_INPROCESS.getKey().equals(accTradeInDB.getPayState())) {
                    BigDecimal totalAmount = new BigDecimal(response.getTotalAmount());
                    WalletUpdateDTO walletUpdateDTO = new WalletUpdateDTO();
                    walletUpdateDTO.setAmount(totalAmount);
                    walletUpdateDTO.setUserId(accTradeVo.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);
            }
            return response;
        } catch (AlipayApiException e) {
            log.error("查询异常, ", e.getErrMsg());
            return null;
        }
    }

}
