/**
 * 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.dto.StoreDeliveryInfoDto;
import cn.freemud.entities.dto.UserDeliveryInfoDto;
import cn.freemud.entities.dto.delivery.WeixinDeliveryAddressDto;
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.ShoppingCartInfoRequestVo;
import cn.freemud.entities.vo.delivery.DeliveryAmountVo;
import cn.freemud.enums.BusinessTypeEnum;
import cn.freemud.enums.CouponFlag;
import cn.freemud.enums.OrderChannelType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.delivery.ThirdDeliveryServiceImpl;
import cn.freemud.service.thirdparty.ShoppingCartClient;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
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 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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class CheckMallOrder {

    @Autowired
    private ShoppingCartClient shoppingCartClient;
    @Autowired
    private ThirdDeliveryServiceImpl thirdDeliveryService;
    @Autowired
    private AssortmentCustomerInfoManager customerInfoManager;
    @Autowired
    private StoreCenterService storeCenterService;

    /**
     * 下单会员相关校验
     */
    public AssortmentCustomerInfoVo checkOrderByMember(CreateOrderVo createOrderVo) {
        // 通过sessionId查询缓存中会员id
        String sessionId = createOrderVo.getSessionId();
        AssortmentCustomerInfoVo userLoginInfoDto = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (userLoginInfoDto == null || StringUtils.isEmpty(userLoginInfoDto.getMemberId())) {
            throw new ServiceException(ResponseResult.NOT_LOGIN);
        }
        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 void checkOrderByDelivery(CreateOrderVo createOrderVo, AssortmentCustomerInfoVo userLoginInfoDto,
                                         StoreResponse.BizVO storeResponseDto,Long totalAmount, String trackingNo) {
        StoreDeliveryInfoDto storeDeliveryInfoDto = this.getStoreDeliveryInfo(storeResponseDto, userLoginInfoDto.getWxAppId());
        //订单金额小于起送费提示
        if (storeDeliveryInfoDto.getDeliveryLimitAmount() > totalAmount) {
            throw new ServiceException(ResponseResult.STORE_DISCONTENT_DELIVERY_FEE);
        }
        storeDeliveryInfoDto.setEnableTakeaway(true);
        this.checkReceiveAddress(storeDeliveryInfoDto, createOrderVo);
    }

    public ShoppingCartGoodsDto getShoppingCartGoodsDto(CreateOrderVo createOrderVo) {
        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())
                .channelType(OrderChannelType.SAASMALL.getCode())
                .menuType(BusinessTypeEnum.SAAS_MALL.getName())
                .build();
        // 通过购物车获取优惠信息
        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())) {
            throw new ServiceException(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 StoreDeliveryInfoDto getStoreDeliveryInfo(StoreResponse.BizVO storeResponseDto, String wxAppid) {
        StoreDeliveryInfoDto storeDeliveryInfoDto = new StoreDeliveryInfoDto();
        storeDeliveryInfoDto.setPartnerId(storeResponseDto.getPartnerId());
        storeDeliveryInfoDto.setStoreId(storeResponseDto.getStoreCode());
        storeDeliveryInfoDto.setStoreName(storeResponseDto.getStoreName());

        storeDeliveryInfoDto.setDeliveryLimitAmount(0L);
        storeDeliveryInfoDto.setDeliveryAmount(0L);
        storeDeliveryInfoDto.setDefaultDeliveryRange(0L);
        storeDeliveryInfoDto.setAddRangeAmount(0L);
        storeDeliveryInfoDto.setAddRangeCount(0L);
        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);
        }
        storeDeliveryInfoDto.setDeliveryType("third");
        storeDeliveryInfoDto.setPushOrderTime(0);
        return storeDeliveryInfoDto;
    }

    /**
     * 校验收货地址是否可配送
     */
    public void checkReceiveAddress(StoreDeliveryInfoDto storeDeliveryInfoDto, CreateOrderVo createOrderVo) {
        WeixinDeliveryAddressDto weixinDeliveryAddress = createOrderVo.getWeixinDeliveryAddress();
        if(weixinDeliveryAddress == null || StringUtils.isEmpty(weixinDeliveryAddress.getProvinceName())) {
            throw new ServiceException(ResponseResult.DELIVERY_INFO_ERROR);
        }
        cn.freemud.base.entity.BaseResponse<DeliveryAmountVo> deliveryAmountVoBaseResponse = thirdDeliveryService.queryDeliveryAmount(createOrderVo.getWeixinDeliveryAddress());
        if(deliveryAmountVoBaseResponse == null || !ResponseResult.SUCCESS.getCode().equals(deliveryAmountVoBaseResponse.getCode())) {
            throw new ServiceException(ResponseResult.DELIVERY_INFO_NOT_DELIVERY);
        }
        DeliveryAmountVo deliveryAmountVo = deliveryAmountVoBaseResponse.getResult();
        UserDeliveryInfoDto userDeliveryInfoDto = UserDeliveryInfoDto.builder()
                .deliveryLimitAmount(storeDeliveryInfoDto.getDeliveryLimitAmount())
                .userEnableTakeaway(true)
                .realDeliveryAmount(deliveryAmountVo.getDeliveryAmount().longValue())
                .storeId(storeDeliveryInfoDto.getStoreId())
                .storeName(storeDeliveryInfoDto.getStoreName())
                .receiveMobile(weixinDeliveryAddress.getTelNumber())
                .receiveUserName(weixinDeliveryAddress.getUserName())
                .receiveProvince(weixinDeliveryAddress.getProvinceName())
                .receiveCity(weixinDeliveryAddress.getCityName())
                .receiveRegion(weixinDeliveryAddress.getCountyName())
                .receiveAddress(weixinDeliveryAddress.getDetailInfo())
                .storeDeliveryInfoDto(storeDeliveryInfoDto).build();
        createOrderVo.setUserDeliveryInfoDto(userDeliveryInfoDto);
    }

}
