package cn.freemud.management.adapter;

import cn.freemud.base.constant.Version;
import cn.freemud.management.entities.dto.request.order.*;
import cn.freemud.management.entities.dto.response.coupon.McdNetBatchQueryResponse;
import cn.freemud.management.enums.CouponReqTypeEnum;
import cn.freemud.management.enums.MCCafeChannelEnum;
import cn.freemud.management.thirdparty.CouponOfflineMCCafeClient;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.ordercenter.entities.v1.AccountBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductBeanV1;
import com.freemud.application.sdk.api.ordercenter.entities.v1.ProductDiscountV1;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.enums.orderv1.OrderSourceV1;
import com.freemud.application.sdk.api.ordercenter.util.LogUtil;
import com.freemud.sdk.api.assortment.order.enums.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.QueryOrderAccountType;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Component
public class McCafeCouponAdapter {

    @Autowired
    private CouponOfflineMCCafeClient couponOfflineMCCafeClient;

    @Autowired
    private LogUtil logUtil;
    private Integer SUCCESS = 100;

    public List<MCCafeCouponRequest> convertOrderBean2CouponLockRequest(OrderBeanV1 orderBean) {
        if (null == orderBean || CollectionUtils.isEmpty(orderBean.getAccountList())) {
            return null;
        }

        List<AccountBeanV1> accountList = orderBean.getAccountList().stream().filter(
                account -> (OldOrderAccountType.COUPON.getCode().equals(account.getType())
                        || OldOrderAccountType.PRODUCT_COUPON.getCode().equals(account.getType())
                        || OldOrderAccountType.EVM_PRODUCT_COUPON.getCode().equals(account.getType())
                        || OldOrderAccountType.DISCOUNT_COUPON.getCode().equals(account.getType())
                        || OldOrderAccountType.FREIGHT_COUPON.getCode().equals(account.getType()))
        ).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(accountList) ) {
            return null;
        }
        MCCafeCouponRequest mcCafeCouponRequest = MCCafeCouponRequest.builder()
                .ver(88)
                .reqtype(88)
                .partnerId(Integer.parseInt(orderBean.getCompanyId()))
                .store_id(orderBean.getShopId())
                .station_id("1")
                .operator_id(orderBean.getUserId())
                .channel(OrderSourceV1.ALIPAY.getCode().equals(orderBean.getSource())?MCCafeChannelEnum.MOCOFFEE_ZFB.getName():MCCafeChannelEnum.MOCOFFEE_WX.getName())
                .couponlist(accountList.stream().map(o -> new MCCafeCouponVo(o.getAccountId())).collect(Collectors.toList()))
                .sign("skip")
                .build();
        McdNetBatchQueryResponse mcdNetBatchQueryResponse = couponOfflineMCCafeClient.batchQuery(mcCafeCouponRequest);
        if (mcdNetBatchQueryResponse == null || !SUCCESS.equals(mcdNetBatchQueryResponse.getStatusCode())
                || CollectionUtils.isEmpty(mcdNetBatchQueryResponse.getCouponlist())) {
            logUtil.error("","获取优惠券详情失败，无法核销,mcCafeCouponRequest:{},mcdNetBatchQueryResponse:{}", null,mcCafeCouponRequest, mcdNetBatchQueryResponse);
            return null;
        }

