package cn.freemud.manager;

import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.*;
import cn.freemud.entities.dto.delivery.QueryDeliveryTemplateRequest;
import cn.freemud.entities.dto.delivery.QueryDeliveryTemplateResponse;
import cn.freemud.entities.dto.ecology.VirtualBindStoreResponse;
import cn.freemud.entities.dto.ecology.VirtualStoreRequest;
import cn.freemud.entities.dto.product.ProductInfo;
import cn.freemud.entities.dto.promotion.*;
import cn.freemud.entities.vo.CreateOrderVo;
import cn.freemud.entities.vo.QueryGroupHistoryRequest;
import cn.freemud.entities.vo.QuerySpellGroupRequest;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.thirdparty.*;
import com.alibaba.fastjson.JSON;
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.membercenter.request.QueryReceiveAddressRequest;
import com.freemud.application.sdk.api.membercenter.response.QueryReceiveAddressResponse;
import com.freemud.application.sdk.api.membercenter.service.MemberCenterService;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wanghanghang
 * @title: SpellGroupOrderDataManager
 * @projectName order-group
 * @description: TODO
 * @date 2021/4/15下午3:45
 */
@Component
@Slf4j
public class SpellGroupOrderDataManager {

    @Autowired
    private StoreItemClient storeItemClient;

    @Autowired
    private PromotionDiscountClient promotionDiscountClient;

    //会员SDK
    @Autowired
    private MemberCenterService memberCenterService;

    //门店SDK
    @Autowired
    private StoreCenterService storeCenterService;

    @Autowired
    private DeliveryFeiginClient deliveryFeiginClient;

    @Autowired
    private EcologyAdminApplicationClient ecologyAdminApplicationClient;

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


    /**
     * 查询地址信息
     *
     * @param receiveId
     * @param partnerId
     * @param trackingNo
     * @return
     */
    public QueryReceiveAddressResponse queryOrderReceiveAddress(String receiveId, String partnerId, String trackingNo) {
        QueryReceiveAddressRequest request = new QueryReceiveAddressRequest(receiveId, partnerId);
        BaseResponse<QueryReceiveAddressResponse> queryReceiveAddressResponse = memberCenterService.queryReceiveAddressById(request, trackingNo);
        if (!ResponseResult.SUCCESS.getCode().equals(queryReceiveAddressResponse.getCode()) || queryReceiveAddressResponse.getData() == null) {
            return null;
        }
        QueryReceiveAddressResponse receiveAddressResult = queryReceiveAddressResponse.getData();
        return receiveAddressResult;
    }

    /**
     * 查询商品信息
     *
     * @param createSpellGroupOrderDto
     * @return
     */
    public List<ProductInfo> queryProductInfos(CreateSpellGroupOrderDto createSpellGroupOrderDto) {
        GetProductInfoDto getProductInfoReq = new GetProductInfoDto();
        List<String> proIds = new ArrayList<>();
        createSpellGroupOrderDto.getSpellGroupProductList().forEach(proInfo -> {
            proIds.add(proInfo.getProductId());
        });
        getProductInfoReq.setProductIds(proIds);
        getProductInfoReq.setPartnerId(createSpellGroupOrderDto.getPartnerId());
        getProductInfoReq.setShopId(createSpellGroupOrderDto.getStoreId());
        getProductInfoReq.setProductInfoType(1);
        ProductInfosDto productInfosReps = storeItemClient.listProductInfos(getProductInfoReq);
        if (!ResponseResult.SUCCESS.getCode().equals(productInfosReps.getErrcode().toString()) || productInfosReps.getData() == null) {
           return null;
        }
        return productInfosReps.getData().getProducts();
    }

    /**
     * 查询算价信息
     *
     * @param calculationDiscountRequestDto
     * @return
     */
    public ActivityCalculationDiscountResponseDto queryCalculationDiscount(CalculationDiscountRequestDto calculationDiscountRequestDto) {
        ActivityCalculationDiscountResponseDto activityCalculationDiscountResponseDto = promotionDiscountClient.calculationDiscountSharing(calculationDiscountRequestDto);
        return activityCalculationDiscountResponseDto;

    }

    /**
     * 查询配送费
     *
     * @param queryDeliveryTemplateRequest
     * @return
     */
    public QueryDeliveryTemplateResponse queryDeliveryTemplate(QueryDeliveryTemplateRequest queryDeliveryTemplateRequest) {
        QueryDeliveryTemplateResponse queryDeliveryTemplateResponse = deliveryFeiginClient.queryDeliveryTemplate(queryDeliveryTemplateRequest);
        if (!ResponseResult.SUCCESS.getCode().equals(queryDeliveryTemplateResponse.getCode().toString()) || queryDeliveryTemplateResponse.getData() == null) {
            return null;
        }
        return queryDeliveryTemplateResponse;
    }

