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.StoreService;
import cn.freemud.service.coupon.CouponRelationFactory;
import cn.freemud.service.coupon.CouponRelationService;
//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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

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

    /**
     * coco商户
     */
    @Value("#{'${coco.partnerId}'.split(',')}")
    private List<String> cocoPartnerId;

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

    @Autowired
    private CouponRelationFactory couponRelationFactory;

    /**
     * 核销优惠券
     *
     * @param orderBean
     */
    @Override
    public BaseResponse verificationCoupon(QueryOrdersResponseDto.DataBean.OrderBean orderBean,CouponReqType couponReqType) {
        List<QueryOrdersResponseDto.DataBean.OrderBean.AccountBean> accountList = orderBean.getAccountList();
        if (CollectionUtils.isEmpty(accountList) || CollectionUtils.isEmpty(orderBean.getProductList())) {
            return ResponseUtil.success();
        }

        // 平台走老的逻辑，cooc定制参数
        CouponRelationService couponRelationService = couponRelationFactory.getVerificationCouponService(orderBean.getCompanyId());
        return couponRelationService.verificationCoupon(accountList,orderBean,couponReqType);
    }

    @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.getCode(), 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);
        }
    }
}
