package nckd.jimin.jyyy.fi.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jimin.jyyy.fi.mservice.impl.SynSapFIServiceImpl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 后台任务插件
 */
public class SynVoucherArchiveTask extends AbstractTask implements Plugin {

    private static final Log logger = LogFactory.getLog(SynVoucherArchiveTask.class);
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        SynSapFIServiceImpl synSapService = new SynSapFIServiceImpl();
        //属性核算组织=是
        QFilter qFilter = new QFilter("fisaccounting", QCP.equals, "1");
        //使用状态=启用
        qFilter.and(new QFilter("enable", QCP.equals, "1"));
        //数据状态=已审核
        qFilter.and(new QFilter("status", QCP.equals, "C"));
        //属性核算组织=是
        qFilter.and(new QFilter("fisaccounting", QCP.equals, "1"));
        DynamicObject[] orgLst = BusinessDataServiceHelper.load("bos_org", "id, number", qFilter.toArray());

        logger.info("------同步SAP凭证归档----------");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        String currentYear = sdf.format(new Date());

        for (DynamicObject org : orgLst) {

            String orgNumber = org.getString("number");
            logger.info("------同步SAP凭证归档 " + orgNumber + "----------");
            Map<String, String> result = synSapService.synVoucherArchiveForSap(orgNumber,  currentYear);

            if (!result.get("code").equals("200")) {
                logger.info("同步SAP凭证归档失败, " + "组织编码：" + orgNumber + "，错误：" + result.get("msg"));
            } else {
                logger.info("同步SAP凭证归档成功, " + "组织编码：" + orgNumber + "，信息：" + result.get("msg"));
            }
        }
    }
}