package com.awspaas.user.apps.donenow_ctt.job;

import com.actionsoft.bpms.commons.database.RowMap;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.bpms.util.TypeUtil;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.Logger;
import com.awspaas.user.apps.donenow_ctt.service.contractServiceAdj;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.time.LocalDate;
import java.util.List;

public class ServiceAutoRenewJob implements Job {
    private static final Logger jobLogger = SDK.getLogAPI().getLogger(ServiceAutoRenewJob.class);//记录日志

    /**
     * 合同服务定数续约
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //当前日期
        UserContext uc = UserContext.fromUID("admin");

        List<RowMap> sales = DBSql.getMaps("SELECT c.CONTRACT_SERVICE_ID, MAX( c.PERIOD_BEGIN_DATE) AS PERIOD_BEGIN_DATE, MAX( c.PERIOD_END_DATE) AS  PERIOD_END_DATE FROM bo_eu_dnctt_contract a JOIN bo_eu_dnctt_contract_service b ON a.ID = b.CONTRACT_ID JOIN bo_eu_dnctt_contract_service_period c ON b.ID = c.CONTRACT_SERVICE_ID WHERE a.AUTO_RENEW = 1  AND b.PERIOD_TYPE<>'609'  GROUP BY c.CONTRACT_SERVICE_ID HAVING MAX( c.PERIOD_BEGIN_DATE)<=DATE_ADD(NOW(), INTERVAL 1 MONTH)");
        for (RowMap sale : sales) {
            String contractServiceId = sale.getString("CONTRACT_SERVICE_ID");
            LocalDate EFFECTIVE_DATE = TypeUtil.convert(sale.getDate("PERIOD_END_DATE"), LocalDate.class);
            contractServiceAdj.getInstance().editServiceSaleEndDate(uc, contractServiceId, EFFECTIVE_DATE.plusYears(1).plusDays(1));
        }

        List<RowMap> purchs = DBSql.getMaps("SELECT c.CONTRACT_SERVICE_ID, MAX( c.PERIOD_BEGIN_DATE) AS PERIOD_BEGIN_DATE, MAX( c.PERIOD_END_DATE) AS  PERIOD_END_DATE FROM bo_eu_dnctt_contract a JOIN bo_eu_dnctt_contract_service b ON a.ID = b.CONTRACT_ID JOIN BO_EU_DNIVT_ORDER_PAYMENT_PLAN c ON b.ID = c.CONTRACT_SERVICE_ID WHERE a.AUTO_RENEW = 1   AND b.PURCHASE_PERIOD_TYPE<>'609' GROUP BY c.CONTRACT_SERVICE_ID HAVING MAX( c.PERIOD_BEGIN_DATE)<=DATE_ADD(NOW(), INTERVAL 1 MONTH)");
        for (RowMap purch : purchs) {
            String contractServiceId = purch.getString("CONTRACT_SERVICE_ID");
            LocalDate EFFECTIVE_DATE = TypeUtil.convert(purch.getDate("PERIOD_END_DATE"), LocalDate.class);
            contractServiceAdj.getInstance().editServicePurchaseEndDate(uc, contractServiceId, EFFECTIVE_DATE.plusYears(1).plusDays(1));
        }
    }

}