        Map<String, McdNetBatchQueryResponse.Coupon> couponMap = mcdNetBatchQueryResponse.getCouponlist().stream()
                .collect(Collectors.toMap(McdNetBatchQueryResponse.Coupon::getCode, Function.identity(), (k1, k2) -> k1));
        List<MCCafeCouponRequest> list = new ArrayList<>();
        accountList.forEach(accountBean -> list.add(convert2MCCafeCouponRequest(orderBean, accountBean, couponMap.get(accountBean.getAccountId()))));
        return list;
    }

    public MCCafeCouponRequest convert2MCCafeCouponRequest(OrderBeanV1 orderBean, AccountBeanV1 accountBean, McdNetBatchQueryResponse.Coupon coupon) {
        List<MCCafeProductRedeemVo> products = new ArrayList<>();
        //商品券核销核销参数
        if (OldOrderAccountType.PRODUCT_COUPON.getCode().equals(accountBean.getType()) || OldOrderAccountType.EVM_PRODUCT_COUPON.getCode().equals(accountBean.getType())) {
            for (int i = 0; i < orderBean.getProductList().size(); i++) {
                ProductBeanV1 productBean = orderBean.getProductList().get(i);
                String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                if (!org.springframework.util.CollectionUtils.isEmpty(productBean.getDiscountList())) {
                    List<ProductDiscountV1> discounts = productBean.getDiscountList().stream().
                            filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                    for (ProductDiscountV1 productDiscount : discounts) {
                        if (productDiscount.getDiscountType() == null || productDiscount.getDiscountType() == 0) {
                            continue;
                        }
                        MCCafeProductRedeemVo mcCafeProductRedeemVo = new MCCafeProductRedeemVo();
                        mcCafeProductRedeemVo.setPid(pid);
                        String extInfo = productDiscount.getAddInfo();
                        Integer extendType = StringUtils.isBlank(extInfo)?null: JSON.parseObject(extInfo).getInteger("extendType");
                        if(extendType != null && extendType == 4) {
                            mcCafeProductRedeemVo.setKeyProductCode(JSON.parseObject(extInfo).getString("tenderId"));
                            mcCafeProductRedeemVo.setCustomer_code(JSON.parseObject(extInfo).getString("tenderId"));
                        } else {
                            mcCafeProductRedeemVo.setKeyProductCode(productBean.getCustomerCode());
                            mcCafeProductRedeemVo.setCustomer_code(productBean.getCustomerCode());
                        }
                        mcCafeProductRedeemVo.setConsume_num(productDiscount.getDiscountQty());
                        mcCafeProductRedeemVo.setSeq(i + 1);
                        if(null != coupon && CollectionUtils.isNotEmpty(coupon.getCodeInfo().getGroups())) {
                            mcCafeProductRedeemVo.setGid(coupon.getCodeInfo().getGroups().get(0).getGid());
                        }
                        products.add(mcCafeProductRedeemVo);
                    }
                }
            }
        }else if (OldOrderAccountType.COUPON.getCode().equals(accountBean.getType())) {
            for (int i = 0; i < orderBean.getProductList().size(); i++) {
                ProductBeanV1 productBean = orderBean.getProductList().get(i);
                String pid = StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                MCCafeProductRedeemVo mcCafeProductRedeemVo = new MCCafeProductRedeemVo();
                mcCafeProductRedeemVo.setPid(pid);
                mcCafeProductRedeemVo.setKeyProductCode(productBean.getCustomerCode());
                mcCafeProductRedeemVo.setCustomer_code(productBean.getCustomerCode());
                mcCafeProductRedeemVo.setConsume_num(productBean.getNumber());
                mcCafeProductRedeemVo.setSeq(i + 1);
                products.add(mcCafeProductRedeemVo);
            }
        }
        MCCafeCouponRequest mcCafeCouponRequest = new MCCafeCouponRequest();
        mcCafeCouponRequest.setVer(Integer.valueOf(Version.VERSION_1));
        mcCafeCouponRequest.setReqtype(CouponReqTypeEnum.REDEEM.getCode());
        mcCafeCouponRequest.setPartnerId(Integer.parseInt(orderBean.getCompanyId()));
        mcCafeCouponRequest.setStore_id(orderBean.getShopId());
        mcCafeCouponRequest.setStation_id("-1");
        mcCafeCouponRequest.setOperator_id("-1");
        // 订单号
        mcCafeCouponRequest.setTrans_id(orderBean.getOid());
        mcCafeCouponRequest.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);
        mcCafeCouponRequest.setTransactions(transactions);
        mcCafeCouponRequest.setSign("skip");

        mcCafeCouponRequest.setAppFlag("kgd.Y");
        mcCafeCouponRequest.setBusiness_date(cn.freemud.base.util.DateUtil.convert2Str(new Date(), cn.freemud.base.util.DateUtil.FORMAT_yyyyMMdd));
        return mcCafeCouponRequest;
    }


    /**
     * 获取聚合订单活动类型
     */
    public QueryOrderAccountType getQueryOrderAccountType(OldOrderAccountType oldOrderAccountType) {
        return QueryOrderAccountType.getByCode(oldOrderAccountType.getMessage());
    }




    public List<MCCafeCouponLockRequest> convertOrderBean2UnlockCoupon(OrderBeanV1 orderBean) {
        if (null == orderBean || CollectionUtils.isEmpty(orderBean.getAccountList())) {
            return null;
        }
        List<AccountBeanV1> accountList = orderBean.getAccountList().stream().filter(
                account -> (getQueryOrderAccountType(OldOrderAccountType.getByCode(account.getType())).equals(QueryOrderAccountType.COUPON)
                        ||  getQueryOrderAccountType(OldOrderAccountType.getByCode(account.getType())).equals(QueryOrderAccountType.PRODUCT_COUPON)
                        ||  getQueryOrderAccountType(OldOrderAccountType.getByCode(account.getType())).equals(QueryOrderAccountType.DISCOUNT_COUPON))
        ).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(accountList) ) {
            return null;
        }
        List<MCCafeCouponLockRequest> list = new ArrayList<>();
        accountList.forEach(accountBean -> list.add(convert2MCCafeCouponLockRequest(orderBean, accountBean)));
        return list;
    }

    public MCCafeCouponLockRequest convert2MCCafeCouponLockRequest(OrderBeanV1 orderBean, AccountBeanV1 accountBean) {
        MCCafeCouponLockRequest mcCafeCouponLockRequest = new MCCafeCouponLockRequest();
        mcCafeCouponLockRequest.setVer(Integer.valueOf(Version.VERSION_1));
        mcCafeCouponLockRequest.setReqType(CouponReqTypeEnum.UNLOCK.getCode());
        mcCafeCouponLockRequest.setPartnerId(orderBean.getCompanyId());
        mcCafeCouponLockRequest.setStoreId(orderBean.getShopId());
        // 订单号
        mcCafeCouponLockRequest.setTransId(orderBean.getOid());
        mcCafeCouponLockRequest.setCoupon(accountBean.getAccountId());
        mcCafeCouponLockRequest.setOfferId(accountBean.getAccountId());
        mcCafeCouponLockRequest.setNumber("1");
        mcCafeCouponLockRequest.setChannel(OrderSourceV1.ALIPAY.getCode().equals(orderBean.getSource())?
                MCCafeChannelEnum.MOCOFFEE_ZFB.getName():MCCafeChannelEnum.MOCOFFEE_WX.getName());
        mcCafeCouponLockRequest.setOperatorId("-1");
        mcCafeCouponLockRequest.setStationId("-1");
        mcCafeCouponLockRequest.setSign("skip");

        return mcCafeCouponLockRequest;
    }
}
