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.vo.OrderCountRequestVo;
import cn.freemud.entities.vo.SendOrderCountsMsg;
import cn.freemud.service.Orderservice;
import cn.freemud.service.thirdparty.MicroOpenplatformClient;
import cn.freemud.utils.LogUtil;
import com.alibaba.fastjson.JSON;
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.application.sdk.api.ordercenter.response.OrderGetPartnerRequest;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.Set;
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();
        log.info("begin xxl-job by send report msg --------  trackingNo:{}", trackingNo);

        OrderGetPartnerRequest build1 = OrderGetPartnerRequest.builder().type(3).build();
        // 获取需要 上报的商户号
        BaseResponse<GetFilterPartnerResponse> filterPartner = microOpenplatformClient.getFilterPartner(build1);
        if (filterPartner == null || filterPartner.getResult() == null) {
            LogUtil.info("上报商户号没有数据", build1, filterPartner == null ? null : JSON.toJSONString(filterPartner));
            return ReturnT.SUCCESS;
        }
        OrderCountRequestVo orderCountRequestVo = new OrderCountRequestVo();
        Set<String> partnerFilter = getPartnerFilter(filterPartner.getResult());
        orderCountRequestVo.setPartnerIds(partnerFilter);
        // 时间设置 前一天
        setBeginAndEndTime(orderCountRequestVo);
        BaseResponse<List<OrderCountResp>> result = orderservice.selectCountOrdersByPartnerIds(orderCountRequestVo, trackingNo);
        LogUtil.info("orderCountJobHandlersendreportordercountmsg", orderCountRequestVo, result == null ? null : JSON.toJSONString(result));
        if (!ResponseResultEnum.SUCCESS.getCode().equalsIgnoreCase(result.getCode()) || Objects.isNull(result.getResult())) {
            return ReturnT.SUCCESS;
        }
        // 每次推送 只能 50条 让生态端处理
        List<OrderCountResp> orderCounts = result.getResult();
        SendOrderCountsMsg build = SendOrderCountsMsg.builder().orders(orderCounts).build();
        BaseResponse baseResponse = microOpenplatformClient.addOrderSum(build);
        LogUtil.info("orderCountJobHandlersendreportorderend", null,  JSON.toJSONString(baseResponse));
        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().isEmpty()) {
            return null;
        }
        return data.getPartnerFilterVos().stream().map(PartnerFilterResponse::getPartnerId).collect(Collectors.toSet());
    }
}
