/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: OrderAdapter
 * @Package cn.freemud.adapter
 * @Description:
 * @author: liming.guo
 * @date: 2018/5/21 20:34
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.adapter;

import cn.freemud.base.constant.Version;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.management.entities.dto.request.order.*;
import cn.freemud.entities.dto.openplatform.AddWeixinCardCodeRequestDto;
import cn.freemud.entities.dto.openplatform.AddWeixinCardCodeResponseDto;
import cn.freemud.entities.dto.openplatform.AddWeixinCardJudgeRequestDto;
import cn.freemud.entities.dto.openplatform.AddWeixinCardJudgeResponseDto;
import cn.freemud.entities.dto.promotion.CouponPromotionDto;
import cn.freemud.entities.dto.promotion.OrderBeanRequest;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.*;
import cn.freemud.management.entities.dto.response.coupon.McdNetBatchQueryResponse;
import cn.freemud.management.entities.dto.response.coupon.McdNetCouponProductRespDto;
import cn.freemud.management.enums.OrderSource;
import cn.freemud.service.mccafe.CouponClientService;
import cn.freemud.utils.BeanUtil;
import cn.freemud.utils.LogUtil;
import com.alibaba.fastjson.JSON;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.card.sdk.vo.coupon.request.MemberAddCouponVo;
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.freemud.sdk.api.assortment.order.response.order.QueryOrdersResponse;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.math.BigDecimal;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Component
public class CouponAdapter {

    @Autowired
    private OrderAdapter orderAdapter;

    @Autowired
    private CouponClientService couponClientService;

    public CouponListDto convert2CouponListDto(String userId, String partnerId) {
        CouponListDto couponListDto = new CouponListDto();
        couponListDto.setPartnerCode(partnerId);
        couponListDto.setUserId(userId);
        couponListDto.setVer(Version.VERSION_1);
        // 优惠券类型，0：满减券 1：代金券
        couponListDto.setType(1);
        return couponListDto;
    }

    public ActivityCouponBean convert2ActivityCouponBean(CouponListResponseDto.CouponBean couponBean
            , Long payAmount, String storeId, boolean benefit) {
        if (couponBean == null) {
            return null;
        }
        ActivityCouponBean activityCouponBean = new ActivityCouponBean();
        activityCouponBean.setCouponCode(couponBean.getCouponCode());
        activityCouponBean.setCouponName(couponBean.getActivityName());
        activityCouponBean.setEndTime(DateUtil.convert2Str(new Date(couponBean.getValidityPeriodEnd()), DateUtil.FORMAT_yyyyMMdd_date));
        activityCouponBean.setDiscountAmount(couponBean.getDiscountAmount() + "");
        activityCouponBean.setThresholdDesc("满" + formatAmount((couponBean.getThresholdAmount()) * 1.00 / 100) + "元可用");
        if (couponBean.getActivity() != null && Objects.equals(couponBean.getActivity().getIsShared(), ActivityShareType.NOT_SHARE.getCode())) {
            activityCouponBean.setActivityDesc("不与其他活动优惠同时享受。");
        } else {
            activityCouponBean.setActivityDesc("可与其他活动优惠同时享受。");
        }
        /**
         * 不与其他优惠同享
         * 不满足券的指定消费金额
         * 门店不可用
         * 不满足券开始使用时间
         */
        Long now = System.currentTimeMillis();
        if (couponBean.getActivity() != null && Objects.equals(couponBean.getActivity().getIsShared(), ActivityShareType.NOT_SHARE.getCode()) && benefit) {
            activityCouponBean.setUnusedReason("不与其他优惠同享");
        } else if (payAmount < couponBean.getThresholdAmount()) {
            activityCouponBean.setUnusedReason("不满足券的指定消费金额");
        } else if (!Arrays.stream(couponBean.getStoreId().split(",")).anyMatch(Predicate.isEqual(storeId))) {
            activityCouponBean.setUnusedReason("门店不可用");
        } else if (now < couponBean.getValidityPeriodStart()) {
            activityCouponBean.setUnusedReason("不满足券开始使用时间");
        }
        return activityCouponBean;

    }

    public CouponVerificationDto convert2CouponVerificationDto(String userId, String storeId
            , String partnerCode, String orderId, String couponCode) {
        CouponVerificationDto couponVerificationDto = new CouponVerificationDto();
        couponVerificationDto.setVer(Version.VERSION_1);
        couponVerificationDto.setUserId(userId);
        couponVerificationDto.setStoreId(storeId);
        couponVerificationDto.setPartnerCode(partnerCode);
        couponVerificationDto.setOrderId(orderId);
        couponVerificationDto.setCodes(Arrays.asList(couponCode));
        return couponVerificationDto;
    }

