package cn.freemud.xxljob;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.dto.delivery.GetFilterPartnerResponse;
import cn.freemud.entities.dto.delivery.PartnerFilterResponse;
import cn.freemud.entities.dto.openplatform.OrderGetPartnerRequest;
import cn.freemud.entities.vo.OrderCountRequestVo;
import cn.freemud.entities.vo.SendOrderCountsMsg;
import cn.freemud.service.Orderservice;
import cn.freemud.service.thirdparty.MicroOpenplatformClient;
import cn.freemud.utils.AppLogUtil;
import com.freemud.application.sdk.api.constant.ResponseResultEnum;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.response.OrderCountResp;
import com.freemud.sdk.api.assortment.order.domain.ResponseCodeConstant;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author : xh.Z
 * @email : fisherman0510@163.com
 * @Date : 2021/4/26 下午8:27
 * @description :
 */
@Component
//@JobHandler("orderCountJobHandler")
//@Log4j2
public class OrderCountJobHandler extends IJobHandler {

    @Autowired
    private Orderservice orderservice;

    @Autowired
    private MicroOpenplatformClient microOpenplatformClient;

    /**
     * 【ID1028455】 【订单】非码-腾讯有数数据上报V1.0.0
     * 每天6点前上报昨天数据
     *
     * @param param
     * @return
     * @throws Exception
     */
    @Override
    public ReturnT<String> execute(String param) throws Exception {
        String trackingNo = LogThreadLocal.getTrackingNo();

        OrderGetPartnerRequest build1 = OrderGetPartnerRequest.builder().type(3).build();
        // 获取需要 上报的商户号
        try {
            BaseResponse<GetFilterPartnerResponse> filterPartner = microOpenplatformClient.getFilterPartner(build1);
//            AppLogUtil.infoLog("上报商户号查询结果", build1, filterPartner == null ? null : JSON.toJSONString(filterPartner));
            if (filterPartner == null
                    || filterPartner.getResult() == null
                    || !ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(filterPartner.getCode())
                    || filterPartner.getResult().getPartnerFilterVos() == null
                    || filterPartner.getResult().getPartnerFilterVos().isEmpty()) {
                return ReturnT.SUCCESS;
            }
            OrderCountRequestVo orderCountRequestVo = new OrderCountRequestVo();
            Set<String> partners = getPartnerFilter(filterPartner.getResult());
            if (partners.isEmpty()) {
                return ReturnT.SUCCESS;
            }
            orderCountRequestVo.setPartnerIds(partners);
            // 时间设置 前一天
            setBeginAndEndTime(orderCountRequestVo);
            // 查询 自己的数据
            BaseResponse<List<OrderCountResp>> result = orderservice.selectCountOrdersByPartnerIds(orderCountRequestVo, trackingNo);
            if (Objects.isNull(result)) {
                return ReturnT.SUCCESS;
            }
//            AppLogUtil.infoLog("orderCountJobHandlersendreportordercountmsg", orderCountRequestVo, JSON.toJSONString(result));

            if (!ResponseResultEnum.SUCCESS.getCode().equalsIgnoreCase(result.getCode()) || CollectionUtils.isEmpty(result.getResult())) {
                return ReturnT.SUCCESS;
            }
            // 每次推送 只能 50条 让生态端处理
            List<OrderCountResp> orderCounts = result.getResult();
            SendOrderCountsMsg build = SendOrderCountsMsg.builder().partnerRequests(orderCounts).build();
            BaseResponse baseResponse = microOpenplatformClient.addOrderSum(build);
//            AppLogUtil.infoLog("orderCountJobHandlersendreportorderend", JSON.toJSONString(build), JSON.toJSONString(baseResponse));
        } catch (Exception e) {
            AppLogUtil.errorLog("orderCountJobHandlersendreportorderend", null, null,e);
        }
        return ReturnT.SUCCESS;
    }

    private void setBeginAndEndTime(OrderCountRequestVo request) {
        Calendar start = Calendar.getInstance();
        // 取昨天时间 的 00:00:00
        start.add(5, -1);
        start.set(Calendar.HOUR_OF_DAY, 00);
        start.set(Calendar.MINUTE, 0);
        start.set(Calendar.SECOND, 0);


        // 取昨天时间 的 23:59:59
        Calendar end = Calendar.getInstance();
        end.add(5, -1);
        end.set(Calendar.HOUR_OF_DAY, 23);
        end.set(Calendar.MINUTE, 59);
        end.set(Calendar.SECOND, 59);
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        request.setBeginTime(start.getTime());
        request.setEndTmie(end.getTime());
    }


    private Set<String> getPartnerFilter(GetFilterPartnerResponse data) {
        if (data.getPartnerFilterVos() == null || data.getPartnerFilterVos().isEmpty()) {
            return new HashSet<>();
        }
        return data.getPartnerFilterVos().stream().map(PartnerFilterResponse::getPartnerId).collect(Collectors.toSet());
    }
}
