package cn.freemud.service.impl;

import cn.freemud.adapter.CouponAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.vo.ActivityClassifyCouponBean;
import cn.freemud.entities.vo.ActivityCouponBean;
import cn.freemud.enums.*;
import cn.freemud.service.CouponActivityService;
import cn.freemud.service.thirdparty.CouponClient;
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.ApiLog;
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.sdk.api.assortment.order.enums.OldOrderAccountType;
import com.freemud.sdk.api.assortment.order.enums.QueryOrderAccountType;
import com.freemud.sdk.api.assortment.order.request.order.CreateOrderAccountRequest;
import com.google.common.base.Throwables;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 券服务
 */
@Service
public class CouponActivityServiceImpl implements CouponActivityService {

    @Autowired
    private CouponAdapter couponAdapter;
    @Autowired
    private CouponOfflineClient couponOfflineClient;
    @Autowired
    private EmailAlertService emailAlertService;
    @Autowired
    private OfflineCouponSdkService offlineCouponSdkService;


    /**
     * 核销优惠券
     *
     * @param orderBean
     */
    @Override
    public BaseResponse verificationCoupon(QueryOrdersResponseDto.DataBean.OrderBean orderBean) {
        List<QueryOrdersResponseDto.DataBean.OrderBean.AccountBean> accountList = orderBean.getAccountList();
        if (CollectionUtils.isEmpty(accountList) || CollectionUtils.isEmpty(orderBean.getProductList())) {
            return ResponseUtil.success();
        }
        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();
            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());
                try {
                    //71.券核销
                    CouponCodeResponseDto couponCodeResponseDto = couponOfflineClient.verification(couponCodeVerificationDto);
                    ThirdPartyLog.infoConvertJson(System.currentTimeMillis(), System.currentTimeMillis(), "/api", couponCodeVerificationDto, couponCodeResponseDto);
                    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();
    }

    @Override
    public BaseResponse callbackNotify(QueryOrdersResponseDto.DataBean.OrderBean orderBean) {
        if (CollectionUtils.isEmpty(orderBean.getAccountList())) {

            return ResponseUtil.success();
        }
        QueryOrdersResponseDto.DataBean.OrderBean.AccountBean accountBean = orderBean.getAccountList().stream().filter(account -> account.getType().equals(OldOrderAccountType.COUPON.getCode()) || account.getType().equals(OldOrderAccountType.PRODUCT_COUPON.getCode())
                || account.getType().equals(OldOrderAccountType.DISCOUNT_COUPON.getCode())).findFirst().orElse(null);
        if (accountBean == null) {
            return ResponseUtil.success();
        }
        String orderCode = orderBean.getOid();
        String partnerId = orderBean.getCompanyId();
        String couponCode=accountBean.getAccountId();

        try {
            //移除卡包失败，邮件报警
            com.freemud.application.sdk.api.base.BaseResponse baseResponse = offlineCouponSdkService.callbackNotify(couponCode, orderCode, partnerId,"");
            if (!Objects.equals(baseResponse.getStatusCode(), ResponseResult.SUCCESS.getCode())) {
                emailAlertService.sendEmailAlert("券码移除卡包失败", String.format("request:%s \r\nresponse:%s","券码号："+couponCode+"订单号："+orderCode, JSONObject.toJSONString(baseResponse)));
                return ResponseUtil.error(ResponseResult.COUPON_CALLBACK_FAIL);
            }
            return ResponseUtil.success();
        } catch (Exception ex) {
            emailAlertService.sendEmailAlert("券码移除卡包异常", String.format("request:%s \r\nexception:%s", "券码号："+couponCode+"订单号："+orderCode, Throwables.getStackTraceAsString(ex)));
            ErrorLog.printErrorLog("verification_error", "/callbackNotify", orderCode, ex);
            return ResponseUtil.error(ResponseResult.COUPON_CALLBACK_FAIL);
        }
    }
}
