package com.fs.pay.controller;


import com.fs.common.core.domain.R;
import com.fs.common.utils.StringUtils;

import com.fs.company.domain.CompanyRecharge;
import com.fs.company.service.ICompanyRechargeService;
import com.fs.pay.bean.WxPayBean;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.enums.TradeType;
import com.ijpay.core.kit.HttpKit;
import com.ijpay.core.kit.IpKit;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.WxPayApiConfig;
import com.ijpay.wxpay.WxPayApiConfigKit;
import com.ijpay.wxpay.model.UnifiedOrderModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/pay/wxPay")
public class WxPayController extends WxPayApiController {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WxPayBean wxPayBean;

    private String notifyUrl;
    private String refundNotifyUrl;

    @Autowired
    ICompanyRechargeService rechargeService;



    @Override
    public WxPayApiConfig getApiConfig() {
        WxPayApiConfig apiConfig;

        try {
            apiConfig = WxPayApiConfigKit.getApiConfig(wxPayBean.getAppId());
        } catch (Exception e) {
            apiConfig = WxPayApiConfig.builder()
                    .appId(wxPayBean.getAppId())
                    .mchId(wxPayBean.getMchId())
                    .partnerKey(wxPayBean.getPartnerKey())
                    .certPath(wxPayBean.getCertPath())
                    .domain(wxPayBean.getDomain())
                    .build();
        }
        notifyUrl = apiConfig.getDomain().concat("/pay/wxPay/payNotify");
        refundNotifyUrl = apiConfig.getDomain().concat("/pay/wxPay/refundNotify");
        return apiConfig;
    }
    @GetMapping("/test")
    @ResponseBody
    public WxPayBean test() {
        return wxPayBean;
    }

    @GetMapping(value="/qrPay")
    @ResponseBody
    public R qrPay(
            @ApiParam(required = true, name = "orderNo", value = "订单ID") @RequestParam(value = "orderNo", required = false) String orderNo,
            @ApiParam(required = true, name = "orderType", value = "订单类型 1 充值") @RequestParam(value = "orderType", required = false) Integer orderType,
            HttpServletRequest request){
        if(orderType.equals(1)){
            CompanyRecharge recharge=rechargeService.selectCompanyRechargeByNo(orderNo);
            if(recharge==null){
                return R.error("充值订单不存在");
            }
            if(recharge.getStatus()!=0){
                return R.error("此订单已支付");
            }
            Integer money= recharge.getMoney().multiply(new BigDecimal(100)).intValue();
            String ip = IpKit.getRealIp(request);
            if (StringUtils.isEmpty(ip)) {
                ip = "127.0.0.1";
            }
            WxPayApiConfig wxPayApiConfig = WxPayApiConfigKit.getWxPayApiConfig();
            Map<String, String> params = UnifiedOrderModel
                    .builder()
                    .appid(wxPayApiConfig.getAppId())
                    .mch_id(wxPayApiConfig.getMchId())
                    .nonce_str(WxPayKit.generateStr())
                    .body("充值订单")
                    .out_trade_no("recharge-"+recharge.getRechargeNo())
                    .total_fee(money.toString())
                    .spbill_create_ip(ip)
                    .notify_url(notifyUrl)
                    .trade_type(TradeType.NATIVE.getTradeType())
                    .build()
                    .createSign(wxPayApiConfig.getPartnerKey(), SignType.HMACSHA256);

            String xmlResult = WxPayApi.pushOrder(false, params);
            log.info("统一下单:" + xmlResult);

            Map<String, String> result = WxPayKit.xmlToMap(xmlResult);

            String returnCode = result.get("return_code");
            String returnMsg = result.get("return_msg");
            System.out.println(returnMsg);
            if (!WxPayKit.codeIsOk(returnCode)) {
                return R.error("error:" + returnMsg);
            }
            String resultCode = result.get("result_code");
            if (!WxPayKit.codeIsOk(resultCode)) {
                return R.error("error:" + returnMsg);
            }
            //生成预付订单success
            //生成预付订单success
            String qrCodeUrl = result.get("code_url");
//            String name = order.getOrderNo()+".png";
//            String filePath = FSConfig.getUploadPath();
//            boolean encode = QrCodeKit.encode(qrCodeUrl, BarcodeFormat.QR_CODE, 3, ErrorCorrectionLevel.H, "png", 200, 200,
//                    filePath +"/"+ File.separator + name);
//            if (encode) {
//                //在页面上显示
//                order.setPayType(1);
//                goodsOrderService.updateFsGoodsOrder(order);
//                return R.ok().put("name",name);
//            }
            recharge.setPayType(1);
            rechargeService.updateCompanyRecharge(recharge);
            return R.ok().put("qr",qrCodeUrl);

        }
        return R.error("订单类型不正确");
    }

    @RequestMapping(value = "/payNotify",method={RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String payNotify(HttpServletRequest request) {
        // 支付结果通用通知文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
        String xmlMsg = HttpKit.readData(request);
        System.out.println("支付通知="+xmlMsg);
        Map<String, String> params = WxPayKit.xmlToMap(xmlMsg);
        String returnCode = params.get("return_code");
        // 微信支付订单号
        String transaction_id      = params.get("transaction_id");
        // 商户订单号
        String out_trade_no      = params.get("out_trade_no");
        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 注意此处签名方式需与统一下单的签名类型一致
        if (WxPayKit.verifyNotify(params, WxPayApiConfigKit.getWxPayApiConfig().getPartnerKey(), SignType.HMACSHA256)) {
            if (WxPayKit.codeIsOk(returnCode)) {
                // 更新订单信息
                // 发送通知等
                String[] order=out_trade_no.split("-");
                R r;
                switch (order[0]){
                    case "recharge":
                        CompanyRecharge recharge=rechargeService.selectCompanyRechargeByNo(order[1]);

                        if(recharge!=null&&recharge.getStatus()==1){
                            Map<String, String> xml = new HashMap<String, String>(2);
                            xml.put("return_code", "SUCCESS");
                            xml.put("return_msg", "OK");
                            return WxPayKit.toXml(xml);
                        }
                        recharge.setTradeNo(transaction_id);
                        r= rechargeService.payNotify(recharge);
                        if(r.get("code").equals(200)){
                            Map<String, String> xml = new HashMap<String, String>(2);
                            xml.put("return_code", "SUCCESS");
                            xml.put("return_msg", "OK");
                            return WxPayKit.toXml(xml);

                        }
                        else {
                            return null;
                        }

                }
            }
        }
        return null;

    }






}
