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

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

import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.awspaas.user.apps.donenow_ctt.service.contractService.LocalDateYYYYMMDD;
import static com.awspaas.user.apps.donenow_ctt.service.contractService.getLocalDate;


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

    /**
     * 合同服务定数续约
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        /*
        定期服务合同上加了自动续约功能，如果勾选，则其下的定期服务（不是一次性服务），需要自动修改计费结束时间，延长一年。触发时机：最后一个完整周期的开始日期
         */

        //当前日期
        String nowDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        LocalDate next2Year = LocalDate.now().plusYears(2);//两年后

        List<RowMap> list = DBSql.getMaps("SELECT a.ID, a.BINDID, a.START_DATE, a.END_DATE, b.EFFECTIVE_DATE, c.CONTRACT_SERVICE_ID, MIN(c.PERIOD_BEGIN_DATE) AS PERIOD_BEGIN_DATE, MIN(c.PERIOD_END_DATE) AS PERIOD_END_DATE, COUNT(c.ID) AS CNT 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 c.PERIOD_END_DATE>='" + nowDate + "' GROUP BY a.ID, a.BINDID, a.START_DATE, a.END_DATE, b.EFFECTIVE_DATE, c.CONTRACT_SERVICE_ID HAVING COUNT(c.ID)<=1 ORDER BY PERIOD_BEGIN_DATE DESC");

        UserContext uc = UserContext.fromUID("admin");
        contractService serviceOp = contractService.getInstance();

        for (RowMap rowMap : list) {
            String contractId = rowMap.getString("ID");
            String bindId = rowMap.getString("BINDID");
            String startDate = rowMap.getString("START_DATE");
            String endDate = rowMap.getString("END_DATE");
            String effectiveDate = rowMap.getString("EFFECTIVE_DATE");
            String contractServiceId = rowMap.getString("CONTRACT_SERVICE_ID");
            String periodBeginDate = rowMap.getString("PERIOD_BEGIN_DATE");
            String periodEndDate = rowMap.getString("PERIOD_END_DATE");
            int cnt = rowMap.getInt("CNT");

            System.out.println("contractId:" + contractId);
            BO contract = SDK.getBOAPI().get("BO_EU_DNCTT_CONTRACT", contractId);

            if (contract != null) {
                LocalDate START_DATE = getLocalDate(contract.get("START_DATE"));//服务开始日期
                LocalDate END_DATE = getLocalDate(contract.get("END_DATE"));//合同结束日期
                END_DATE = END_DATE.plusYears(1);
                if (END_DATE.isBefore(next2Year)) {
                    contract.set("END_DATE", LocalDateYYYYMMDD(END_DATE));
                    SDK.getBOAPI().update("BO_EU_DNCTT_CONTRACT", contract);

                    jobLogger.info("合同:" + contract.getString("NAME") + "[" + contract.getString("NO") + "]开始续约");

                    jobLogger.info("原结束日期：" + endDate + "----新结束日期：" + LocalDateYYYYMMDD(END_DATE));

                    Connection conn = null;
                    try {
                        conn = DBSql.open();
                        conn.setAutoCommit(false);

                        //获取服务列表
                        List<BO> serviceList = SDK.getBOAPI().query("BO_EU_DNCTT_CONTRACT_SERVICE").connection(conn).addQuery("CONTRACT_ID =", contract.get("ID")).list();

                        for (BO service : serviceList) {
                            //   boolean isAutoRenew = serviceOp.ServiceAutoRenew(uc, service, END_DATE, conn);
                            serviceOp.ServiceAdjustEndDate(uc, service, END_DATE, conn);
                        }

                        conn.commit();
                    } catch (SQLException e) {

                        jobLogger.info("AddServiceServiceBundle--error--失败。。。" + e.getMessage());

                        e.printStackTrace();

                        try {
                            conn.rollback();
                        } catch (SQLException ex) {
                            throw new RuntimeException(ex);
                        }

                    } finally {
                        if (conn != null) DBSql.close(conn);
                    }

                    jobLogger.info("合同:" + contract.getString("NAME") + "[" + contract.getString("NO") + "]结束续约");
                }
            }
        }

    }
}
