package com.zm.order.tool.server.manager;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.qmai.event.model.EventExecuteTypeEnum;
import com.zm.order.tool.server.constants.EventConstants;
import com.zm.order.tool.server.exception.InnerApiException;
import com.zm.order.tool.server.inner.InnerApiRequest;
import com.zm.order.tool.server.model.Order;
import com.zm.order.tool.server.utils.HttpUtils;
import com.zm.util.dto.Result;
import org.apache.http.HttpException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Description 时间管理
 * @Author: ph
 * @Date: 2019/12/20 15:07
 */
@Component
public class EventManager {

    private static final Logger logger = LoggerFactory.getLogger(EventManager.class);

    private static final String APP_CODE = "order_center";

    private static final String USER_ID = "userId";

    private static final String API_APP_NAME = "eventcenter";

    private static final String API_PATH = "qapi/event-center/event/add";

    /**
     * 开发环境url
     */
    private static final String BASE_URL_DEV = "http://eventcenter.zvcms.com";

    /**
     * 生产环境url
     */
    private static final String BASE_URL_PROD = "http://eventcenter.qmai.cn";

    /**
     * 发送超时完成订单事件
     *
     * @param order
     * @param executeAt
     * @return
     */
    public Result sendDelayCompleteOrderEvent(Order order, Date executeAt) {
        Result result = new Result();
        try {
            Map<String, Object> param = Maps.newHashMap();
            param.put("appCode", APP_CODE);
            param.put("eventType", EventConstants.ORDER_CENTER_DELAY_COMPLETE_ORDER);
            param.put("executeTime", executeAt.getTime());
            param.put("executeType", EventExecuteTypeEnum.SYNC_EVENT.getTypeCode());
            param.put("bizId", order.getOrderNo());
            param.put("version", 0L);
            param.put(USER_ID, order.getUserId().toString());
            InnerApiRequest request = buildRequest(param);
            result = this.call(request);
        } catch (Exception e) {
            logger.error("send auto complete message failed!cause by:{}", e);
            result.setMessage("发送自动完成消息失败");
        }
        return result;
    }

    /**
     * 补推自动评论事件
     *
     * @param order
     * @param executeAt
     * @return
     */
    public Result sendCommentOrderEvent(Order order, Date executeAt) {
        Result result = new Result();
        try {
            Map<String, Object> param = Maps.newHashMap();
            param.put("appCode", APP_CODE);
            param.put("eventType", EventConstants.ORDER_AUTO_COMMENT);
            param.put("executeTime", executeAt.getTime());
            param.put("executeType", EventExecuteTypeEnum.SYNC_EVENT.getTypeCode());
            param.put("bizId", order.getOrderNo());
            param.put("version", 0L);
            param.put(USER_ID, order.getUserId().toString());
            InnerApiRequest request = buildRequest(param);
            result = this.call(request);
        } catch (Exception e) {
            logger.error("send auto comment message failed!cause by:{}", e);
            result.setMessage("发送自动评论消息失败");
        }
        return result;
    }

    private InnerApiRequest buildRequest(Map<String, Object> param) {
        InnerApiRequest request = new InnerApiRequest();
        request.setAppName(API_APP_NAME);
        request.setBaseUri(BASE_URL_PROD);
        request.setPath(API_PATH);
        request.setUrl(BASE_URL_PROD + "/" + API_PATH);
        request.setMethod(HttpUtils.MethodEnum.POST);
        request.setContentType(HttpUtils.ContentTypeEnum.JSON);
        request.setVersion("1.0");
        request.setParams(param);
        return request;
    }


    /**
     * 调用内部接口
     *
     * @param request
     * @return
     */
    private Result call(InnerApiRequest request) {
        CloseableHttpClient httpClient = HttpClients.custom().build();
        HttpUtils.Result httpResult = null;
        try {
            httpResult = HttpUtils.req(httpClient,
                request.getMethod(),
                request.getUrl(),
                request.getParams(),
                request.getHeaders(),
                request.getContentTypeOrDefault());
        } catch (HttpException e) {
            logger.error("cause by:{}", e);
        } finally {
            HttpUtils.closeHttpClient(httpClient);
        }
        logger.info("httpResult:{}",httpResult);
        if (httpResult.isStatusOk()) {
            return JSON.parseObject(httpResult.getResponse(), Result.class);
        }
        throw new InnerApiException("调用内部方法错误");
    }

}
