/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: CheckOrder
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: ping.wu
 * @date: 2019/5/8 10:01
 * @version V1.0
 * @Copyright: 2019 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.service.impl;

import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.constant.StoreConstant;
import cn.freemud.entities.db.OpenPlatformIappWxappConfig;
import cn.freemud.entities.db.OpenPlatformPartnerStoreDeliveryConfig;
import cn.freemud.entities.db.StoreTableNumber;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.shoppingCart.GetShoppingCartGoodsApportionDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.GetMemberCouponRequestVo;
import cn.freemud.entities.vo.ShoppingCartInfoRequestVo;
import cn.freemud.enums.CouponFlag;
import cn.freemud.enums.CreateOrderType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.manager.OpenPlatformIappWxappConfigManager;
import cn.freemud.manager.OpenPlatformPartnerStoreDeliveryConfigManager;
import cn.freemud.manager.StoreTableNumberManager;
import cn.freemud.service.CouponService;
import cn.freemud.service.thirdparty.ShoppingCartClient;
import cn.freemud.service.thirdparty.StockClient;
import cn.freemud.utils.LogUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.application.sdk.api.base.BaseResponse;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.membercenter.request.QueryReceiveAddressRequest;
import com.freemud.application.sdk.api.membercenter.request.StatisticalPropertyRequest;
import com.freemud.application.sdk.api.membercenter.response.GetSvcInfoByMemberIdResponse;
import com.freemud.application.sdk.api.membercenter.response.QueryReceiveAddressResponse;
import com.freemud.application.sdk.api.membercenter.service.MemberCenterService;
import com.freemud.application.sdk.api.membercenter.service.MemberPropertyService;
import com.freemud.application.sdk.api.storecenter.request.StoreInfoRequest;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.awt.geom.Point2D;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class CheckOrder {

    @Autowired
    private StoreTableNumberManager storeTableNumberManager;
    @Autowired
    private OpenPlatformIappWxappConfigManager openPlatformIappWxappConfigManager;
    @Autowired
    private OpenPlatformPartnerStoreDeliveryConfigManager deliveryConfigManager;
    // 缓存取用户数据用
//    @Autowired
//    private UserServiceImpl userService;
    @Autowired
    private AssortmentCustomerInfoManager customerInfoManager;
    //门店SDK
    @Autowired
    private StoreCenterService storeCenterService;
    //会员SDK
    @Autowired
    private MemberCenterService memberCenterService;
    //会员SDK
    @Autowired
    private MemberPropertyService memberPropertyService;
    @Autowired
    private ShoppingCartClient shoppingCartClient;
//    @Autowired
//    private OrderAdapter orderAdapter;
    @Autowired
    private StoreServiceImpl storeService;
    @Autowired
    private StockClient stockClient;
    @Autowired
    private ItemServiceImpl itemService;
    @Autowired
    private CouponService couponService;
    private static Gson gson = new Gson();
    /**
     * 下单会员相关校验
     */
    public AssortmentCustomerInfoVo checkOrderByMember(CreateOrderVo createOrderVo, String trackingNo) {
        // 通过sessionId查询缓存中会员id
        String sessionId = createOrderVo.getSessionId();
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }
        //校验会员svc卡信息
        checkCardCode(createOrderVo.getPartnerId(),userLoginInfoDto.getMemberId(),createOrderVo.getCardCode(),trackingNo);

        createOrderVo.setUserId(userLoginInfoDto.getMemberId());
        return userLoginInfoDto;
    }


    /**
     * 查询门店信息
     */
    public StoreResponse getStoreInfo(String partnerId, String shopId, String trackingNo) {
        // 获取门店信息
        StoreInfoRequest storeInfoRequest = new StoreInfoRequest(partnerId, shopId,null);
        return storeCenterService.getStoreInfo(storeInfoRequest, trackingNo);
    }

    /**
     * 下单门店相关校验
     */
    public StoreResponse.BizVO checkOrderByStore(CreateOrderVo createOrderVo, String trackingNo) {
        String partnerId = createOrderVo.getPartnerId();
        String shopId = createOrderVo.getShopId();

        // 获取门店信息
        StoreResponse storeResponse = getStoreInfo(partnerId, shopId, trackingNo);
        if (storeResponse == null || storeResponse.getBizVO() == null) {
            throw new ServiceException(ResponseResult.STORE_NOT_FOUND);
        }
        StoreResponse.BizVO storeResponseDto = storeResponse.getBizVO();
        // 校验门店是否停业 1 营业 2 停业 3 繁忙置休
        if (storeResponseDto.getActiveFlag() == null || storeResponseDto.getActiveFlag() != 1) {
            throw new ServiceException(ResponseResult.STORE_ITEM_STOP_BUSINESS);
        }
        if (!StoreConstant.BUSINESS.equals(storeResponseDto.getState())) {
            throw new ServiceException(ResponseResult.STORE_ITEM_CHECK_CLOSE);
        }
        //设置营业开始和结束时间
        String businessHourStr = storeResponseDto.getBusinessHoursDay().replace("-", ",").replace("_", ",");
        String[] businessHours = businessHourStr.split(",");
        if (businessHours.length != 2) {
            throw new ServiceException(ResponseResult.STORE_NOT_FOUND);
        }
        Date date = new Date();
        String startDateTimeStr = DateUtil.convert2String(date, DateUtil.FORMAT_YMD) + " " + businessHours[0] + ":00";
        Date startDateTime = DateUtil.convert2Date(startDateTimeStr, DateUtil.FORMAT_YYYY_MM_DD_HHMMSS);
        String endDateTimeStr = DateUtil.convert2String(date, DateUtil.FORMAT_YMD) + " " + businessHours[1] + ":00";
        SimpleDateFormat hhmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date endDateTime;
        try {
            endDateTime = hhmmss.parse(endDateTimeStr);
        } catch (ParseException e) {
            throw new ServiceException(ResponseResult.STORE_BUSINESS_HOUR_ERROR);
        }
        storeResponseDto.setBusinessHoursDayStartTime(startDateTime);
        storeResponseDto.setBusinessHoursDayEndTime(endDateTime);

        // 校验门店是否打烊，打烊了则不让操作
        if (storeResponseDto.getBusinessHoursDayStartTime() == null
                || storeResponseDto.getBusinessHoursDayEndTime() == null) {
            throw new ServiceException(ResponseResult.STORE_ITEM_STOP_BUSINESS);
        }

        // 桌号不为空，查数据库重新设置桌号
        /*if (StringUtils.isNotBlank(createOrderVo.getTableNumber())) {
            createOrderVo.setTableNumber(getTableNumber(partnerId, shopId, createOrderVo.getTableNumber()));
        }*/
        createOrderVo.setStoreName(storeResponseDto.getStoreName());
        createOrderVo.setStoreAddress(storeResponseDto.getAddress());
        createOrderVo.setThirdShopId(storeResponseDto.getThirdPartCode());
        return storeResponseDto;
    }

    /**
     * 下单订单类型校验
     */
    public Integer checkOrderByOrderType(CreateOrderVo createOrderVo, AssortmentCustomerInfoVo userLoginInfoDto,
                                         StoreResponse.BizVO storeResponseDto,Long totalAmount, String trackingNo) {
        Integer pushOrderTime = 0;
        //TODO 设置预约时间
        Date takeMealDateTime = null;
        Date date = new Date();
        if (StringUtils.isNotBlank(createOrderVo.getTakeMealTime())) {
            StringBuffer takeMealTime = new StringBuffer("");
            takeMealTime = takeMealTime.append(DateUtil.convert2String(date, "yyyy-MM-dd"))
                    .append(" ").append(createOrderVo.getTakeMealTime()).append(":00");
            takeMealDateTime = DateUtil.convert2Date(takeMealTime.toString(), "yyyy-MM-dd HH:mm:ss");
        }
        String appId = userLoginInfoDto.getWxAppId();
        // 校验小程序是否支持到店或者外卖
        OpenPlatformIappWxappConfig config = openPlatformIappWxappConfigManager.selectIappWxappConfigByWxAppId(appId);
        // 自提校验
        if (CreateOrderType.COLLECT_GOODS.getCode().equals(createOrderVo.getOrderType())) {
            if (config == null || config.getTakeInside() == null || config.getTakeInside() != 1) {
                throw new ServiceException(ResponseResult.ORDER_WXAPP_NOT_ENABLE_COLLECT_GOODS);
            }
            if (storeResponseDto.getIsSelfMention() == null || storeResponseDto.getIsSelfMention() != 1) {
                throw new ServiceException(ResponseResult.STORE_NOT_ENABLE_COLLECT_GOODS);
            }

            //有预约时间，预约时间要在营业时间范围内
            if (takeMealDateTime != null && (takeMealDateTime.before(storeResponseDto.getBusinessHoursDayStartTime())
                    || takeMealDateTime.after(storeResponseDto.getBusinessHoursDayEndTime()))) {
                throw new ServiceException(ResponseResult.ORDER_TAKEMEALTIME_INVAILD);
            }
            createOrderVo.setUserName(userLoginInfoDto.getNickName());
            createOrderVo.setMobile(userLoginInfoDto.getMobile());
        }
        // 校验外卖信息
        if (CreateOrderType.TAKE_OUT.getCode().equals(createOrderVo.getOrderType())) {
            if (config == null || config.getTakeaway() == null || config.getTakeaway() == 0) {
                throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
            }
            if (storeResponseDto.getDelivery() == null || storeResponseDto.getDelivery() == 2) {
                throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
            }
            if (StringUtils.isBlank(storeResponseDto.getDeliveryHoursDay())) {
                throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
            }
            //获取门店配送信息
            StoreDeliveryInfoDto storeDeliveryInfoDto = getStoreDeliveryInfo(storeResponseDto, config, appId);
            //订单金额小于起送费提示
            if (storeDeliveryInfoDto.getDeliveryLimitAmount() > totalAmount) {
                throw new ServiceException(ResponseResult.STORE_DISCONTENT_DELIVERY_FEE);
            }
            String deliveryStr = storeResponseDto.getDeliveryHoursDay().replace("-", ",")
                    .replace("_", ",");
            String[] deliverys = deliveryStr.split(",");
            Date startDate = null;
            Date endDate = null;
            if (deliverys.length == 2) {
                SimpleDateFormat hhmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyy-MM-dd");
                String startDateTimeStr = yyyyMMdd.format(date) + " " + deliverys[0] + ":00";
                String endDateTimeStr = yyyyMMdd.format(date) + " " + deliverys[1] + ":00";
                try {
                    endDate = hhmmss.parse(endDateTimeStr);
                    startDate = hhmmss.parse(startDateTimeStr);
                    storeDeliveryInfoDto.setDeliveryStartTime(hhmmss.parse(startDateTimeStr));
                    storeDeliveryInfoDto.setDeliveryEndTime(hhmmss.parse(endDateTimeStr));
                } catch (ParseException e) {
                    LogUtil.error("getStoreDeliveryInfo_error", endDateTimeStr, e.getMessage());
                }
            }
            if (startDate == null || endDate == null || date.after(endDate)) {
                throw new ServiceException(ResponseResult.ORDER_CREATE_TIME_NOT_DELIVERY);
            }
            if (StringUtils.isNotBlank(createOrderVo.getTakeMealTime())) {
                storeDeliveryInfoDto.setPushOrderTime(30);
            }
            // 校验预约配送时间
            if (StringUtils.isBlank(createOrderVo.getTakeMealTime()) && date.before(startDate)) {
                long takeAwayTime = startDate.getTime() + storeResponseDto.getServiceTime() * 60 * 1000L;
                takeMealDateTime = new Date(takeAwayTime);
                createOrderVo.setTakeMealTime(DateUtil.convert2Str(takeMealDateTime, "HH:mm"));
            }
            if (takeMealDateTime != null && (takeMealDateTime.before(startDate) || takeMealDateTime.after(endDate))) {
                throw new ServiceException(ResponseResult.ORDER_CREATE_TIME_NOT_DELIVERY);
            }
            storeDeliveryInfoDto.setEnableTakeaway(true);
            // 校验收货地址是否可配送
            checkReceiveAddress(storeDeliveryInfoDto, createOrderVo);
            pushOrderTime = storeDeliveryInfoDto.getPushOrderTime();
        }
        //非到店或者外卖，类型错误
        if (!(CreateOrderType.COLLECT_GOODS.getCode().equals(createOrderVo.getOrderType()) ||
                CreateOrderType.TAKE_OUT.getCode().equals(createOrderVo.getOrderType()))) {
            throw new ServiceException(ResponseResult.PARAMETER_MISSING);
        }
        return pushOrderTime;
    }

    public List<String> getStockProductIdList(CreateOrderVo createOrderVo, ShoppingCartGoodsDto shoppingCartGoodsDto) {
        List<String> stockProductIds = Lists.newArrayList();
        GetProductStockResponseDto stockResponseDto = checkProductStock(shoppingCartGoodsDto, createOrderVo.getPartnerId(), createOrderVo.getShopId());
        if (!ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(stockResponseDto.getCode())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE);
        }
        if (CollectionUtils.isNotEmpty(stockResponseDto.getResult())) {
            stockProductIds = stockResponseDto.getResult().stream().map(p -> p.getPid().toString()).collect(Collectors.toList());
            LogUtil.debug("stockProductIds", gson.toJson(stockProductIds), null);
        }
        return stockProductIds;
    }

    public ShoppingCartGoodsDto getShoppingCartGoodsDto(CreateOrderVo createOrderVo) {
        ShoppingCartInfoRequestVo.BuyMemberCard buyMemberCard = null;
        if (createOrderVo.getBuyMemberCard() != null) {
            buyMemberCard = new ShoppingCartInfoRequestVo.BuyMemberCard();
            buyMemberCard.setPaidId(createOrderVo.getBuyMemberCard().getPaidId());
            buyMemberCard.setRuleId(createOrderVo.getBuyMemberCard().getRuleId());
        }
        ShoppingCartInfoRequestVo shoppingCartInfoRequestVo = ShoppingCartInfoRequestVo.builder()
                .partnerId(createOrderVo.getPartnerId())
                .shopId(createOrderVo.getShopId())
                .version(createOrderVo.getVersion())
                .sessionId(createOrderVo.getSessionId())
                .orderType(createOrderVo.getOrderType())
                .reachStoreType(createOrderVo.getReachStoreType())
                .flag(CouponFlag.NO.getCode())
                .useCustomerScore(createOrderVo.getUseCustomerScore())
                .buyMemberCard(buyMemberCard)
                .build();
        // 如果使用优惠券或者商品券，校验 couponCode
        if (StringUtils.isNotBlank(createOrderVo.getCouponCode())) {
            // 校验couponCode
            GetCouponDetailResponseDto getCouponDetailResponseDto = couponService.getMemberCoupon(GetMemberCouponRequestVo.builder()
                    .partnerId(createOrderVo.getPartnerId())
                    .couponCode(createOrderVo.getCouponCode()).build());
            if (Objects.equals(getCouponDetailResponseDto, null) || CollectionUtils.isEmpty(getCouponDetailResponseDto.getDetails())
                    || getCouponDetailResponseDto.getDetails().get(0).getActive() == null
                    || getCouponDetailResponseDto.getDetails().get(0).getActive().getActiveCode() == null) {
                    if ((CollectionUtils.isNotEmpty(getCouponDetailResponseDto.getDetails().get(0).getActiveRestrictionVOS())
                            && CollectionUtils.isEmpty(getCouponDetailResponseDto.getDetails().get(0).getActiveRestrictionVOS().stream()
                            .filter(a -> Objects.equals(a.getStoreIdPartner(), createOrderVo.getShopId())).collect(Collectors.toList()))
                    )) {
                        throw new ServiceException(ResponseResult.COUPON_SHOP_NOTSUPPORT);
                    } else {
                        throw new ServiceException(ResponseResult.COUPON_GETINFO_INVAILD);
                    }
            }
            String activeCode = getCouponDetailResponseDto.getDetails().get(0).getActive().getActiveCode();
            // 校验点餐方式,查询购物车接口内部已校验
            shoppingCartInfoRequestVo.setCouponCode(createOrderVo.getCouponCode());
            // 活动code
            shoppingCartInfoRequestVo.setActivityCode(activeCode);
            shoppingCartInfoRequestVo.setCardCode(createOrderVo.getCardCode());
        }
        // 通过购物车获取优惠信息
        GetShoppingCartGoodsApportionDto requestDto = new GetShoppingCartGoodsApportionDto();
        requestDto.setShoppingCartInfoRequestVo(shoppingCartInfoRequestVo);
        //加价购商品 校验放购物车校验
        requestDto.setPremiumExchangeActivity(createOrderVo.getPremiumExchangeActivity());
        cn.freemud.base.entity.BaseResponse<ShoppingCartGoodsDto> apportionResponse = shoppingCartClient.getShoppingCartGoodsApportionNew(requestDto);
        if (!ObjectUtils.equals(ResponseCodeConstant.RESPONSE_SUCCESS_STR, apportionResponse.getCode())) {
            ResponseResult responseResult = ResponseResult.getResponseResult(apportionResponse.getCode());
            throw new ServiceException(responseResult != null ? responseResult : ResponseResult.SHOPPING_CART_GETINFO_ERROR );
        }
        if (apportionResponse.getResult() == null || CollectionUtils.isEmpty(apportionResponse.getResult().getProducts())) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_GETINFO_INVAILD);
        }
        ShoppingCartGoodsDto shoppingCartGoodsDto = apportionResponse.getResult();
        if (shoppingCartGoodsDto.getOriginalTotalAmount() == null) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_GETINFO_INVAILD);
        }
        return shoppingCartGoodsDto;
    }

    /**
     * 获取桌号
     */
    public String getTableNumber(String partnerId, String shopId, String tableNumber) {
        StoreTableNumber storeTableNumber = storeTableNumberManager.selectOne(partnerId, shopId, tableNumber);
        if (storeTableNumber == null) {
            return "";
        }
        return tableNumber;
    }

    /**
     * 获取门店配送信息
     */
    public StoreDeliveryInfoDto getStoreDeliveryInfo(StoreResponse.BizVO storeResponseDto,
                                                     OpenPlatformIappWxappConfig openPlatformIappWxappConfig, String wxAppid) {
        StoreDeliveryInfoDto storeDeliveryInfoDto = new StoreDeliveryInfoDto();
        storeDeliveryInfoDto.setPartnerId(storeResponseDto.getPartnerId());
        storeDeliveryInfoDto.setStoreId(storeResponseDto.getStoreCode());
        storeDeliveryInfoDto.setStoreName(storeResponseDto.getStoreName());
        // 查询外卖配送信息
        OpenPlatformPartnerStoreDeliveryConfig deliveryConfig = deliveryConfigManager.findByPartnerIdAndStoreCode(storeResponseDto.getPartnerId(),
                storeResponseDto.getStoreCode());
        if (deliveryConfig == null) {
            throw new ServiceException(ResponseResult.STORE_ITEM_NOT_DELIVERY);
        }
        // 判断门店是否启用外卖，只有当小程序开通外卖，且门店开通外卖,设置 外卖配送时间 才开启外卖功能
        storeDeliveryInfoDto.setDeliveryLimitAmount(deliveryConfig == null ? 0 : deliveryConfig.getDeliveryLimitAmount());
        storeDeliveryInfoDto.setDeliveryAmount(deliveryConfig == null ? 0 : deliveryConfig.getDeliveryAmount());
        storeDeliveryInfoDto.setDefaultDeliveryRange(deliveryConfig == null ? 0L : deliveryConfig.getDefaultDeliveryRange());
        storeDeliveryInfoDto.setAddRangeAmount(deliveryConfig == null ? 0L : deliveryConfig.getAddRangeAmount());
        storeDeliveryInfoDto.setAddRangeCount(deliveryConfig == null ? 0L : deliveryConfig.getAddRangeCount());
        storeDeliveryInfoDto.setPoint2DList(getDeliveryPoint2DList(storeResponseDto.getDistributionScope()));
        storeDeliveryInfoDto.setDeliveryHoursDay(storeResponseDto.getDeliveryHoursDay());
        storeDeliveryInfoDto.setLongitude(storeResponseDto.getLongitude());
        storeDeliveryInfoDto.setLatitude(storeResponseDto.getLatitude());
        storeDeliveryInfoDto.setScopeConfig(storeResponseDto.getScopeConfig());
        if (StringUtils.isNotEmpty(storeResponseDto.getDeliveryRadius())) {
            storeDeliveryInfoDto.setDeliveryRadius(Integer.valueOf(storeResponseDto.getDeliveryRadius()));
        } else {
            storeDeliveryInfoDto.setDeliveryRadius(0);
        }
        // 只有小程序设置了外卖，并且开通了第三方配送账户，才是第三方配送单
        if (openPlatformIappWxappConfig == null) {
            openPlatformIappWxappConfig = openPlatformIappWxappConfigManager.selectIappWxappConfigByWxAppId(wxAppid);
        }
        if (openPlatformIappWxappConfig == null) {
            storeDeliveryInfoDto.setDeliveryType("self");
            storeDeliveryInfoDto.setPushOrderTime(0);
        } else {
            if (ObjectUtils.equals(openPlatformIappWxappConfig.getTakeType(), 1)) {
                storeDeliveryInfoDto.setDeliveryType("self");
                storeDeliveryInfoDto.setPushOrderTime(0);
            } else {
                storeDeliveryInfoDto.setDeliveryType("third");
                storeDeliveryInfoDto.setPushOrderTime(0);
            }
        }
        return storeDeliveryInfoDto;
    }

    /**
     * 获取配送范围内集合
     */
    public List<Point2D.Double> getDeliveryPoint2DList(String distributionScope) {
        if (StringUtils.isBlank(distributionScope)) {
            return Collections.emptyList();
        }
        /**
         * 如果点不为整数，返回空
         */
        String[] points = distributionScope.split(",");
        if (points.length % 2 != 0) {
            return Collections.emptyList();
        }
        List<String> pointList = Arrays.asList(points);
        List<Point2D.Double> point2DList = Lists.newArrayList();
        for (int i = 0; i < pointList.size(); i++) {
            Double pointX = Double.parseDouble(pointList.get(i));
            Double pointY = Double.parseDouble(pointList.get(++i));
            point2DList.add(new Point2D.Double(pointX, pointY));
        }
        return point2DList;
    }

    /**
     * 校验收货地址是否可配送
     */
    public void checkReceiveAddress(StoreDeliveryInfoDto storeDeliveryInfoDto, CreateOrderVo createOrderVo) {
        //校验收货地址是否可配送
        String receiveId = createOrderVo.getReceiveId();
        String trackingNo = LogThreadLocal.getTrackingNo();
        QueryReceiveAddressRequest request = new QueryReceiveAddressRequest(receiveId, storeDeliveryInfoDto.getPartnerId());
        BaseResponse<QueryReceiveAddressResponse> queryReceiveAddressResponse = memberCenterService.queryReceiveAddressById(request, trackingNo);
        if (!ResponseResult.SUCCESS.getCode().equals(queryReceiveAddressResponse.getCode()) || queryReceiveAddressResponse.getData() == null) {
            throw new ServiceException(ResponseResult.USER_GETRECEIVEADDRESS_ERROR);
        }
        QueryReceiveAddressResponse receiveAddressResult = queryReceiveAddressResponse.getData();
        UserDeliveryInfoDto userDeliveryInfoDto = storeService.getUserDeliveryInfo(storeDeliveryInfoDto, receiveAddressResult.getLongitude(),
                receiveAddressResult.getLatitude());
        if (!userDeliveryInfoDto.getUserEnableTakeaway()) {
            throw new ServiceException(ResponseResult.ORDER_TAKE_OUT_ADDRESS_NOT_DELIVERY);
        }
        userDeliveryInfoDto.setReceiveUserName(receiveAddressResult.getReceiveName());
        userDeliveryInfoDto.setReceiveMobile(StringUtils.isEmpty(receiveAddressResult.getMobile()) ? receiveAddressResult.getReceiveMobile() : receiveAddressResult.getMobile());
        String receiveAddress = receiveAddressResult.getReceiveAddress();
        if (StringUtils.isNotBlank(receiveAddress)) {
            userDeliveryInfoDto.setReceiveAddress(receiveAddress);
            if (receiveAddress.contains("officeName") && receiveAddress.contains("address")) {
                JSONObject jsonObject = JSONObject.parseObject(receiveAddress);
                userDeliveryInfoDto.setReceiveOfficeName(jsonObject.getString("officeName"));
                userDeliveryInfoDto.setReceiveAddress(jsonObject.getString("address"));
            }
        }

        createOrderVo.setUserName(receiveAddressResult.getReceiveName());
        createOrderVo.setMobile(StringUtils.isEmpty(receiveAddressResult.getMobile()) ? receiveAddressResult.getReceiveMobile() : receiveAddressResult.getMobile());
        createOrderVo.setUserDeliveryInfoDto(userDeliveryInfoDto);
    }

    public GetProductStockResponseDto checkProductStock(ShoppingCartGoodsDto shoppingCartGoodsDto, String partnerId, String storeId) {
        List<Long> skuIds = new ArrayList<>();
        for (ShoppingCartGoodsDto.CartGoodsDetailDto goodsDetailDto : shoppingCartGoodsDto.getProducts()) {
            //1.9.2兼容套餐商品改动  套餐类子集商品不校验库存
            if(StringUtils.isBlank(goodsDetailDto.getParentProductId())){
                skuIds.add(Long.parseLong(goodsDetailDto.getSkuId()));
            }
        }
        GetProductStockRequestDto requestDto = new GetProductStockRequestDto();
        requestDto.setChannel("saas");
        requestDto.setPartnerId(partnerId);
        requestDto.setStoreId(storeId);
        requestDto.setProductIds(skuIds);
        // TODO: 2019/5/13 SDK无该方法,暂不修改
        GetProductStockResponseDto stocks = stockClient.getAvailableStocks(requestDto);
        LogUtil.debug("checkProductStock_end", gson.toJson(requestDto), gson.toJson(stocks));
        if (stocks == null) {
            throw new ServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE);
        }
        if (ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(stocks.getCode())
                && CollectionUtils.isNotEmpty(stocks.getResult())) {
            String msg = "";
            for (GetProductStockResponseDto.DataBean stock : stocks.getResult()) {
                for (ShoppingCartGoodsDto.CartGoodsDetailDto goodsDetailDto : shoppingCartGoodsDto.getProducts()) {
                    //1.9.2兼容套餐商品改动  套餐类子集商品不校验库存
                    if(StringUtils.isBlank(goodsDetailDto.getParentProductId())) continue;
                    //累计买一赠一商品
                    List<ShoppingCartGoodsDto.CartGoodsDetailDto> products = shoppingCartGoodsDto.getProducts().stream().filter(p -> p.getSkuId().equals(goodsDetailDto.getSkuId())).collect(Collectors.toList());
                    Integer qty = 0;
                    if (CollectionUtils.isNotEmpty(products)) {
                        qty = products.stream().mapToInt(ShoppingCartGoodsDto.CartGoodsDetailDto::getQty).sum();
                    }
                    if (stock.getPid().toString().equals(goodsDetailDto.getSkuId())
                            && stock.getQty() < qty) {
                        msg += msg + goodsDetailDto.getSkuName();
                        break;
                    }
                }
            }
            if (!msg.isEmpty()) {
                throw new ServiceException(ResponseResult.SHOPPING_CART_STOCK_NOT_HAVE, msg + "库存不足");
            }
        }
        return stocks;
    }


    /**
     * 获取商品第三方商品编号
     *
     */
