package cn.freemud.service;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.constant.RedisKeyConstant;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.dto.ecology.BookingOrderPayedScene;
import cn.freemud.entities.dto.ecology.InstantOrderPayedScene;
import cn.freemud.entities.dto.ecology.SubscribeMessageRequest;
import cn.freemud.entities.dto.ecology.SubscribeMessageResponse;
import cn.freemud.entities.vo.TakeMealNoticesVO;
import cn.freemud.enums.MessageEventTypeEnum;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.impl.CheckOrder;
import cn.freemud.service.thirdparty.EcologyAdminApplicationClient;
import cn.freemud.utils.DateTimeUtil;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.application.sdk.api.ordercenter.enums.OrderType;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.util.LogUtil;
import com.freemud.application.sdk.api.storecenter.response.StoreResponse;
import com.freemud.sdk.api.assortment.order.request.order.BaseQueryOrderRequest;
import com.freemud.sdk.api.assortment.order.response.order.QueryOrderByIdResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@AllArgsConstructor
@Service
public class CallerService {

//    private final RedisTemplate redisTemplate;
    private final EcologyAdminApplicationClient ecologyAdminApplicationClient;
    private final OrderCenterSdkService orderCenterSdkService;
    private final CheckOrder checkOrder;
    @Autowired
    private LogUtil logUtil;
    @Autowired
    private RedisCache redisCache;


    /**
     * 缓存 待制作杯数量
     *
     * @param vo
     */
    private void cacheTakeMealNotices(TakeMealNoticesVO vo) {
        RedisTemplate redisTemplate = redisCache.getRedisTemplate();
        String redisKey = RedisKeyConstant.notMadeGoodsNumber(vo.getPartnerId(), vo.getStoreCode());
        redisTemplate.boundValueOps(redisKey).set(vo.getCupTotalNum(), 1, TimeUnit.DAYS);
    }

    /**
     * pos -> 推送模板消息
     * 即时单
     * 预约单
     *
     * @param vo
     * @return
     */
    public BaseResponse takeMealNotices(TakeMealNoticesVO vo) {
         cacheTakeMealNotices(vo);
        if (Objects.isNull(vo.getOrderList())) {
            return ResponseUtil.success();
        }
        vo.getOrderList().stream().forEach(orderId -> {
            BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
            baseQueryOrderRequest.setOrderId(orderId);
            baseQueryOrderRequest.setTrackingNo(LogThreadLocal.getTrackingNo());
            baseQueryOrderRequest.setPartnerId(vo.getPartnerId());
            QueryOrderByIdResponse queryOrderByIdResponse = orderCenterSdkService.queryOrderById(baseQueryOrderRequest);
            OrderBeanV1 orderBean = queryOrderByIdResponse.getData();
            if (Objects.isNull(orderBean)) {
                return;
            }
            OrderExtInfoDto extInfoDto = JSONObject.parseObject(orderBean.getExtInfo(), new TypeReference<OrderExtInfoDto>() {
            });
            if (Objects.isNull(extInfoDto.getOpenid())) {
                logUtil.info("订单号:{},没有openId", orderId);
                return;
            }
            StoreResponse storeResponse = checkOrder.getStoreInfo(orderBean.getCompanyId(), orderBean.getShopId(), LogThreadLocal.getTrackingNo());
            if (storeResponse.getBizVO() == null) {
                logUtil.info("订单号:{},商户号:{},没有门店信息", orderId, orderBean.getShopId());
                return;
            }
            List<Integer> takeawayOrderType = Lists.newArrayList(
                    OrderType.RESERVED_EXPRESS.getIndex(),
                    OrderType.GENERAL_EXPRESS.getIndex());
            if (takeawayOrderType.contains(orderBean.getNewOrderType())) {
                // 外卖单不发模板消息
                    return;
            }
            orderBean.setShopAddress(storeResponse.getBizVO().getAddress());
            SubscribeMessageRequest subscribeMessageRequest = new SubscribeMessageRequest();
            subscribeMessageRequest.setMiniAppId(extInfoDto.getAppid());
            subscribeMessageRequest.setOpenIdList(Lists.newArrayList(extInfoDto.getOpenid()));
            //  coco  order_client  2微信小程序 3支付宝小程序 需要转换生态的
            subscribeMessageRequest.setChannel(orderBean.getOrderClient().equals("2") ? 1 : 2);
            boolean reservationOrder = isReservationOrder(orderBean);
            if (reservationOrder) {
                //预约单
                BookingOrderPayedScene scene = new BookingOrderPayedScene();
                scene.setMerchantAddress(orderBean.getShopAddress());
                scene.setMerchantName(orderBean.getShopName());
                scene.setOrderNo(orderId);
                scene.setOrderType(orderBean.getNewOrderType().toString());
                scene.setTakeOrderTime(DateTimeUtil.getCurrentTimeStr());
                subscribeMessageRequest.setBookingOrderTakeReminderScene(scene);
                subscribeMessageRequest.setScene("scene_appoint");
                subscribeMessageRequest.setMessageEventType(MessageEventTypeEnum.BOOKING_ORDER_TAKE_REMINDER.getType());
            } else {
                InstantOrderPayedScene scene = new InstantOrderPayedScene();
                scene.setFriendlyTips("饮品已制作完成，请凭取单号及时到店取单哟！");
                scene.setOrderType(orderBean.getNewOrderType().toString());
                scene.setMerchantAddress(orderBean.getShopAddress());
                scene.setMerchantName(orderBean.getShopName());
                scene.setOrderNo(orderId);
                subscribeMessageRequest.setInstantOrderTakeReminderScene(scene);
                subscribeMessageRequest.setScene("scene_instant");
                subscribeMessageRequest.setMessageEventType(MessageEventTypeEnum.INSTANT_ORDER_TAKE_REMINDER.getType());
            }
            //发送模板消息
            SubscribeMessageResponse subscribeMessageResponse = ecologyAdminApplicationClient.subscribeMessage(subscribeMessageRequest);
            if (!ResponseCodeConstant.RESPONSE_SUCCESS.equals(subscribeMessageResponse.getCode())) {
                logUtil.info("ecologyAdminApplicationClient.subscribeMessage调用失败 ,request:{},body:{}", subscribeMessageResponse, subscribeMessageRequest);
            }
        });

        return ResponseUtil.success();
    }

    /**
     * 是否预约单
     * true 预约单
     *
     * @return
     */
    private boolean isReservationOrder(OrderBeanV1 orderBean) {
        if (Objects.nonNull(orderBean.getGmtExpect())) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;

    }

}
