package com.bohuikeji.frame.module.admin.utils.ali;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayMarketingActivityOrdervoucherCreateRequest;
import com.alipay.api.response.AlipayMarketingActivityOrdervoucherCreateResponse;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * 支付宝商家卷
 */
public class businessVolumeUtils {

    /**
     * 支付宝小程序公钥证书加签方式
     */
    public static class aliClient {
        public static AlipayClient alipayBycodeClient;
        static {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
            certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
            certAlipayRequest.setAppId(AliConfig.AliClientID);
            certAlipayRequest.setPrivateKey(AliConfig.APP_PRIVATE_KEY);
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset("GBK");
            certAlipayRequest.setSignType("RSA2");
            certAlipayRequest.setCertPath(AliConfig.appclientCertPath);
            certAlipayRequest.setAlipayPublicCertPath(AliConfig.alipayclientCertPath);
            certAlipayRequest.setRootCertPath(AliConfig.alipayclientRootCertPath);
            try {
                alipayBycodeClient = new DefaultAlipayClient(certAlipayRequest);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     * @param couponName 活动名称
     * @param couponType 券类型
     * @param satrtTime 券发放开始时间
     * @param endTime 券发放结束时间
     * @param amount 优惠金额（满减、特价、兑换）
     * @param floorAmount 门槛金额（满减、折扣、特价、兑换）
     * @param discount 折扣率（折扣卷）
     * @param originAmount 原价（特价卷）
     * @param saleAmount 购买金额（兑换卷）
     * @return
     * @throws AlipayApiException
     * @throws ParseException
     */
    public static JSONObject getObject(String couponName,String couponType, String satrtTime,String endTime,String amount,String floorAmount,String discount,String originAmount,String saleAmount) throws AlipayApiException, ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        AlipayMarketingActivityOrdervoucherCreateRequest request = new AlipayMarketingActivityOrdervoucherCreateRequest();
        AlipayMarketingActivityOrdervoucherCreateModel model = new AlipayMarketingActivityOrdervoucherCreateModel();
        model.setVoucherType(businessVolumeUtils.geType(couponType));
        model.setCodeMode("MERCHANT_UPLOAD");
        model.setActivityName(couponName);
        model.setPublishStartTime(sdf.parse(satrtTime));
        model.setPublishEndTime(sdf.parse(endTime));
        model.setOutBizNo("20170101000001654bb46ba");
        model.setBelongMerchantInfo(businessVolumeUtils.getBelongMerchantInfo());//商家券活动归属的商户信息
        model.setVoucherDisplayInfo(businessVolumeUtils.getVoucherDisplayInfo()); //券展示信息
        model.setVoucherUseRule(businessVolumeUtils.getVoucherUseRule(couponType,amount,floorAmount,discount,originAmount,saleAmount));//商家券可用范围
        model.setVoucherSendRule(businessVolumeUtils.getVoucherSendRuleDetail()); //券发放规则
        model.setCustomerGuide(businessVolumeUtils.getCustomerGuide());//自定义入口
        request.setBizModel(model);
        AlipayMarketingActivityOrdervoucherCreateResponse response = aliClient.alipayBycodeClient.certificateExecute(request);
        JSONObject orderStr  = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_trade_create_response");
        System.out.println(orderStr);
        /*if (!response.isSuccess()) {
            System.out.println("调用成功");
            return orderStr;
        } else {
            System.out.println("调用失败");
        }*/
        return orderStr;
    }

    /**
     * 自定义入口
     * @return
     */
    public static CustomerGuide getCustomerGuide(){
        CustomerGuide customerGuide = new CustomerGuide();
        VoucherUseGuide voucherUseGuide = new VoucherUseGuide();
        voucherUseGuide.setMiniAppId(AliConfig.AliClientID);
        voucherUseGuide.setOfflineCodeUseGuide(true);
        /*List<String> serviceCodes = new ArrayList<String>();
        serviceCodes.add("2020030921000303380758");
        voucherUseGuide.setServiceCodes(serviceCodes);*/
        voucherUseGuide.setMiniAppUseGuide(true);
        voucherUseGuide.setMiniAppPath("/index/path/path&query=xx=xx");
        customerGuide.setVoucherUseGuide(voucherUseGuide);
        VoucherSendGuide voucherSendGuide = new VoucherSendGuide();
        //voucherSendGuide.setVoucherDetailUrl("alipays://platformapi/startapp?appId=xxxx");
        customerGuide.setVoucherSendGuide(voucherSendGuide);
        return customerGuide;
    }

    /**
     * 券展示信息
     * @return
     */
    public static VoucherDisplayInfo getVoucherDisplayInfo(){
        VoucherDisplayInfo voucherDisplayInfo = new VoucherDisplayInfo();
        //voucherDisplayInfo.setBrandLogo("adeDSktiQO-u5vJUqVbcQwAAACMAAQED");
        //voucherDisplayInfo.setVoucherImage("adeDSktiQO-u5vJUqVbcQwAAACMAAQED");
        //voucherDisplayInfo.setCustomerServiceMobile("81XXXXXXX");
        //voucherDisplayInfo.setCustomerServiceUrl("alipay://xxxx");
        voucherDisplayInfo.setVoucherComment("同城急送，品质之选");
       /* List<String> voucherDetailImages = new ArrayList<String>();
        voucherDetailImages.add("adeDSktiQO-u5vJUqVbcQwAAACMAAQE1");
        voucherDetailImages.add("adeDSktiQO-u5vJUqVbcQwAAACMAAQE2");
        voucherDetailImages.add("adeDSktiQO-u5vJUqVbcQwAAACMAAQE3");*/
        //voucherDisplayInfo.setVoucherDetailImages(voucherDetailImages);
        voucherDisplayInfo.setVoucherDescription("1、本券不可兑换现金，不可找零。2、每个用户最多可以领取1张。3、如果订单发生退款，优惠券无法退还。");
        voucherDisplayInfo.setBrandName("同城急送");
        return voucherDisplayInfo;
    }

    /**
     * 商家券活动归属的商户信息
     * @return
     */
    public static BelongMerchantInfo getBelongMerchantInfo(){
        BelongMerchantInfo belongMerchantInfo = new BelongMerchantInfo();
        belongMerchantInfo.setMerchantIdType("SMID");
        belongMerchantInfo.setMerchantId("2088102111111111");
        belongMerchantInfo.setBusinessType("ISV_FOR_MERCHANT");
        return belongMerchantInfo;
    }

    /**
     * 券发放规则
     * @return
     */
    public static VoucherSendRuleDetail getVoucherSendRuleDetail(){
        VoucherSendRuleDetail voucherSendRule = new VoucherSendRuleDetail();
        voucherSendRule.setVoucherQuantityLimitPerUser(1L);
        voucherSendRule.setPhoneNumberLimit(false);
        voucherSendRule.setNaturalPersonLimit(true);
        voucherSendRule.setVoucherQuantity(0L);
        return voucherSendRule;
    }


    /**
     * 商家券可用范围
     * @param couponType 券类型
     * @param amount 优惠金额（满减、特价、兑换）
     * @param floorAmount 门槛金额（满减、折扣、特价、兑换）
     * @param discount 折扣率（折扣卷）
     * @param originAmount 原价（特价卷）
     * @param saleAmount 购买金额（兑换卷）
     * @return
     * @throws ParseException
     */
    public static VoucherUseRule getVoucherUseRule(String couponType, String amount,String floorAmount,String discount,String originAmount,String saleAmount) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        VoucherUseRule voucherUseRule = new VoucherUseRule();
        VoucherAvailableScope voucherAvailableScope = new VoucherAvailableScope();
        /*OrderVoucherAvailableShop orderVoucherAvailableShop = new OrderVoucherAvailableShop();
        List<String> realShopIds = new ArrayList<String>();
        realShopIds.add("2018051000502000000011111111");
        realShopIds.add("2018040200502000000011111111");
        realShopIds.add("2018062800502000000022271997");
        orderVoucherAvailableShop.setRealShopIds(realShopIds);
        List<String> shopIds = new ArrayList<String>();
        shopIds.add("2018051000502000000011111111");
        shopIds.add("2018040200502000000011111111");
        shopIds.add("2018062800502000000022271997");
        orderVoucherAvailableShop.setShopIds(shopIds);*/
        //voucherAvailableScope.setOrderVoucherAvailableShop(orderVoucherAvailableShop);
        voucherAvailableScope.setVoucherAvailableType("CITY_CODE");
        OrderVoucherAvailableCityCode orderVoucherAvailableCityCode = new OrderVoucherAvailableCityCode();
        orderVoucherAvailableCityCode.setAllCity(true);
        /*List<String> cityCodes = new ArrayList<String>();
        cityCodes.add("100100");
        orderVoucherAvailableCityCode.setCityCodes(cityCodes);*/
        voucherAvailableScope.setOrderVoucherAvailableCityCode(orderVoucherAvailableCityCode);
        voucherUseRule.setVoucherAvailableScope(voucherAvailableScope);
        switch (couponType){
            case "满减券":
                voucherUseRule.setFixVoucher(businessVolumeUtils.getFixVoucher(amount,floorAmount));break;
            case "折扣券":
                voucherUseRule.setDiscountVoucher(businessVolumeUtils.getDiscountVoucher(amount,floorAmount,discount));break;
            case "特价券":
                voucherUseRule.setSpecialVoucher(businessVolumeUtils.getSpecialVoucher(amount,floorAmount,originAmount));break;
            case "兑换券":
                voucherUseRule.setExchangeVoucher(businessVolumeUtils.getExchangeVoucher(amount,floorAmount,saleAmount));break;
            default:
                return null;
        }
        VoucherValidPeriod voucherValidPeriod = new VoucherValidPeriod();
        voucherValidPeriod.setType("ABSOLUTE");
        voucherValidPeriod.setValidDaysAfterReceive(3L);
        voucherValidPeriod.setValidEndTime(sdf.parse("2017-01-13 23:59:59"));
        voucherValidPeriod.setValidBeginTime(sdf.parse("2017-01-10 00:00:00"));
        voucherValidPeriod.setWaitDaysAfterReceive(2L);
        voucherUseRule.setVoucherValidPeriod(voucherValidPeriod);
        return voucherUseRule;
    }