//    private CreateOrderDto getProductCustomerCode(CreateOrderDto createOrderDto) {
//        List<String> pids = new ArrayList<>();
//        for (cn.freemud.entities.dto.order.CreateOrderProductDto productDto : createOrderDto.getProducts()) {
//            pids.add(productDto.getSpecification());
//        }
//        Map<String, GetProductsVo> products = itemService.getProducts(pids, createOrderDto.getCompanyId(), createOrderDto.getShopId());
//        if (products.isEmpty()) {
//            return createOrderDto;
//        }
//        for (String pid : pids) {
//            for (cn.freemud.entities.dto.order.CreateOrderProductDto productDto : createOrderDto.getProducts()) {
//                if (pid.equals(productDto.getSpecification())) {
//                    if (products.get(pid) != null) {
//                        productDto.setCustomerCode(products.get(pid).getCustomerCode());
//                    } else {
//                        productDto.setCustomerCode("");
//                        LogUtil.info("getProducts_exception", JSONObject.toJSONString(pids), JSONObject.toJSONString(products));
//                    }
//                }
//            }
//        }
//        return createOrderDto;
//    }

    public void checkCardCode(String partnerId,String memberId,String cardCode,String trackingNo){
        if(StringUtils.isBlank(cardCode)){
            return;
        }
        StatisticalPropertyRequest request = new StatisticalPropertyRequest();
        request.setPartnerId(partnerId);
        request.setMemberId(memberId);
        BaseResponse<List<GetSvcInfoByMemberIdResponse>> responseDTO = memberPropertyService.getSvcInfoByMemberId(request,trackingNo);
        if (!ResponseResult.SUCCESS.getCode().equals(responseDTO.getCode()) || responseDTO.getData() == null
                || responseDTO.getData().size() == 0 ) {
            throw new ServiceException(ResponseResult.USER_SVC_CARD_ERROR);
        }
        //svc卡无效
        boolean b = true;
        for (GetSvcInfoByMemberIdResponse getSvcInfoByMemberIdResponse : responseDTO.getData()){
            if(cardCode.equals(getSvcInfoByMemberIdResponse.getCardCode()) && getSvcInfoByMemberIdResponse.getStatusFlag() == 0){
                b = false;
            }
        }
        if(b){
            throw new ServiceException(ResponseResult.USER_SVC_CARD_ERROR);
        }
    }

}