    public VerifyCheckRequestDto convert2VerifyCheckRequestDto(String couponCode, String partnerCode, String userId) {
        VerifyCheckRequestDto verifyCheckRequestDto = new VerifyCheckRequestDto();
        verifyCheckRequestDto.setCouponCodes(Arrays.asList(couponCode));
        verifyCheckRequestDto.setPartnerCode(partnerCode);
        verifyCheckRequestDto.setUserId(userId);
        verifyCheckRequestDto.setVer(Integer.valueOf(Version.VERSION_1));
        return verifyCheckRequestDto;
    }

    public VerifyNoticeRequestDto convert2VerifyNoticeRequestDto(String couponCode, String orderId, String partnerCode, String storeId, String userId) {
        VerifyNoticeRequestDto verifyNoticeRequestDto = new VerifyNoticeRequestDto();
        verifyNoticeRequestDto.setVer(Integer.valueOf(Version.VERSION_1));
        verifyNoticeRequestDto.setCouponCode(couponCode);
        verifyNoticeRequestDto.setOrderId(orderId);
        verifyNoticeRequestDto.setPartnerCode(partnerCode);
        verifyNoticeRequestDto.setStoreId(storeId);
        verifyNoticeRequestDto.setUserId(userId);
        return verifyNoticeRequestDto;
    }

    public CouponCodeVerificationDto convert2CouponCodeVerificationDto(ActivityChannelEnum activityChannelEnum, String couponCode, String orderId,
                                                                       String partnerCode, String storeId, String userId,
                                                                       List<CouponCodeVerificationProductDto> products, Integer discountPrice, CouponReqType couponReqType) {
        CouponCodeVerificationDto couponCodeVerificationDto = new CouponCodeVerificationDto();
        couponCodeVerificationDto.setVer(Integer.valueOf(Version.VERSION_1));
        couponCodeVerificationDto.setReqtype(couponReqType.getCode());
        couponCodeVerificationDto.setPartnerId(partnerCode);
        couponCodeVerificationDto.setChannel(activityChannelEnum.getCode());
        couponCodeVerificationDto.setStation_id("-1");
        couponCodeVerificationDto.setOperator_id("-1");
        couponCodeVerificationDto.setStore_id(storeId);
        // 订单号 替换成唯一序号
        couponCodeVerificationDto.setTrans_id(orderId);
        couponCodeVerificationDto.setBusiness_date(DateUtil.convert2Str(new Date(), DateUtil.FORMAT_yyyyMMdd));
        List<CouponCodeVerificationTransDto> transactions = new ArrayList<>();
        CouponCodeVerificationTransDto couponCodeVerificationTransDto = new CouponCodeVerificationTransDto();
        couponCodeVerificationTransDto.setCode(couponCode);
        if (discountPrice != null && discountPrice < 0) {
            discountPrice = 0 - discountPrice;
        }
        couponCodeVerificationTransDto.setTotalAmount(discountPrice);
        if (CollectionUtils.isNotEmpty(products)) {
            couponCodeVerificationTransDto.setProducts(products);
        }
        transactions.add(couponCodeVerificationTransDto);
        couponCodeVerificationDto.setTransactions(transactions);
        return couponCodeVerificationDto;
    }

    public CouponCodeVerificationDto convert2CouponReverseDto(ActivityChannelEnum activityChannelEnum, String couponCode, String orderId,
                                                                       String partnerCode, String storeId, String userId,
                                                                       List<CouponCodeVerificationProductDto> products, Integer discountPrice) {
        CouponCodeVerificationDto couponCodeVerificationDto = new CouponCodeVerificationDto();
        couponCodeVerificationDto.setVer(Integer.valueOf(Version.VERSION_1));
        couponCodeVerificationDto.setReqtype(3);
        couponCodeVerificationDto.setPartnerId(partnerCode);
        couponCodeVerificationDto.setChannel(activityChannelEnum.getCode());
        couponCodeVerificationDto.setStation_id("-1");
        couponCodeVerificationDto.setOperator_id("-1");
        couponCodeVerificationDto.setStore_id(storeId);
        // 订单号 替换成唯一序号
        couponCodeVerificationDto.setTrans_id(orderId);
        couponCodeVerificationDto.setBusiness_date(DateUtil.convert2Str(new Date(), DateUtil.FORMAT_yyyyMMdd));
        List<CouponCodeVerificationTransDto> transactions = new ArrayList<>();
        CouponCodeVerificationTransDto couponCodeVerificationTransDto = new CouponCodeVerificationTransDto();
        couponCodeVerificationTransDto.setCode(couponCode);
        if (discountPrice != null && discountPrice < 0) {
            discountPrice = 0 - discountPrice;
        }
        couponCodeVerificationTransDto.setTotalAmount(discountPrice);
        if (CollectionUtils.isNotEmpty(products)) {
            couponCodeVerificationTransDto.setProducts(products);
        }
        transactions.add(couponCodeVerificationTransDto);
        couponCodeVerificationDto.setTransactions(transactions);
        return couponCodeVerificationDto;
    }

