package com.younike.merchant;


import com.younike.common.core.domain.AjaxResult;
import com.younike.common.exception.ServiceException;
import com.younike.common.utils.SecurityUtils;
import com.younike.system.domain.BondPayment;
import com.younike.system.domain.Merchant;
import com.younike.system.domain.vo.WechatPay;
import com.younike.system.service.IBondPaymentService;
import com.younike.system.service.IMerchantService;
import com.younike.system.service.ISysConfigService;
import com.younike.wxpay.params.Amount;
import com.younike.wxpay.params.TransactionParams;
import com.younike.wxpay.service.IBasePayService;
import com.younike.wxpay.service.IMerchantPayService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

import static com.younike.wxpay.enums.TransactionType.NATIVE;

/**
 * @Description:
 * @Author: maol
 * @Date: 2018/12/26 13:28
 */
@RestController
@Scope("prototype")
@RequestMapping(value = "/wxAppPay")
public class WeChatAppPayController {

    @Resource
    private IMerchantService merchantService;
    @Resource
    private IBondPaymentService bondPaymentService;
    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private IMerchantPayService merchantPayService;

    @Value("${domain}")
    private String domain;

    /**
     * @Description: 普通商户模式：微信统一下单接口
     * @param: [request, response, payInfo]
     * @return: com.gd.activiti.frame.pojo.APIResult
     * @Author: maol
     * @Date: 2019/2/2 13:29
     */
    @PreAuthorize("@ss.hasRole('merchant')")
    @PostMapping("orderPayment")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult payment(@RequestBody WechatPay payInfo) {
        Merchant merchant = merchantService.selectMerchantByAdminId(SecurityUtils.getUserId());
        if (Objects.isNull(merchant)){
            throw new ServiceException("非平台入驻商户，无法充值");
        }
        BigDecimal payMoney = BigDecimal.valueOf(Double.parseDouble(payInfo.getTotal_fee()));

        String min = sysConfigService.selectConfigByKey("bond.pay.min");
        BigDecimal payMin = StringUtils.isNotBlank(min)? new BigDecimal(min): BigDecimal.valueOf(100L);
        if (payMoney.compareTo(payMin) < 0){
            throw new ServiceException("充值金额不能低于" + min + "元");
        }

        String paymentId = UUID.randomUUID().toString().replace("-", "");
        String code = merchantPayService.transaction(NATIVE,
                TransactionParams.builder()
                        .description("保证金充值")
                        .out_trade_no(paymentId)
                        .notify_url(domain + "member/order/bond/cb")
                        .amount(Amount.pay(payMoney.multiply(BigDecimal.valueOf(100l)).intValue()))
                        .build()).getCode_url();

        BondPayment bondPayment = new BondPayment();
        bondPayment.setPaymentId(paymentId);
        bondPayment.setMerchantId(merchant.getMerchantId());
        bondPayment.setOrderNo(paymentId);
        bondPayment.setPayType("002");
        bondPayment.setBondMoney(payMoney);
        bondPayment.setCreateTime(LocalDateTime.now());
        bondPayment.setCreateBy(SecurityUtils.getUserId().toString());
        bondPaymentService.insertBondPayment(bondPayment);

        AjaxResult result = AjaxResult.success();
        result.put("code_url", code);
        return result;
    }

}
