package cn.freemud.service.mccafe.impl;

import cn.freemud.base.constant.Version;
import cn.freemud.entities.dto.coupon.MCCafeConponRequest;
import cn.freemud.entities.dto.coupon.MCCafeCouponLockRequest;
import cn.freemud.entities.dto.coupon.MCCafeProductRedeemVo;
import cn.freemud.entities.dto.coupon.MCCafeTransactionVo;
import cn.freemud.enums.CouponReqTypeEnum;
import cn.freemud.enums.MCCafeChannelEnum;
import cn.freemud.service.mccafe.CouponClientService;
import cn.freemud.service.mccafe.thirdparty.CouponOfflineMCCafeClient;
import com.freemud.application.sdk.api.couponcenter.offline.response.CouponBaseResponse;
import com.freemud.application.sdk.api.couponcenter.offline.response.CouponQueryResponse;
import com.freemud.application.sdk.api.couponcenter.offline.response.CouponRedeemResponse;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.sdk.api.assortment.order.enums.*;
import com.freemud.sdk.api.assortment.order.request.order.CreateOrderAccountRequest;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CouponClientServiceImpl implements CouponClientService {

    @Autowired
    private CouponOfflineMCCafeClient couponOfflineMCCafeClient;

    @Override
    public CouponRedeemResponse redeem(QueryOrdersResponse.DataBean.OrderBean orderBean, List<CreateOrderAccountRequest> accounts) {
        if (null == orderBean || CollectionUtils.isEmpty(accounts)) {
            return null;
        }
        Optional<CreateOrderAccountRequest> accountRequest = accounts.stream().filter(
                account -> account.getAccountType().equals(QueryOrderAccountType.COUPON)
                ||  account.getAccountType().equals(QueryOrderAccountType.PRODUCT_COUPON)
                ||  account.getAccountType().equals(QueryOrderAccountType.DISCOUNT_COUPON)).findFirst();
        if (!accountRequest.isPresent() || accountRequest.get().getPrice() == 0) {
            return null;
        }
        CreateOrderAccountRequest accountBean = accountRequest.get();
        List<MCCafeProductRedeemVo> products = new ArrayList<>();
        //商品券核销核销参数
        if (QueryOrderAccountType.PRODUCT_COUPON.equals(accountBean.getAccountType())) {
            for (int i = 0; i < orderBean.getProductList().size(); i++) {
                QueryOrdersResponse.DataBean.OrderBean.ProductBean productBean = orderBean.getProductList().get(i);
                String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                if (!org.springframework.util.CollectionUtils.isEmpty(orderBean.getProductList().get(i).getDiscountList())) {
                    List<QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                            filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                    for (QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount productDiscount : discounts) {
                        if (productDiscount.getDiscountType() == null || productDiscount.getDiscountType() == 0) {
                            continue;
                        }
                        MCCafeProductRedeemVo mcCafeProductRedeemVo = new MCCafeProductRedeemVo();
                        mcCafeProductRedeemVo.setPid(pid);
                        mcCafeProductRedeemVo.setKeyProductCode(productBean.getCustomerCode());
                        mcCafeProductRedeemVo.setCustomer_code(productBean.getCustomerCode());
                        mcCafeProductRedeemVo.setConsume_num(productDiscount.getDiscountQty());
                        mcCafeProductRedeemVo.setSeq(i + 1);
                        products.add(mcCafeProductRedeemVo);
                    }
                }
            }
        }
        MCCafeConponRequest mcCafeConponRequest  = new MCCafeConponRequest();
        mcCafeConponRequest.setVer(Integer.valueOf(Version.VERSION_1));
        mcCafeConponRequest.setReqtype(CouponReqTypeEnum.REDEEM.getCode());
        mcCafeConponRequest.setPartnerId(Integer.parseInt(orderBean.getCompanyId()));
        mcCafeConponRequest.setStore_id(orderBean.getShopId());
        mcCafeConponRequest.setStation_id("-1");
        mcCafeConponRequest.setOperator_id("-1");
        // 订单号
        mcCafeConponRequest.setTrans_id(orderBean.getOid());
        mcCafeConponRequest.setChannel(OrderClientType.ALIPAY.getIndex().toString().equals(orderBean.getOrderClient())?MCCafeChannelEnum.MOCOFFEE_ZFB.getName():MCCafeChannelEnum.MOCOFFEE_WX.getName());
        List<MCCafeTransactionVo> transactions = new ArrayList<>();
        MCCafeTransactionVo mcCafeTransactionVo = new MCCafeTransactionVo();
        mcCafeTransactionVo.setCode(accountBean.getAccountId());
        mcCafeTransactionVo.setTotalAmount(-accountBean.getPrice());
        if (CollectionUtils.isNotEmpty(products)) {
            mcCafeTransactionVo.setProducts(products);
        }
        transactions.add(mcCafeTransactionVo);
        mcCafeConponRequest.setTransactions(transactions);
        mcCafeConponRequest.setSign("skip");

        mcCafeConponRequest.setAppFlag("kgd.N");
        mcCafeConponRequest.setBusiness_date(cn.freemud.base.util.DateUtil.convert2Str(new Date(), cn.freemud.base.util.DateUtil.FORMAT_yyyyMMdd));

        return couponOfflineMCCafeClient.redeem(mcCafeConponRequest);
    }

    @Override
    public CouponRedeemResponse redeem(MCCafeConponRequest mcCafeConponRequest) {
        return couponOfflineMCCafeClient.redeem(mcCafeConponRequest);
    }

    @Override
    public CouponRedeemResponse redeemBatch(QueryOrdersResponse.DataBean.OrderBean orderBean, List<CreateOrderAccountRequest> accounts) {
        return null;
    }

    @Override
    public CouponRedeemResponse cancelRedeem(QueryOrdersResponse.DataBean.OrderBean orderBean, List<CreateOrderAccountRequest> accounts) {
        MCCafeConponRequest mcCafeConponRequest = new MCCafeConponRequest();
        return couponOfflineMCCafeClient.cancelRedeem(mcCafeConponRequest);
    }

    @Override
    public CouponQueryResponse query(MCCafeConponRequest mcCafeConponRequest) {
        return couponOfflineMCCafeClient.query(mcCafeConponRequest);
    }

    @Override
    public CouponBaseResponse lock(QueryOrdersResponse.DataBean.OrderBean orderBean, List<CreateOrderAccountRequest> accounts) {
        if (null == orderBean || CollectionUtils.isEmpty(accounts)) {
            return null;
        }
        Optional<CreateOrderAccountRequest> accountRequest = accounts.stream().filter(
                account -> account.getAccountType().equals(QueryOrderAccountType.COUPON)
                ||  account.getAccountType().equals(QueryOrderAccountType.PRODUCT_COUPON)
                ||  account.getAccountType().equals(QueryOrderAccountType.DISCOUNT_COUPON)).findFirst();
        if (!accountRequest.isPresent() || accountRequest.get().getPrice() == 0) {
            return null;
        }
        CreateOrderAccountRequest accountBean = accountRequest.get();
        MCCafeCouponLockRequest couponCodeVerificationDto = new MCCafeCouponLockRequest();
        couponCodeVerificationDto.setVer(Integer.valueOf(Version.VERSION_1));
        couponCodeVerificationDto.setReqType(CouponReqTypeEnum.LOCK.getCode());
        couponCodeVerificationDto.setPartnerId(orderBean.getCompanyId());
        couponCodeVerificationDto.setStoreId(orderBean.getShopId());
        // 订单号
        couponCodeVerificationDto.setTransId(orderBean.getOid());
        couponCodeVerificationDto.setCoupon(accountBean.getAccountId());
        couponCodeVerificationDto.setOfferId(accountBean.getAccountId());
        couponCodeVerificationDto.setNumber("1");
        couponCodeVerificationDto.setChannel(OrderClientType.ALIPAY.getIndex().toString().equals(orderBean.getOrderClient())
                ? MCCafeChannelEnum.MOCOFFEE_ZFB.getName():MCCafeChannelEnum.MOCOFFEE_WX.getName());
        couponCodeVerificationDto.setOperatorId("-1");
        couponCodeVerificationDto.setStationId("-1");
        couponCodeVerificationDto.setSign("skip");

        return couponOfflineMCCafeClient.lock(couponCodeVerificationDto);
    }

    @Override
    public CouponBaseResponse unlock(MCCafeCouponLockRequest mcCafeCouponLockRequest) {
        return couponOfflineMCCafeClient.unlock(mcCafeCouponLockRequest);
    }
}
