/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: PlatformOrderRelationServiceImpl
 * @Description:
 * @author: pengfei.liu
 * @date: 2020/11/23
 * @version V1.0
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */

package cn.freemud.service.coupon.impl;

import cn.freemud.adapter.CouponAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.dto.CouponCodeResponseDto;
import cn.freemud.entities.dto.CouponCodeVerificationDto;
import cn.freemud.entities.dto.CouponCodeVerificationProductDto;
import cn.freemud.entities.dto.QueryOrdersResponseDto;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.QueryOrderResponseVo;
import cn.freemud.enums.ActivityChannelEnum;
import cn.freemud.enums.CouponReqType;
import cn.freemud.enums.OrderAccountType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.management.enums.OrderSource;
import cn.freemud.service.coupon.CouponRelationFactory;
import cn.freemud.service.coupon.CouponRelationService;
import cn.freemud.service.impl.StoreServiceImpl;
import cn.freemud.service.order.OrderRelationService;
import cn.freemud.service.thirdparty.CouponOfflineClient;
import cn.freemud.utils.LogUtil;
import cn.freemud.utils.PropertyConvertUtil;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.couponcenter.offline.service.OfflineCouponSdkService;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.ThirdPartyLog;
import com.freemud.application.sdk.api.service.EmailAlertService;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import com.google.common.base.Throwables;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service("platformCouponRelationService")
public class PlatformCouponRelationServiceImpl implements CouponRelationService {

    @Autowired
    private CouponAdapter couponAdapter;
    @Autowired
    private CouponOfflineClient couponOfflineClient;
    @Autowired
    private EmailAlertService emailAlertService;
    @Autowired
    private StoreServiceImpl storeService;

    @Override
    public BaseResponse verificationCoupon(List<QueryOrdersResponseDto.DataBean.OrderBean.AccountBean> accountList, QueryOrdersResponseDto.DataBean.OrderBean orderBean, CouponReqType couponReqType) {
        for (QueryOrdersResponseDto.DataBean.OrderBean.AccountBean accountBean : accountList) {
            List<CouponCodeVerificationProductDto> products = new ArrayList<>();
            //商品券核销核销参数
            if (OrderAccountType.PRODUCT_COUPON.getCode().equals(accountBean.getType())) {
                for (int i = 0; i < orderBean.getProductList().size(); i++) {
                    QueryOrdersResponseDto.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<QueryOrdersResponseDto.DataBean.OrderBean.ProductBean.ProductDiscount> discounts = orderBean.getProductList().get(i).getDiscountList().stream().
                                filter(productDiscount -> productDiscount.getDiscountId().equals(accountBean.getAccountId())).collect(Collectors.toList());
                        for (QueryOrdersResponseDto.DataBean.OrderBean.ProductBean.ProductDiscount productDiscount : discounts) {
                            if (productDiscount.getDiscountType() == null || productDiscount.getDiscountType() == 0) {
                                continue;
                            }
                            CouponCodeVerificationProductDto couponCodeVerificationProductDto = new CouponCodeVerificationProductDto();
                            couponCodeVerificationProductDto.setPID(pid);
                            couponCodeVerificationProductDto.setConsume_num(productDiscount.getDiscountQty());
                            couponCodeVerificationProductDto.setSeq(i + 1);
                            products.add(couponCodeVerificationProductDto);
                        }
                    }
                }
            }

            Integer orderType = orderBean.getType();
            //商城单子用NewOrderType
            if(Objects.equals(OrderSource.MALL.getSource(),orderBean.getSource())){
                orderType = orderBean.getNewOrderType();
            }
            ActivityChannelEnum activityChannelEnum = PropertyConvertUtil.orderTypeEnumConvert2ActivityChannel(orderType);
            if (activityChannelEnum == null) {
                activityChannelEnum = ActivityChannelEnum.pickup;
            }

            if (OrderAccountType.COUPON.getCode().equals(accountBean.getType())
                    || OrderAccountType.PRODUCT_COUPON.getCode().equals(accountBean.getType())
                    || OrderAccountType.DISCOUNT_COUPON.getCode().equals(accountBean.getType())) {
                CouponCodeVerificationDto couponCodeVerificationDto = couponAdapter.convert2CouponCodeVerificationDto(activityChannelEnum, accountBean.getAccountId(), orderBean.getOid(), orderBean.getCompanyId(), orderBean.getShopId(), orderBean.getUserId(), products, accountBean.getPrice().intValue(),couponReqType);
                couponCodeVerificationDto.setOrderTotalAmount(orderBean.getOriginalAmount()==null ? 0L: orderBean.getOriginalAmount().longValue());
                couponCodeVerificationDto.setOrderPaymentAmount(orderBean.getAmount());
                couponCodeVerificationDto.setOrderDiscountAmount(orderBean.getOriginalAmount().longValue()-orderBean.getAmount());
                // 核销券新增参数：组织机构ID
                couponCodeVerificationDto.setChannel_codes(storeService.getOrgIdsArr(orderBean.getCompanyId(), orderBean.getShopId()));
                try {
                    //71.券核销
                    for (int i = 2; i >= 0; i--) {
                        LogUtil.info("核销券码开始==", JSON.toJSONString(couponCodeVerificationDto), null);
                        CouponCodeResponseDto couponCodeResponseDto = couponOfflineClient.verification(couponCodeVerificationDto);
                        LogUtil.info("核销券码返回==", JSON.toJSONString(couponCodeVerificationDto), null);
                        ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(), "/api", couponCodeVerificationDto, couponCodeResponseDto);
                        if (Objects.equals(couponCodeResponseDto.getStatusCode(), ResponseResult.SUCCESS.getCode())) {
                            LogUtil.info("CouponReverseServiceImpl", JSON.toJSONString(couponCodeVerificationDto), JSON.toJSONString(couponCodeResponseDto));
                            break;
                        }
                        if (!Objects.equals(couponCodeResponseDto.getStatusCode(), ResponseResult.SUCCESS.getCode())) {
                            emailAlertService.sendEmailAlert("核销券码失败", String.format("request:%s \r\nresponse:%s", JSONObject.toJSONString(couponCodeVerificationDto), JSONObject.toJSONString(couponCodeResponseDto)));
                            return ResponseUtil.error(ResponseResult.COUPON_VERIFICATION_FAIL);
                        }
                    }

                } catch (Exception ex) {
                    emailAlertService.sendEmailAlert("核销券码异常", String.format("request:%s \r\nexception:%s", JSONObject.toJSONString(couponCodeVerificationDto), Throwables.getStackTraceAsString(ex)));
                    ErrorLog.printErrorLog("verification_error", "/api", couponCodeVerificationDto, ex);
                    return ResponseUtil.error(ResponseResult.COUPON_VERIFICATION_FAIL);
                }
            }
        }
        return ResponseUtil.success();
    }
}