    public CouponCreateDto convert2CouponCreateDto(String userId, List<String> activityCodes
            , String partnerCode, String mobile, String storeId) {
        CouponCreateDto couponCreateDto = new CouponCreateDto();
        couponCreateDto.setVer(Version.VERSION_1);
        couponCreateDto.setUserId(userId);
        couponCreateDto.setActivityCodes(activityCodes);
        couponCreateDto.setPartnerCode(partnerCode);
        couponCreateDto.setMobile(mobile);
        couponCreateDto.setStoreId(storeId);
        return couponCreateDto;
    }

    public CreateCouponBeanVo conver2CreateCouponBeanVo(CouponListResponseDto.CouponBean couponBean) {
        if (couponBean == null) {
            return null;
        }
        CreateCouponBeanVo createCouponBeanVo = new CreateCouponBeanVo();
        createCouponBeanVo.setThresholdAmount(couponBean.getThresholdAmount());
        createCouponBeanVo.setDiscountAmount(couponBean.getDiscountAmount());
        createCouponBeanVo.setValidityPeriodStart(DateUtil.convert2Str(new Date(couponBean.getValidityPeriodStart()), DateUtil.FORMAT_yyyyMMdd_date));
        createCouponBeanVo.setValidityPeriodEnd(DateUtil.convert2Str(new Date(couponBean.getValidityPeriodEnd()), DateUtil.FORMAT_yyyyMMdd_date));
        createCouponBeanVo.setCouponCode(couponBean.getCouponCode());
        createCouponBeanVo.setActivityName(couponBean.getActivityName());
        createCouponBeanVo.setCouponType(couponBean.getType());
        return createCouponBeanVo;
    }

    // 进店有礼单独使用
    public CouponCreateDto convertEnterShopCouponCreateDto(String userId, List<String> activityCodes
            , String partnerCode, String mobile, String storeId) {
        CouponCreateDto couponCreateDto = new CouponCreateDto();
        couponCreateDto.setVer(Version.VERSION_1);
        couponCreateDto.setUserId(userId);
        couponCreateDto.setActivityCodes(activityCodes);
        couponCreateDto.setPartnerCode(partnerCode);
        couponCreateDto.setMobile(mobile);
        couponCreateDto.setIsAllowPart(1);
        couponCreateDto.setStoreId(storeId);
        return couponCreateDto;
    }