    /**
     * 拼团订单，支付回调时开团参团
     * @param orderBean
     * @param userLoginInfoDto
     * @param wxappid
     * @return
     */
    public GroupWorkJoinResponse groupWorkJoin(QueryOrdersResponseDto.DataBean.OrderBean orderBean,AssortmentCustomerInfoVo userLoginInfoDto,String wxappid){
        GroupWorkJoinRequest groupWorkJoinRequest = new GroupWorkJoinRequest();
        QueryOrdersResponseDto.DataBean.OrderBean.ProductBean productBean = orderBean.getProductList().get(0);
        groupWorkJoinRequest.setActivityCode(orderBean.getOrderSettlementDetailList().get(0).getExternalObjectId());
        groupWorkJoinRequest.setGoodId(productBean.getProductId());
        groupWorkJoinRequest.setGoodName(productBean.getProductName());
        groupWorkJoinRequest.setGroupId(orderBean.getSpellGroupCode());
        groupWorkJoinRequest.setHeadUrl(userLoginInfoDto.getPhotoUrl());
        groupWorkJoinRequest.setOrderId(orderBean.getOid());
        groupWorkJoinRequest.setUserId(orderBean.getUserId());
        groupWorkJoinRequest.setUserName(orderBean.getUserName());
        groupWorkJoinRequest.setPartnerCode(orderBean.getCompanyId());
        groupWorkJoinRequest.setAppId(wxappid);
        groupWorkJoinRequest.setMobile(StringUtils.isEmpty(userLoginInfoDto.getMobile()) ? orderBean.getPhone() : userLoginInfoDto.getMobile());
        log.info(JSON.toJSONString(groupWorkJoinRequest));
        GroupWorkJoinResponse groupWorkJoinResponse = promotionDiscountClient.groupWorkJoin(groupWorkJoinRequest);
        return groupWorkJoinResponse;
    }

    /**
     * 查询团信息
     * @param groupId
     * @param partnerId
     * @param userId
     * @return
     */
    public QueryHistoryGroupVO queryHistoryByGroupId(String groupId, String partnerId,String userId){
        QueryGroupHistoryRequest querySpellGroupRequest = new QueryGroupHistoryRequest();
        List<String> groups = new ArrayList<>();
        groups.add(groupId);
        querySpellGroupRequest.setPartnerId(partnerId);
        querySpellGroupRequest.setGroupIds(groups);
        querySpellGroupRequest.setUserId(userId);
        QueryHistoryGroupVOResponse queryHistory = promotionDiscountClient.queryHistory(querySpellGroupRequest);
        if(!ResponseResult.SUCCESS.getCode().equals(queryHistory.getStatusCode()) || queryHistory.getResult() == null){
            return null;
        }
        return queryHistory.getResult().get(0);
    }

    /**
     * 创建拼团订单，校验团信息
     * @param groupId
     * @param userId
     * @param activityCode
     * @param partnerId
     * @return
     */
    public QuerySpellGroupVoResponse queryByGroupIdNew(String groupId, String userId, String activityCode, String partnerId){
        QuerySpellGroupRequest querySpellGroupRequest = new QuerySpellGroupRequest();
        querySpellGroupRequest.setGroupId(groupId);
        querySpellGroupRequest.setPartnerId(partnerId);
        querySpellGroupRequest.setUserId(userId);
        querySpellGroupRequest.setActivityCode(activityCode);
        QuerySpellGroupVoResponse querySpellGroupVoResponse = promotionDiscountClient.queryByGroupId(querySpellGroupRequest);
        return querySpellGroupVoResponse;
    }

    /**
     * 获取商城门店id
     */
    public VirtualBindStoreResponse change2BindMallShopId(String appId) {
        VirtualStoreRequest virtualStoreRequest = new VirtualStoreRequest();
        virtualStoreRequest.setPlatformAppId(appId);
        virtualStoreRequest.setType("microMall");
        cn.freemud.base.entity.BaseResponse<VirtualBindStoreResponse> virtualBindStoreResponse = ecologyAdminApplicationClient.getBuyBindVirtualStore(virtualStoreRequest);
        if(virtualBindStoreResponse == null || virtualBindStoreResponse.getResult() == null || StringUtils.isBlank(virtualBindStoreResponse.getResult().getStoreId())) {
            return null;
        }
        return virtualBindStoreResponse.getResult();
    }
}
