package com.yem.wm.im.csrCreditLine.task;

import com.yem.wm.utils.CalendarUtils;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.Date;
import java.util.Map;

/**
 * @Description TODO
 * @Date 2024/1/25 21:02
 * @Created by ZZSLL
 */

public class CsrCreditLineTask extends AbstractTask
{
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException
    {
        // 客户信保额度申请
        DynamicObject[] csrcreditlines = BusinessDataServiceHelper.load("yem_im_csrcreditline", "id, billno, yem_im_info, yem_im_info.yem_paydate1, yem_im_info.yem_countpayback, yem_unused, yem_countdown", null);
        for (DynamicObject dynamicObject : csrcreditlines) {
            // yem_countdown = yem_unused - today
            Date unused = dynamicObject.getDate("yem_unused");
            if (YEM.isNotEmpty(unused)) {

                dynamicObject.set("yem_countdown", -CalendarUtils.calcPayBackCount(unused));
            }

            DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_im_info");
            for (DynamicObject object : collection) {
                Date receivableDate = object.getDate("yem_paydate1");
                if (receivableDate == null) continue;
                object.set("yem_countpayback", CalendarUtils.calcPayBackCount(receivableDate));
            }
        }
        SaveServiceHelper.save(csrcreditlines);

        DynamicObject[] storagetrans = BusinessDataServiceHelper.load("yem_es_storagetrans", "id, billno, yem_creditdetail, yem_creditdetail.yem_paydate1, yem_creditdetail.yem_countpayback", null);
        for (DynamicObject storagetran : storagetrans) {
            DynamicObjectCollection collection = storagetran.getDynamicObjectCollection("yem_creditdetail");
            for (DynamicObject object : collection) {
                Date receivableDate = object.getDate("yem_paydate1");
                if (receivableDate == null) continue;
                object.set("yem_countpayback", CalendarUtils.calcPayBackCount(receivableDate));
            }
        }
        SaveServiceHelper.save(storagetrans);
    }
}