    /**
     * 满减券详情
     * @param amount 满减金额
     * @param floorAmount 门槛金额
     * @return
     */
    public static FixVoucher getFixVoucher(String amount,String floorAmount){
        FixVoucher fixVoucher = new FixVoucher();
        fixVoucher.setFloorAmount(floorAmount);
        fixVoucher.setAmount(amount);
        fixVoucher.setGoodsName("同城急送");
        return fixVoucher;
    }

    /**
     * 折扣券详情
     * @param amount 满减金额
     * @param floorAmount 门槛金额
     * @param discount 折扣率
     * @return
     */
    public static DiscountVoucher getDiscountVoucher(String amount,String floorAmount,String discount){
        DiscountVoucher discountVoucher = new DiscountVoucher();
        discountVoucher.setFloorAmount(floorAmount);
        discountVoucher.setCeilingAmount("50.00");
        /*discountVoucher.setOriginAmount("65.00");
        discountVoucher.setGoodsName("同城急送");*/
        discountVoucher.setDiscount(discount);
        return discountVoucher;
    }

    /**
     * 特价券详情
     * @param amount 特价金额
     * @param floorAmount 门槛金额
     * @param originAmount 原价
     * @return
     */
    public static SpecialVoucher getSpecialVoucher(String amount,String floorAmount,String originAmount){
        SpecialVoucher specialVoucher = new SpecialVoucher();
        specialVoucher.setFloorAmount(floorAmount);
        specialVoucher.setSpecialAmount(amount);
        specialVoucher.setOriginAmount(originAmount);
        specialVoucher.setGoodsName("同城急送");
        return specialVoucher;
    }

