package cn.freemud.service.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.StoreConstant;
import cn.freemud.entities.bo.CreateOrderBo;
import cn.freemud.entities.dto.StoreDeliveryInfoDto;
import cn.freemud.entities.dto.UserDeliveryInfoDto;
import cn.freemud.entities.dto.delivery.WeixinDeliveryAddressDto;
import cn.freemud.entities.dto.ecology.VirtualBindStoreResponse;
import cn.freemud.entities.dto.ecology.VirtualStoreRequest;
import cn.freemud.entities.dto.shoppingCart.GetShoppingCartGoodsApportionDto;
import cn.freemud.entities.dto.shoppingCart.ShoppingCartGoodsDto;
import cn.freemud.entities.vo.CreateOrderBaseVo;
import cn.freemud.entities.vo.ShoppingCartInfoRequestVo;
import cn.freemud.entities.vo.delivery.DeliveryAmountVo;
import cn.freemud.enums.OrderChannelType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.CheckOrderUniversal;
import cn.freemud.service.delivery.ThirdDeliveryServiceImpl;
import cn.freemud.service.thirdparty.EcologyAdminApplicationClient;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
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;

/**
 * @author : xh.Z
 * @email : fisherman0510@163.com
 * @Date : 2021/4/15 下午2:55
 * @description :
 */
@Component
public class CheckOrderSaasMall extends CheckOrderUniversal {

    @Autowired
    private EcologyAdminApplicationClient ecologyAdminApplicationClient;

    @Autowired
    private ThirdDeliveryServiceImpl thirdDeliveryService;

    /**
     * 钩子
     * 商城订单 不校验  会员svc卡信息
     *
     * @return
     */
    @Override
    protected boolean checkCardCode() {
        return false;
    }

    @Override
    protected OrderChannelType getChannelType() {
        return OrderChannelType.SAASMALL;
    }


    /**
     * 重新商城 门店的相关校验
     *
     * @param createOrderBo
     * @param trackingNo
     * @param isCheck           商城默认传递 false
     * @return
     */
    @Override
    protected StoreResponse.BizVO checkOrderByStore(CreateOrderBo createOrderBo, String trackingNo, boolean isCheck) {
        // 设置门店id为商城的虚拟门店id
        this.change2BindMallShopId(createOrderBo.getCreateOrderBaseVo(), createOrderBo.getUserLoginInfoDto().getWxAppId());

        StoreResponse.BizVO storeResponseDto = super.checkOrderByStore(createOrderBo, trackingNo, false);

        if (!StoreConstant.BUSINESS.equals(storeResponseDto.getState())) {
            throw new ServiceException(ResponseResult.STORE_ITEM_CHECK_CLOSE);
        }

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

        // 设置营业开始/结束时间
        this.setBeginAndEndTime(storeResponseDto);
        return storeResponseDto;
    }

    private void change2BindMallShopId(CreateOrderBaseVo createOrderBaseVo, String wxAppId) {
        VirtualStoreRequest virtualStoreRequest = new VirtualStoreRequest();
        virtualStoreRequest.setPlatformAppId(wxAppId);
        virtualStoreRequest.setType("microMall");
        BaseResponse<VirtualBindStoreResponse> virtualBindStoreResponse = ecologyAdminApplicationClient.getBuyBindVirtualStore(virtualStoreRequest);
        if (virtualBindStoreResponse == null || virtualBindStoreResponse.getResult() == null || StringUtils.isBlank(virtualBindStoreResponse.getResult().getStoreId())) {
            throw new ServiceException(ResponseResult.STORE_BIND_MALL_NOT_FOUND);
        }
        createOrderBaseVo.setShopId(virtualBindStoreResponse.getResult().getStoreId());
    }

    private void setBeginAndEndTime(StoreResponse.BizVO storeResponseDto) {
        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);
    }


    /**
     * 校验购物车优惠信息请求对象
     *
     * @param createOrderVo
     * @param shoppingCartInfoRequestVo
     * @return
     */
    @Override
    protected GetShoppingCartGoodsApportionDto getShoppingCartGoodsApportionDto(CreateOrderBaseVo createOrderVo, ShoppingCartInfoRequestVo shoppingCartInfoRequestVo) {
        GetShoppingCartGoodsApportionDto requestDto = new GetShoppingCartGoodsApportionDto();
        //设置用户选择的买一赠一商品信息
        requestDto.setShoppingCartInfoRequestVo(shoppingCartInfoRequestVo);
        //加价购商品 校验放购物车校验
        requestDto.setPremiumExchangeActivity(createOrderVo.getPremiumExchangeActivity());
        return requestDto;
    }

    /**
     *  业务场景 下单前通用校验
     * @param createOrderBo
     */
    @Override
    public void checkCustomCreateOrderParam(CreateOrderBo createOrderBo) {
        // 查询商城的配送模板信息，校验订单是否满足配送条件
        StoreResponse.BizVO storeResponseDto = createOrderBo.getStoreResponseDto();
        CreateOrderBaseVo createOrderBaseVo = createOrderBo.getCreateOrderBaseVo();
        AssortmentCustomerInfoVo userLoginInfoDto = createOrderBo.getUserLoginInfoDto();
        ShoppingCartGoodsDto shoppingCartGoodsDto = createOrderBo.getShoppingCartGoodsDto();
        String trackingNo = LogThreadLocal.getTrackingNo();
        checkOrderByDelivery(createOrderBaseVo, userLoginInfoDto,
                storeResponseDto, shoppingCartGoodsDto.getTotalAmount(), trackingNo);
        // 查询商城的配送模板信息，校验订单是否满足配送条件  end


    }

    private void checkOrderByDelivery(CreateOrderBaseVo createOrderBaseVo, 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.localCheckReceiveAddress(storeDeliveryInfoDto, createOrderBaseVo);
    }


    /**
     * 校验收货地址是否可配送
     */
    private void localCheckReceiveAddress(StoreDeliveryInfoDto storeDeliveryInfoDto, CreateOrderBaseVo 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);
    }

    private 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;
    }




}
