package shkd.repc.recon.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;

/**
 * 合同结算审核
 */
public class ConsettlebillAuditOPPlugin extends AbstractOperationServicePlugIn {

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        //合同结算审核时,将结算日期按照合同保证金年限计算合同最终付款日期反写合同
        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject dataEntity = dataEntities[0];//合同结算
        Date bizdate = dataEntity.getDate("bizdate");//结算日期
        DynamicObject contractbill = dataEntity.getDynamicObject("contractbill");//合同f7
        if (null != contractbill) {
            DynamicObject contractbills = BusinessDataServiceHelper.loadSingle(contractbill.getPkValue(), "recon_contractbill");
            if (null != contractbills) {
                //保证金明细
                DynamicObjectCollection qeug_bondentrys = contractbills.getDynamicObjectCollection("qeug_bondentry");
                for (DynamicObject qeugBondentry : qeug_bondentrys) {
                    String qeugYear = qeugBondentry.getString("qeug_year");//年限
                    //1月、2月、3月、4月、5月、半年、1年、2年、3年、4年、5年
                    int year = Integer.parseInt(qeugYear);
                    Date updatedDate = updateBizDate(bizdate, year);
                    if (updatedDate != null) {
                        qeugBondentry.set("qeug_finalpaymentdate", updatedDate); // 设置最终付款日期
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{contractbills});
            }
        }
    }

    private Date updateBizDate(Date bizdate, int monthsToAdd) {
        if (bizdate != null) {
            LocalDate localBizDate = bizdate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // 将 Date 转换为 LocalDate
            LocalDate newBizDate = localBizDate.plusMonths(monthsToAdd); // 根据传入的月份数加上月份
            return Date.from(newBizDate.atStartOfDay(ZoneId.systemDefault()).toInstant()); // 返回更新后的 Date 类型
        }
        return null;
    }
}