    /**
     * 兑换券详情
     * @param amount 券的价值
     * @param floorAmount 门槛金额
     * @param saleAmount 用户购买优惠券需要支付的金额
     * @return
     */
    public static ExchangeVoucher getExchangeVoucher(String amount,String floorAmount,String saleAmount){
        ExchangeVoucher exchangeVoucher = new ExchangeVoucher();
        exchangeVoucher.setBizType("FIX_EXCHANGE_VOUCHER");
        exchangeVoucher.setFloorAmount(floorAmount);
        exchangeVoucher.setSaleAmount(saleAmount);
        //exchangeVoucher.setCustomerServiceMobile("81XXXXXXX");
        exchangeVoucher.setAmount(amount);
        //exchangeVoucher.setCustomerServiceUrl("alipay://xxxx");
        exchangeVoucher.setOverdueRefundable(true);
        exchangeVoucher.setRefundable(false);
        //exchangeVoucher.setPayeePid("2088xxxxx");
        exchangeVoucher.setVoucherName("同城急送");
        return exchangeVoucher;
    }

    private static String geType(String couponType){
        String type;
        switch (couponType){
            case "满减券":
                type="FIX_VOUCHER";break;
            case "折扣券":
                type="DISCOUNT_VOUCHER";break;
            case "特价券":
                type="SPECIAL_VOUCHER";break;
            case "兑换券":
                type="EXCHANGE_VOUCHER";break;
            default:
                return null;
        }
        return type;
    }
}