    public CreateActivityRecordDto convert2CreateActivityRecordDto(CreateCouponBeanVo couponBean
            , Long activityId, String partnerId, StoreResponseDto storeResponseDto, String userId
            , String orderId, String nickName) {
        if (couponBean == null) {
            return null;
        }
        CreateActivityRecordDto createActivityRecordDto = new CreateActivityRecordDto();
        createActivityRecordDto.setActivityId(activityId + "");
        createActivityRecordDto.setPartnerId(partnerId);
        createActivityRecordDto.setStoreId(storeResponseDto.getStoreId());
        createActivityRecordDto.setStoreName(storeResponseDto.getStoreName());
        createActivityRecordDto.setUserId(userId);
        createActivityRecordDto.setOrderId(orderId);
        createActivityRecordDto.setPrizeType("满" + formatAmount((couponBean.getThresholdAmount()) * 1.00 / 100) + "元可用");
        createActivityRecordDto.setPrizeProductName(couponBean.getActivityName());
        createActivityRecordDto.setPrizeId(DateUtil.convert2Date(couponBean.getValidityPeriodEnd(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS).getTime() + "");
        createActivityRecordDto.setNum(1);
        createActivityRecordDto.setPrice(Long.valueOf(couponBean.getDiscountAmount()));
        createActivityRecordDto.setCouponId(couponBean.getCouponCode() + "");
        createActivityRecordDto.setRecordInfo(nickName);
        return createActivityRecordDto;
    }

    public ShareReceiveRecordListDto convert2ShareReceiveRecordListDto(Long activityId, String orderId, String partnerId) {
        ShareReceiveRecordListDto shareReceiveRecordListDto = new ShareReceiveRecordListDto();
        shareReceiveRecordListDto.setActivityId(activityId);
        shareReceiveRecordListDto.setBizId(orderId);
        shareReceiveRecordListDto.setPartnerId(partnerId);
        return shareReceiveRecordListDto;
    }

    public ShareAcitivityRequestDto convert2ShareAcitivityRequestDto(String activityId, String orderId, String partnerId
            , String userId, String nickName) {
        ShareAcitivityRequestDto shareAcitivityRequestDto = new ShareAcitivityRequestDto();
        shareAcitivityRequestDto.setActivityId(activityId);
        shareAcitivityRequestDto.setBizId(orderId);
        shareAcitivityRequestDto.setPartnerId(partnerId);
        shareAcitivityRequestDto.setUserId(userId);
        shareAcitivityRequestDto.setNickName(nickName);
        return shareAcitivityRequestDto;
    }

    public EnterShopActivityResponseVo.CouponInfo convert2EnterShopCouponInfo(CreateCouponBeanVo couponBean) {
        if (couponBean == null) {
            return null;
        }
        EnterShopActivityResponseVo.CouponInfo couponInfo = new EnterShopActivityResponseVo.CouponInfo();
        couponInfo.setCouponName(couponBean.getActivityName());
        couponInfo.setDiscountAmount(couponBean.getDiscountAmount());
        couponInfo.setExpiryTime(couponBean.getValidityPeriodEnd());
        couponInfo.setActivityCode(couponBean.getActivityCode());
        couponInfo.setCouponCode(couponBean.getCouponCode());
        // 日期转为年月日
        couponInfo.setValidityPeriodEnd(DateUtil.convert2String(DateUtil.convert2Date(couponBean.getValidityPeriodEnd(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS), DateUtil.FORMAT_YMD).replace("-", "."));
        couponInfo.setValidityPeriodStart(DateUtil.convert2String(DateUtil.convert2Date(couponBean.getValidityPeriodStart(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS), DateUtil.FORMAT_YMD).replace("-", "."));
        couponInfo.setEffectiveData(couponInfo.getValidityPeriodStart() + "-" + couponInfo.getValidityPeriodEnd());
        couponInfo.setCouponType(couponBean.getCouponType());
        return couponInfo;
    }

    public EntershopRecordDto convert2EnterShopRecordDto(List<EnterShopActivityResponseVo.CouponInfo> couponInfos
            , StoreResponseDto storeResponseDto, GetActivitiesResponseDto.PromotionActivity promotionActivity
            , String partnerId, String userId, String nickName) {
        EntershopRecordDto createActivityRecordDto = new EntershopRecordDto();
        createActivityRecordDto.setActivityId(String.valueOf(promotionActivity.getId()));
        createActivityRecordDto.setPartnerId(partnerId);
        createActivityRecordDto.setStoreId(storeResponseDto.getStoreCode());
        createActivityRecordDto.setStoreName(storeResponseDto.getStoreName());
        createActivityRecordDto.setUserId(userId);
        // 订单ID暂时写死为0
        createActivityRecordDto.setOrderId("0");
        createActivityRecordDto.setPrizeType(promotionActivity.getActivityName());
        createActivityRecordDto.setNum(1);
        createActivityRecordDto.setRecordInfo(nickName);
        List<EntershopRecordDto.CouponInfo> coupons = new ArrayList<>();
        for (EnterShopActivityResponseVo.CouponInfo coupon : couponInfos) {
            EntershopRecordDto.CouponInfo couponInfo = new EntershopRecordDto.CouponInfo();
            couponInfo.setCouponId(coupon.getCouponCode());
            couponInfo.setPrizeId(coupon.getValidityPeriodEnd() + "");
            couponInfo.setPrizeProductName(coupon.getCouponName());
            couponInfo.setPrice(coupon.getDiscountAmount());
            coupons.add(couponInfo);
        }
        createActivityRecordDto.setCoupons(coupons);
        return createActivityRecordDto;
    }

    public MemberAddCouponVo convert2MemberAddCouponVo(ReceiveMemberCouponRequestVo requestVo) {
        MemberAddCouponVo memberCardVo = new MemberAddCouponVo();
        memberCardVo.setMemberId(requestVo.getMemberId());
        memberCardVo.setPartnerId(requestVo.getPartnerId());
        List<MemberAddCouponVo.Coupons> receiveMemberCouponList = Lists.newArrayList();
        List<MemberAddCouponVo.Coupons> receiveMemberCouponListList = requestVo.getReceiveMemberCouponListList();
        if (CollectionUtils.isNotEmpty(receiveMemberCouponListList)) {
            receiveMemberCouponListList.forEach(coupon -> {
                MemberAddCouponVo.Coupons addCoupon = new MemberAddCouponVo.Coupons();
                addCoupon.setCouponCode(coupon.getCouponCode());
                addCoupon.setEncodeCouponCode(coupon.getEncodeCouponCode());
                addCoupon.setCouponChannel(coupon.getCouponChannel());
                addCoupon.setActivityCode(coupon.getActivityCode());
                addCoupon.setPromotionCode(coupon.getPromotionCode());
                addCoupon.setCouponName(coupon.getCouponName());
                addCoupon.setCouponType(coupon.getCouponType());
                addCoupon.setStartTime(coupon.getStartTime());
                addCoupon.setEndTime(coupon.getEndTime());
                receiveMemberCouponList.add(addCoupon);
            });
        }
        memberCardVo.setCoupons(receiveMemberCouponList);
        return memberCardVo;
    }

    public List<GetMemberCouponListResponseVo.MemberCoupon> convert2MemberCouponList(List<GetMemberCouponListResponseDto.Result.MemberCoupon> couponList, AddWeixinCardJudgeResponseDto responseDto, Map<String, String> couponBarCodeMap) {
        List<GetMemberCouponListResponseVo.MemberCoupon> memberCouponList = Lists.newArrayList();
        Map<String, AddWeixinCardJudgeResponseDto.ResultBean.MemberCoupon> couponMap = Maps.newTreeMap();
        if (responseDto != null && responseDto.getResult() != null && CollectionUtils.isNotEmpty(responseDto.getResult().getMemberCouponList())) {
            List<AddWeixinCardJudgeResponseDto.ResultBean.MemberCoupon> CouponList = responseDto.getResult().getMemberCouponList();
            couponMap = CouponList.stream().collect(Collectors.toMap(AddWeixinCardJudgeResponseDto.ResultBean.MemberCoupon::getCouponCode, (p) -> p));
        }
        if (CollectionUtils.isNotEmpty(couponList)) {
            for (GetMemberCouponListResponseDto.Result.MemberCoupon memberCoupon : couponList) {
                GetMemberCouponListResponseVo.MemberCoupon myMemberCoupon = new GetMemberCouponListResponseVo.MemberCoupon();
                BeanUtil.convertBean(memberCoupon, myMemberCoupon);
                myMemberCoupon.setType(memberCoupon.getCouponType());
                myMemberCoupon.setActivityName(memberCoupon.getCouponName());
                myMemberCoupon.setDateDescribe(getDateDescribe(myMemberCoupon.getStatus(), myMemberCoupon.getStartTime(), myMemberCoupon.getEndTime()));
                //折扣百分比（折扣券时有）
                BigDecimal percentDiscount = memberCoupon.getCouponType().equals(CouponTypeEnum.TYPE_3.getCode()) ? memberCoupon.getPercentDiscount() : new BigDecimal(0);
                myMemberCoupon.setPercentDiscount(percentDiscount.divide(new BigDecimal("10")));
                Long price = memberCoupon.getCouponType().equals(CouponTypeEnum.TYPE_1.getCode()) && memberCoupon.getOriginalPrice() != null ? memberCoupon.getOriginalPrice() : 0;
                //代金券金额
                myMemberCoupon.setPriceOriginal(price);
                //最低金额（满多少可用）
                Long minAmount = !memberCoupon.getCouponType().equals(CouponTypeEnum.TYPE_0.getCode()) && memberCoupon.getMinAmount() != null ? memberCoupon.getMinAmount() : 0;
                myMemberCoupon.setMinAmount(minAmount);
                String startDate = DateUtil.convert2String(DateUtil.convert2Date(memberCoupon.getStartTime(), DateUtil.FORMAT_yyyyMMdd_date), DateUtil.FORMAT_yyyyMMdd_date).replace("-", ".");
                String endDate = DateUtil.convert2String(DateUtil.convert2Date(memberCoupon.getEndTime(), DateUtil.FORMAT_yyyyMMdd_date), DateUtil.FORMAT_yyyyMMdd_date).replace("-", ".");
                myMemberCoupon.setStartTime(startDate);
                myMemberCoupon.setEndTime(endDate);
                if (minAmount > 0) {
                    myMemberCoupon.setThresholdDesc(!memberCoupon.getCouponType().equals(CouponTypeEnum.TYPE_0.getCode()) ? "满" + new BigDecimal(minAmount * 1.0).divide(new BigDecimal(100)) + "可用" : "");
                } else {
                    myMemberCoupon.setThresholdDesc(!memberCoupon.getCouponType().equals(CouponTypeEnum.TYPE_0.getCode()) ? "满" + 0 + "可用" : "");
                }
                String addCardFlag = "0";
                if (couponMap.get(memberCoupon.getCouponCode()) != null) {
                    addCardFlag = String.valueOf(couponMap.get(memberCoupon.getCouponCode()).getIsSynWechat());
                }
                myMemberCoupon.setAddCardFlag(addCardFlag);
                GetMemberCouponListResponseVo.MemberCouponDetail detail = new GetMemberCouponListResponseVo.MemberCouponDetail();
                detail.setActivityName(memberCoupon.getCouponName());
                detail.setEndTime(endDate);
                detail.setStartTime(startDate);
                String remark = memberCoupon.getActiveDesc();
                detail.setRemark(getDescribeText(remark));
                detail.setCouponBarCode(couponBarCodeMap.get(memberCoupon.getCouponCode()));
                if (Objects.equals(memberCoupon.getCouponType(), CouponTypeEnum.TYPE_1.getCode())) {
                    detail.setAmountDesc("满" + formatAmount((myMemberCoupon.getMinAmount() == null ? 0 : myMemberCoupon.getMinAmount()) * 1.00 / 100) + "元减" + formatAmount((myMemberCoupon.getPriceOriginal() == null ? 0 : myMemberCoupon.getPriceOriginal().intValue()) * 1.00 / 100) + "元");
                } else if (Objects.equals(memberCoupon.getCouponType(), CouponTypeEnum.TYPE_3.getCode())) {
                    detail.setAmountDesc("满" + formatAmount((myMemberCoupon.getMinAmount() == null ? 0 : myMemberCoupon.getMinAmount()) * 1.00 / 100) + "元" + formatAmount(myMemberCoupon.getPercentDiscount().doubleValue()) + "折");
                }
                myMemberCoupon.setDetail(detail);
                // 先不过滤，让前端对接起来
//                //过滤代金券时，满减为0，折扣券是折扣为0的数据
//                if (!(memberCoupon.getCouponType().equals(CouponTypeEnum.TYPE_1.getCode())
//                        && myMemberCoupon.getPriceOriginal().compareTo(new BigDecimal("0")) == 0)
//                        && !(memberCoupon.getCouponType().equals(CouponTypeEnum.TYPE_3.getCode()) && percentDiscount.compareTo(new BigDecimal("0")) == 0)) {
                memberCouponList.add(myMemberCoupon);
//                }

            }
        }
        return memberCouponList;
    }

    public String getDateDescribe(Integer status, String startTime, String endTime) {
        String describe = "";
        if (CouponStatus.STATUS_1.getCode().equals(status)) {
            describe = "已使用";
        } else if (CouponStatus.STATUS_6.getCode().equals(status)) {
            describe = "已过期";
        } else if (CouponStatus.STATUS_0.getCode().equals(status)) {
            Date startDate = DateUtil.convert2Date(startTime, DateUtil.FORMAT_yyyyMMdd_date);
            Date endDate = DateUtil.convert2Date(endTime, DateUtil.FORMAT_yyyyMMdd_date);
            Date currentDate = DateUtil.convert2Date(new Date(), DateUtil.FORMAT_yyyyMMdd_date);
            Date startDateTime = DateUtil.convert2Date(startTime, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            Date endDateTime = DateUtil.convert2Date(endTime, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            Date currentDateTime = DateUtil.convert2Date(new Date(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
            if (currentDateTime.before(startDateTime)) {
                //当前时间小于券开始时间(*天后开始)
                int days = (int) ((startDate.getTime() - currentDate.getTime()) / (1000 * 3600 * 24));
                switch (days) {
                    case 0:
                        describe = "今天开始";
                        break;
                    case 1:
                        describe = "明天开始";
                        break;
                    case 2:
                        describe = "后天开始";
                        break;
                    case 3:
                        describe = "3天后开始";
                        break;
                    case 4:
                        describe = "4天后开始";
                        break;
                    case 5:
                        describe = "5天后开始";
                        break;
                    case 6:
                        describe = "6天后开始";
                        break;
                    case 7:
                        describe = "7天后开始";
                        break;
                    default:
                        describe = DateUtil.convert2String(startDate, DateUtil.FORMAT_yyyyMMdd_date).replace("-", ".") + "开始";
                        break;
                }
            } else if (currentDateTime.after(startDateTime) && currentDate.before(endDateTime)) {
                //当前时间大于券开始时间(*天后到期)
                int days = (int) ((endDate.getTime() - currentDate.getTime()) / (1000 * 3600 * 24));
                switch (days) {
                    case 0:
                        describe = "今日到期";
                        break;
                    case 1:
                        describe = "明日到期";
                        break;
                    case 2:
                        describe = "后天到期";
                        break;
                    case 3:
                        describe = "3天后到期";
                        break;
                    case 4:
                        describe = "4天后到期";
                        break;
                    case 5:
                        describe = "5天后到期";
                        break;
                    case 6:
                        describe = "6天后到期";
                        break;
                    case 7:
                        describe = "7天后到期";
                        break;
                    default:
                        describe = DateUtil.convert2String(endDate, DateUtil.FORMAT_yyyyMMdd_date).replace("-", ".") + "到期";
                        break;
                }
            }
        }
        return describe;
    }

    public AddWeixinCardJudgeRequestDto convert2AddWeixinCardJudgeRequestDto(List<GetMemberCouponListResponseDto.Result.MemberCoupon> couponList, String partnerId, String unionId) {
        AddWeixinCardJudgeRequestDto requestDto = new AddWeixinCardJudgeRequestDto();
        requestDto.setPartnerId(partnerId);
        requestDto.setUnionid(unionId);
        List<AddWeixinCardJudgeRequestDto.MemberCoupon> memberCoupons = Lists.newArrayList();
        couponList.forEach(coupon -> {
            AddWeixinCardJudgeRequestDto.MemberCoupon memberCoupon = new AddWeixinCardJudgeRequestDto.MemberCoupon();
            memberCoupon.setStatus(coupon.getStatus());
            memberCoupon.setActivityCode(coupon.getActivityCode());
            memberCoupon.setCouponCode(coupon.getCouponCode());
            memberCoupons.add(memberCoupon);
        });
        requestDto.setMemberCouponList(memberCoupons);
        return requestDto;
    }

    private static Object formatAmount(Double amount) {
        if (amount % (amount.intValue()) == 0.0) {
            return amount.intValue();
        } else {
            return amount;
        }
    }

    public String getDescribe(String desc) {
        if (desc.contains("\n")) {
            String[] arrayStr = desc.split("\n");
            StringBuilder sb = getStyleString(arrayStr);
            desc = sb.toString();
        } else if (desc.contains("\r\n")) {
            String[] arrayStr = desc.split("\r\n");
            StringBuilder sb = getStyleString(arrayStr);
            desc = sb.toString();
        }
        return desc;
    }

    private StringBuilder getStyleString(String[] arrayStr) {
        StringBuilder sb = new StringBuilder();
        sb.append("<ul>");
        for (String str : arrayStr) {
            sb.append("<li>");
            sb.append(str);
            sb.append("</li>");
        }
        sb.append("</ul>");
        return sb;
    }

    public String getDescribeText(String desc) {
        if (StringUtils.isBlank(desc)) {
            return "";
        }
        if (desc.contains("\n")) {
            String[] arrayStr = desc.split("\n");
            StringBuilder sb = getStyleStringText(arrayStr);
            desc = sb.toString();
        } else if (desc.contains("\r\n")) {
            String[] arrayStr = desc.split("\r\n");
            StringBuilder sb = getStyleStringText(arrayStr);
            desc = sb.toString();
        }
        return desc;
    }

    private StringBuilder getStyleStringText(String[] arrayStr) {
        StringBuilder sb = new StringBuilder();
        for (String str : arrayStr) {
            sb.append("<p>");
            sb.append(str);
            sb.append("</p>");
        }
        return sb;
    }

    public AddWeixinCardCodeRequestDto convert2AddWeixinCardCodeRequestDto(String partnerId, String appid, List<EnterShopActivityResponseVo.CouponInfo> coupons) {
        AddWeixinCardCodeRequestDto addWeixinCardCodeRequestDto = new AddWeixinCardCodeRequestDto();
        addWeixinCardCodeRequestDto.setPartnerId(partnerId);
        addWeixinCardCodeRequestDto.setWxAppid(appid);
        List<AddWeixinCardCodeRequestDto.WeixinCardCodeAdd> weixinCardCodeAddsList = Lists.newArrayList();
        coupons.forEach(couponse -> {
            AddWeixinCardCodeRequestDto.WeixinCardCodeAdd cardCodeAdd = new AddWeixinCardCodeRequestDto.WeixinCardCodeAdd();
            cardCodeAdd.setActivityCode(couponse.getActivityCode());
            cardCodeAdd.setCouponCode(couponse.getCouponCode());
            weixinCardCodeAddsList.add(cardCodeAdd);
        });
        addWeixinCardCodeRequestDto.setWeixinCardCodeAddsList(weixinCardCodeAddsList);
        return addWeixinCardCodeRequestDto;
    }

    public List<AddWeixinCardCodeResponseDto.WeixinCardCodeList> convert2AddWeixinCardListRequest(AddWeixinCardCodeResponseDto weixinRequestDto) {
        List<AddWeixinCardCodeResponseDto.WeixinCardCodeList> list = Lists.newArrayList();
        AddWeixinCardCodeResponseDto.ResultBean result = weixinRequestDto.getResult();
        if (result != null) {
            list = result.getWeixinCardCodeListList();
        }
        return list;
    }

    public CouponPromotionDto getCouponPromotionDto(OrderBeanRequest orderBeanRequest, String couponCode, String activityCode, Integer flg) {
        CouponPromotionDto couponPromotionDto = new CouponPromotionDto();
        couponPromotionDto.setPartnerId(orderBeanRequest.getCompanyId());
        couponPromotionDto.setUserId(orderBeanRequest.getUserId());
        couponPromotionDto.setStoreId(orderBeanRequest.getShopId());
        couponPromotionDto.setCouponCode(couponCode);
        couponPromotionDto.setActivityCode(activityCode);
        couponPromotionDto.setOrderType(orderBeanRequest.getOrderType());
        couponPromotionDto.setFlg(flg);
        return couponPromotionDto;
    }

    public MCCafeCouponRequest convert2MCCafeCouponRequest(QueryOrdersResponse.DataBean.OrderBean orderBean, CreateOrderAccountRequest accountBean) {
        List<MCCafeProductRedeemVo> products = new ArrayList<>();
        //商品券核销核销参数
        if (QueryOrderAccountType.PRODUCT_COUPON.equals(accountBean.getAccountType())) {
            for (int i = 0; i < orderBean.getProductList().size(); i++) {
                QueryOrdersResponse.DataBean.OrderBean.ProductBean productBean = orderBean.getProductList().get(i);
                String pid = org.apache.commons.lang3.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);
                        mcCafeProductRedeemVo.setKeyProductCode(productBean.getCustomerCode());
                        mcCafeProductRedeemVo.setCustomer_code(productBean.getCustomerCode());
                        mcCafeProductRedeemVo.setSeq(i + 1);
                        mcCafeProductRedeemVo.setConsume_num(productDiscount.getDiscountQty());
                        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.N");
        mcCafeCouponRequest.setBusiness_date(cn.freemud.base.util.DateUtil.convert2Str(new Date(), cn.freemud.base.util.DateUtil.FORMAT_yyyyMMdd));
        return mcCafeCouponRequest;
    }

    public MCCafeCouponRequest convert2MCCafeCouponRequest(QueryOrdersResponseDto.DataBean.OrderBean orderBean, QueryOrdersResponseDto.DataBean.OrderBean.AccountBean accountBean, McdNetBatchQueryResponse.Coupon coupon) {
        List<MCCafeProductRedeemVo> products = new ArrayList<>();
        //商品券核销核销参数
        if (QueryOrderAccountType.PRODUCT_COUPON.equals(orderAdapter.getQueryOrderAccountType(OldOrderAccountType.getByCode(accountBean.getType())))) {
            for (int i = 0; i < orderBean.getProductList().size(); i++) {
                QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productBean = orderBean.getProductList().get(i);
                String pid = org.apache.commons.lang3.StringUtils.isNotBlank(productBean.getSpecification()) ? productBean.getSpecification() : productBean.getProductId();
                if (!org.springframework.util.CollectionUtils.isEmpty(productBean.getDiscountList())) {
                    List<QueryOrdersResponseDto.DataBean.OrderBean.ProductBean.ProductDiscount> discounts = productBean.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;
                        }
                        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(orderAdapter.getQueryOrderAccountType(OldOrderAccountType.getByCode(accountBean.getType())))) {
            for (int i = 0; i < orderBean.getProductList().size(); i++) {
                QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productBean = orderBean.getProductList().get(i);
                String pid = org.apache.commons.lang3.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);
            }
        } else if (QueryOrderAccountType.FREIGHT_COUPON.equals(orderAdapter.getQueryOrderAccountType(OldOrderAccountType.getByCode(accountBean.getType())))) {
            if(null != coupon) {
                McdNetCouponProductRespDto mcdNetCouponProductRespDto = coupon.getCodeInfo().getProducts().get(0);
                MCCafeProductRedeemVo mcCafeProductRedeemVo = new MCCafeProductRedeemVo();
                mcCafeProductRedeemVo.setKeyProductCode(mcdNetCouponProductRespDto.getPid());
                mcCafeProductRedeemVo.setCustomer_code(mcdNetCouponProductRespDto.getPid());
                mcCafeProductRedeemVo.setConsume_num(mcdNetCouponProductRespDto.getNumber());
                mcCafeProductRedeemVo.setSeq(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(OrderSourceType.ALIPAY.getCode().equals(orderBean.getSource())?
                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.N");
        mcCafeCouponRequest.setBusiness_date(cn.freemud.base.util.DateUtil.convert2Str(new Date(), cn.freemud.base.util.DateUtil.FORMAT_yyyyMMdd));
        return mcCafeCouponRequest;
    }

    public MCCafeCouponLockRequest convert2MCCafeCouponLockRequest(QueryOrdersResponse.DataBean.OrderBean orderBean, CreateOrderAccountRequest 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;
    }

    public MCCafeCouponLockRequest convert2MCCafeCouponLockRequest(QueryOrdersResponseDto.DataBean.OrderBean orderBean, QueryOrdersResponseDto.DataBean.OrderBean.AccountBean accountBean) {
        MCCafeCouponLockRequest mcCafeCouponLockRequest = new MCCafeCouponLockRequest();
        mcCafeCouponLockRequest.setVer(Integer.valueOf(Version.VERSION_1));
        mcCafeCouponLockRequest.setReqType(CouponReqTypeEnum.LOCK.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;
    }
}
