package com.miaxis.wx.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.miaxis.common.config.WxPayConfigImpl;
import com.miaxis.common.config.WxpayConfig;
import com.miaxis.common.core.domain.entity.UserInfo;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.RSAUtils;
import com.miaxis.common.utils.SecurityUtils;
import com.miaxis.common.utils.XmlUtil;
import com.miaxis.system.service.ISysConfigService;
import com.miaxis.user.service.IUserInfoService;
import com.miaxis.wx.domain.WxExtract;
import com.miaxis.wx.domain.WxOrder;
import com.miaxis.wx.dto.QuerySchoolOrderListDTO;
import com.miaxis.wx.dto.WxExtractBankDTO;
import com.miaxis.wx.mapper.WxOrderMapper;
import com.miaxis.wx.service.IWxExtractService;
import com.miaxis.wx.service.IWxOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.PublicKey;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import static com.miaxis.common.utils.OrderCodeFactory.getOrderCode;

/**
 * 电影订单Service业务层处理
 *
 * @author miaxis
 * @date 2021-05-07
 */
@Service
@Slf4j
public class WxOrderServiceImpl extends ServiceImpl<WxOrderMapper, WxOrder> implements IWxOrderService {
    @Resource
    private WxOrderMapper wxOrderMapper;



    @Autowired
    private IWxExtractService wxExtractService;

    @Autowired
    private ISysConfigService configService;


    @Autowired
    private IUserInfoService userInfoService;


    @Autowired
    private WxpayConfig wxpayConfig;


    @Autowired
    private RSAUtils rsaUtils;

    @Value("${app.appid}")
    private String appid;




    @Override
    public void createVipOrder(WxOrder wxOrder) {
        String price = configService.selectConfigByKey("vip_price");
        Double dprice = Double.valueOf(price);
        Double v =dprice* 100;
        wxOrder.setTotal(v.intValue());


    }
    @Override
    public WxOrder getByOutTradeNo(String outTradeNo) {
        return wxOrderMapper.getByOutTradeNo(outTradeNo);
    }

    @Override
    public List<WxOrder> QuerySchoolOrderList(QuerySchoolOrderListDTO dto) {
        return wxOrderMapper.QuerySchoolOrderList(dto);
    }

    @Override
    @Transactional
    public String wxwithdrawal(Integer amount) throws Exception {
        UserInfo student = SecurityUtils.getLoginUser().getStudent();
        UserInfo dbUserInfo = userInfoService.getById(student.getId());
        if (dbUserInfo.getProfitPrice() < amount){
            throw new CustomException("提现金额不能大于可提现金额");
        }

        Map<String, String> sortMap = new TreeMap<String, String>();
        sortMap.put("mch_appid",appid);
        sortMap.put("mchid",wxpayConfig.getMerchantId());
        sortMap.put("nonce_str", RandomStringUtils.randomAlphanumeric(32));
        sortMap.put("partner_trade_no",getOrderCode(null));
        sortMap.put("openid",student.getOpenid());
        sortMap.put("check_name","NO_CHECK");
        sortMap.put("amount",String.valueOf(amount));
        sortMap.put("desc","用户提现");

        WXPayConfig config = new WxPayConfigImpl();
        String sign = WXPayUtil.generateSignature(sortMap, config.getKey(), WXPayConstants.SignType.MD5);
        sortMap.put("sign", sign);
        WXPay pay = new WXPay(config);

        String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
        Map<String, String> resMap;
        String xmlStr = pay.requestWithCert(url, sortMap, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs());
        resMap = XmlUtil.xmlToMap(xmlStr);
        if (!"SUCCESS".equals(resMap.get("return_code"))||!"SUCCESS".equals(resMap.get("result_code"))){
            throw new CustomException(resMap.get("return_msg"));
        }
        //新增提现记录
        WxExtract wxExtract = new WxExtract();
        wxExtract.setOpenid(student.getOpenid());
        wxExtract.setExtractPrice(amount);
        wxExtract.setPartnerTradeNo(resMap.get("partner_trade_no"));
        wxExtract.setStatus("1");
        wxExtractService.save(wxExtract);

        //更新余额
        dbUserInfo.setProfitPrice(dbUserInfo.getProfitPrice()-amount);
        userInfoService.updateById(dbUserInfo);

        return resMap.get("return_msg");
    }

    @Override
    public String wxwithbankdrawal(WxExtractBankDTO dto) throws Exception {
        UserInfo student = SecurityUtils.getLoginUser().getStudent();
        UserInfo dbUserInfo = userInfoService.getById(student.getId());
        if (dbUserInfo.getProfitPrice() < dto.getAmount()){
            throw new CustomException("提现金额不能大于可提现金额");
        }

        Map<String, String> sortMap = new TreeMap<String, String>();
        sortMap.put("mch_id",wxpayConfig.getMerchantId());
        sortMap.put("nonce_str", RandomStringUtils.randomAlphanumeric(32));
        sortMap.put("partner_trade_no",getOrderCode(null));
        sortMap.put("amount",String.valueOf(dto.getAmount()));
        sortMap.put("desc","用户银行卡提现");


//        X509Certificate validCertificate = verifier.getValidCertificate();
        String rsa ="RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING";
        //PublicKey publicKey = getPublicKey();

        // 进行签名服务

        sortMap.put("enc_true_name",rsaUtils.encryptData(dto.getEncTrueName()) );
        sortMap.put("enc_bank_no",rsaUtils.encryptData(dto.getEncBankNo()));
        sortMap.put("bank_code",dto.getBankCode());


        WXPayConfig config = new WxPayConfigImpl();
        String sign = WXPayUtil.generateSignature(sortMap, config.getKey(), WXPayConstants.SignType.MD5);
        sortMap.put("sign", sign);
        WXPay pay = new WXPay(config);

        String url = "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
        Map<String, String> resMap;
        String xmlStr = pay.requestWithCert(url, sortMap, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs());
        resMap = XmlUtil.xmlToMap(xmlStr);
        if (!"SUCCESS".equals(resMap.get("return_code"))||!"SUCCESS".equals(resMap.get("result_code"))){
            throw new CustomException(resMap.get("return_msg"));
        }
        //新增提现记录
        WxExtract wxExtract = new WxExtract();
        wxExtract.setOpenid(student.getOpenid());
        wxExtract.setExtractPrice(dto.getAmount());
        wxExtract.setPartnerTradeNo(resMap.get("partner_trade_no"));
        wxExtract.setStatus("1");
        wxExtractService.save(wxExtract);

        //更新余额
        dbUserInfo.setProfitPrice(dbUserInfo.getProfitPrice()-dto.getAmount());
        userInfoService.updateById(dbUserInfo);

        return resMap.get("return_msg");
    }

    private PublicKey getPublicKey() throws Exception {
        Map<String, String> sortMap = new TreeMap<String, String>();
        sortMap.put("mch_id",wxpayConfig.getMerchantId());
        sortMap.put("nonce_str", RandomStringUtils.randomAlphanumeric(32));
        sortMap.put("sign_type","MD5");


        WXPayConfig config = new WxPayConfigImpl();
        String sign = WXPayUtil.generateSignature(sortMap, config.getKey(), WXPayConstants.SignType.MD5);
        sortMap.put("sign", sign);
        WXPay pay = new WXPay(config);

        String url = "https://fraud.mch.weixin.qq.com/risk/getpublickey";
        Map<String, String> resMap;
        String xmlStr = pay.requestWithCert(url, sortMap, config.getHttpConnectTimeoutMs(), config.getHttpReadTimeoutMs());
        resMap = XmlUtil.xmlToMap(xmlStr);
        return  null;

    }
}
