package com.ywt.outpatient.batch.jobhandler;

import com.xxl.job.core.handler.annotation.XxlJob;
import com.ywt.biz.common.util.Checker;
import com.ywt.biz.common.util.serializers.JsonSerializer;
import com.ywt.gapi.ResultCode;
import com.ywt.gapi.med_equip.MedEquipService;
import com.ywt.gapi.med_equip.TriggerScheduledJobRequest;
import com.ywt.gapi.third.taihe.PhyPayOrderRequest;
import com.ywt.gapi.third.taihe.PhyPayOrderResponse;
import com.ywt.gapi.third.taihe.TaiheService;
import com.ywt.outpatient.domain.entity.center.CheckUpOrder;
import com.ywt.outpatient.domain.entity.center.CheckUpOrderRepository;
import com.ywt.outpatient.domain.models.enums.TriggerScheduledJobEnum;
import com.ywt.outpatient.service.batch.DoctorHisCodeService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * XxlJob开发示例（Bean模式）
 * <p>
 * 开发步骤：
 * 1、任务开发：在Spring Bean实例中，开发Job方法；
 * 2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 * 4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 * @author xuxueli 2019-12-11 21:52:51
 */
@Component
public class OutpatientJob {
    private static Logger logger = LoggerFactory.getLogger(OutpatientJob.class);

    @DubboReference
    MedEquipService medEquipServiceBlockingStub;

    @DubboReference
    private TaiheService taiheServiceBlockingStub;

    @Autowired
    private CheckUpOrderRepository checkUpOrderRepository;

    @Autowired
    private DoctorHisCodeService doctorHisCodeService;


    /**
     * 得到amount分支之前的时间
     *
     * @param amount int型的数据
     * @return {@link Date}
     */
    private Date getBeforeAmountMinuteDate(int amount) {
        //把日期往前移动一天.整数往后推,负数往前移动
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        //这个时间就是日期往后推一天的结果
        calendar.add(Calendar.MINUTE, amount);
        return calendar.getTime();
    }

    private List<CheckUpOrder> getPushFilureList() {
        // 得到前30分钟的时间
        int amount = -30;
        Date date = getBeforeAmountMinuteDate(amount);
        return checkUpOrderRepository.getPushFilureList(date);
    }

    /**
     * 每5分钟执行一次
     */
    @XxlJob("invoiceNotifyReturnEquipJobHandler")
    public void invoiceNotifyReturnEquipJobHandler() {
        logger.info("In invoiceNotifyReturnEquipJobHandler - executing its JOB at " + new Date());
        try {
            // 定时任务处理：24小时归还设备提醒
            medEquipServiceBlockingStub.triggerScheduledJob(TriggerScheduledJobRequest.newBuilder()
                    .setEvent(TriggerScheduledJobEnum.NOTIFY_RETURN_EQUIP.getValue())
                    .build());
        } catch (Exception e) {
            logger.error("invoiceNotifyReturnEquipJobHandler.execute(): {}", e.getMessage(), e);
        }

        logger.info("In invoiceNotifyReturnEquipJobHandler -- two - executing its JOB at " + new Date());
        try {
            // 推送体检缴费订单信息给太和（推送失败的订单）
            List<CheckUpOrder> checkUpOrderList = getPushFilureList();
            if (!Checker.isNone(checkUpOrderList)) {
                checkUpOrderList.forEach(p -> {
                    PhyPayOrderRequest req = PhyPayOrderRequest.newBuilder()
                            .setAdmId(p.getAdmId())
                            .setRegNo(p.getRegNo())
                            .setPayAmount(p.getAmount())
                            .setOrderNo(p.getOrderNo())
                            .setExtOrderNo(Checker.getStringValue(p.getPaymentNo()))
                            .build();
                    PhyPayOrderResponse res = taiheServiceBlockingStub.phyPayOrder(req);
                    if (res.getCode() == ResultCode.SUCCEED.getNumber()) {
                        int status = p.getStatus();
                        status = status & ~4 | 2;
                        p.setStatus(status);
                        p.setUpdateTime(new Date());
                        checkUpOrderRepository.save(p);
                    } else {
                        int status = p.getStatus();
                        status = status | 4;
                        p.setStatus(status);
                        p.setUpdateTime(new Date());
                        checkUpOrderRepository.save(p);
                        logger.error("OutpatientJob#invoiceNotifyReturnEquipJobHandler-通知his失败(): {}", JsonSerializer.toJson(p));
                    }
                });
            }
        } catch (Exception e) {
            logger.error("invoiceNotifyReturnEquipJobHandler.execute(): {}", e.getMessage(), e);
        }
    }

}
