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.ActivityTypeEnum;
import cn.freemud.management.enums.CouponReqTypeEnum;
import cn.freemud.management.enums.MCCafeChannelEnum;
import cn.freemud.management.enums.OrderSource;
import cn.freemud.management.thirdparty.CouponOfflineMCCafeClient;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.sdk.api.assortment.order.enums.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.OrderSourceType;
import com.freemud.sdk.api.assortment.order.enums.QueryOrderAccountType;
import com.freemud.sdk.api.assortment.order.request.order.CreateOrderAccountRequest;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class McCafeCouponAdapter {

    @Autowired
    private CouponOfflineMCCafeClient couponOfflineMCCafeClient;

    private Integer SUCCESS = 100;

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

        List<QueryOrdersResponse.DataBean.OrderBean.AccountBean> 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;
        }
        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(OrderSource.ALIPAY.getSource().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())) {
            log.error("获取优惠券详情失败，无法核销", 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(QueryOrdersResponse.DataBean.OrderBean orderBean, QueryOrdersResponse.DataBean.OrderBean.AccountBean accountBean, McdNetBatchQueryResponse.Coupon coupon) {
        List<MCCafeProductRedeemVo> products = new ArrayList<>();
        //商品券核销核销参数
        if (QueryOrderAccountType.PRODUCT_COUPON.equals(getQueryOrderAccountType(OldOrderAccountType.getByCode(accountBean.getType())))) {
            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(productBean.getDiscountList())) {
                    List<QueryOrdersResponse.DataBean.OrderBean.ProductBean.ProductDiscount> discounts = productBean.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);
                        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 (QueryOrderAccountType.COUPON.equals(getQueryOrderAccountType(OldOrderAccountType.getByCode(accountBean.getType())))) {
            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();
                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(QueryOrdersResponse.DataBean.OrderBean orderBean) {
        if (null == orderBean || CollectionUtils.isEmpty(orderBean.getAccountList())) {
            return null;
        }
        List<QueryOrdersResponse.DataBean.OrderBean.AccountBean> 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(QueryOrdersResponse.DataBean.OrderBean orderBean, QueryOrdersResponse.DataBean.OrderBean.AccountBean 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(OrderSourceType.ALIPAY.getCode().equals(orderBean.getSource())?
                MCCafeChannelEnum.MOCOFFEE_ZFB.getName():MCCafeChannelEnum.MOCOFFEE_WX.getName());
        mcCafeCouponLockRequest.setOperatorId("-1");
        mcCafeCouponLockRequest.setStationId("-1");
        mcCafeCouponLockRequest.setSign("skip");

        return mcCafeCouponLockRequest;
    }
}
